Skip to content

Commit

Permalink
Merge pull request #1592 from input-output-hk/jpraynaud/upgrade-bech3…
Browse files Browse the repository at this point in the history
…2-crate

Upgrade `bech32` crate
  • Loading branch information
jpraynaud authored Mar 27, 2024
2 parents f1bd564 + 3fdf308 commit 950636b
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 24 deletions.
14 changes: 10 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions mithril-common/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "mithril-common"
version = "0.3.22"
version = "0.3.23"
description = "Common types, interfaces, and utilities for Mithril nodes."
authors = { workspace = true }
edition = { workspace = true }
Expand Down Expand Up @@ -28,7 +28,7 @@ harness = false
[dependencies]
anyhow = "1.0.79"
async-trait = "0.1.77"
bech32 = "0.9.1"
bech32 = "0.11.0"
blake2 = "0.10.6"
chrono = { version = "0.4.33", features = ["serde"] }
ciborium = "0.2.2"
Expand Down
13 changes: 5 additions & 8 deletions mithril-common/src/chain_observer/cli_observer.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use anyhow::{anyhow, Context};
use async_trait::async_trait;
use bech32::{self, ToBase32, Variant};
use hex::FromHex;
use nom::IResult;
use rand_core::RngCore;
Expand All @@ -12,7 +11,7 @@ use tokio::process::Command;

use crate::chain_observer::interface::{ChainObserver, ChainObserverError};
use crate::chain_observer::{ChainAddress, TxDatum};
use crate::crypto_helper::{KESPeriod, OpCert, SerDeShelleyFileFormat};
use crate::crypto_helper::{encode_bech32, KESPeriod, OpCert, SerDeShelleyFileFormat};
use crate::entities::{Epoch, StakeDistribution};
use crate::{CardanoNetwork, StdResult};

Expand Down Expand Up @@ -365,14 +364,12 @@ impl CardanoCliChainObserver {

for (k, v) in pools_data.iter() {
let pool_id_hex = k;
let pool_id_bech32 = bech32::encode(
let pool_id_bech32 = encode_bech32(
"pool",
Vec::from_hex(pool_id_hex.as_bytes())
.map_err(|e| ChainObserverError::General(e.into()))?
.to_base32(),
Variant::Bech32,
&Vec::from_hex(pool_id_hex.as_bytes())
.map_err(|e| ChainObserverError::General(e.into()))?,
)
.map_err(|e| ChainObserverError::General(e.into()))?;
.map_err(ChainObserverError::General)?;
let stakes = v
.get("stakeMark")
.ok_or(ChainObserverError::InvalidContent(anyhow!(
Expand Down
8 changes: 3 additions & 5 deletions mithril-common/src/chain_observer/pallas_observer.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use anyhow::{anyhow, Context};
use async_trait::async_trait;
use bech32::{self, ToBase32, Variant};
use pallas_addresses::Address;
use pallas_codec::utils::{Bytes, CborWrap, TagWrap};
use pallas_network::{
Expand All @@ -25,7 +24,7 @@ use std::{

use crate::{
chain_observer::{interface::*, ChainAddress, TxDatum},
crypto_helper::{KESPeriod, OpCert},
crypto_helper::{encode_bech32, KESPeriod, OpCert},
entities::{Epoch, StakeDistribution},
CardanoNetwork, StdResult,
};
Expand Down Expand Up @@ -202,11 +201,10 @@ impl PallasChainObserver {

/// Returns the stake pool hash from the given bytestring.
fn get_stake_pool_hash(&self, key: &Bytes) -> Result<String, ChainObserverError> {
let pool_hash = bech32::encode("pool", key.to_base32(), Variant::Bech32)
let pool_id_bech32 = encode_bech32("pool", key)
.map_err(|err| anyhow!(err))
.with_context(|| "PallasChainObserver failed to encode stake pool hash")?;

Ok(pool_hash)
Ok(pool_id_bech32)
}

/// Fetches the current stake distribution using the provided `statequery` client.
Expand Down
6 changes: 2 additions & 4 deletions mithril-common/src/crypto_helper/cardano/opcert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@

use super::SerDeShelleyFileFormat;
use crate::crypto_helper::cardano::ProtocolRegistrationErrorWrapper;
use crate::crypto_helper::ProtocolPartyId;
use crate::crypto_helper::{encode_bech32, ProtocolPartyId};

use bech32::{self, ToBase32, Variant};
use blake2::{digest::consts::U28, Blake2b, Digest};
use ed25519_dalek::{
Signature as EdSignature, Signer, SigningKey as EdSecretKey, Verifier,
Expand Down Expand Up @@ -117,8 +116,7 @@ impl OpCert {
hasher.update(self.cold_vk.as_bytes());
let mut pool_id = [0u8; 28];
pool_id.copy_from_slice(hasher.finalize().as_bytes());
bech32::encode("pool", pool_id.to_base32(), Variant::Bech32)
.map_err(|_| OpCertError::PoolAddressEncoding)
encode_bech32("pool", &pool_id).map_err(|_| OpCertError::PoolAddressEncoding)
}

/// Compute protocol party id as hash
Expand Down
26 changes: 25 additions & 1 deletion mithril-common/src/crypto_helper/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ use serde::de::DeserializeOwned;
use serde::Serialize;
use thiserror::Error;

use anyhow::anyhow;
use bech32::{self, Bech32, Hrp};

use crate::StdResult;

/// Error raised when the encoding or decoding fails
#[derive(Error, Debug)]
#[error("Codec error: {msg}")]
Expand Down Expand Up @@ -56,11 +61,18 @@ where
})
}

/// Encode to bech32 given Human Readable Part (hrp) and data
pub fn encode_bech32(human_readable_part: &str, data: &[u8]) -> StdResult<String> {
let human_readable_part = Hrp::parse(human_readable_part).map_err(|e| anyhow!(e))?;
bech32::encode::<Bech32>(human_readable_part, data).map_err(|e| anyhow!(e))
}

#[cfg(test)]
pub mod tests {
use hex::FromHex;
use serde::{Deserialize, Serialize};

use super::{key_decode_hex, key_encode_hex};
use super::{encode_bech32, key_decode_hex, key_encode_hex};

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct TestSerialize {
Expand All @@ -78,4 +90,16 @@ pub mod tests {
key_decode_hex(&test_to_serialize_hex).expect("unexpected hex decoding error");
assert_eq!(test_to_serialize, test_to_serialize_restored);
}

#[test]
fn test_bech32_encode() {
let hrp = "pool";
let data =
Vec::from_hex("edfa208d441511f9595ba80e8f3a7b07b6a80cbc9dda9d8e9d1dc039").unwrap();
let encoded_data = encode_bech32(hrp, &data).unwrap();
let expected_encoded_data =
"pool1ahazpr2yz5gljk2m4q8g7wnmq7m2sr9unhdfmr5arhqrjnntwdz".to_string();

assert_eq!(expected_encoded_data, encoded_data);
}
}

0 comments on commit 950636b

Please sign in to comment.