Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: more forgiving dot address parsing #3938

Merged
merged 1 commit into from
Sep 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

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

31 changes: 29 additions & 2 deletions api/lib/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use std::sync::Arc;
use std::{str::FromStr, sync::Arc};

use anyhow::{anyhow, bail, Context, Result};
use async_trait::async_trait;
use cf_chains::{
address::EncodedAddress,
dot::PolkadotAccountId,
evm::{to_evm_address, Address as EthereumAddress},
CcmChannelMetadata, ForeignChain,
};
Expand Down Expand Up @@ -337,7 +338,8 @@ pub trait BrokerApi: SignedExtrinsicApi {
pub fn clean_foreign_chain_address(chain: ForeignChain, address: &str) -> Result<EncodedAddress> {
Ok(match chain {
ForeignChain::Ethereum => EncodedAddress::Eth(clean_hex_address(address)?),
ForeignChain::Polkadot => EncodedAddress::Dot(clean_hex_address(address)?),
ForeignChain::Polkadot =>
EncodedAddress::Dot(PolkadotAccountId::from_str(address).map(|id| *id.aliased_ref())?),
ForeignChain::Bitcoin => EncodedAddress::Btc(address.as_bytes().to_vec()),
})
}
Expand Down Expand Up @@ -495,4 +497,29 @@ mod test_key_generation {

assert_eq!(*original, restored);
}

#[test]
fn test_dot_address_decoding() {
assert_eq!(
clean_foreign_chain_address(
ForeignChain::Polkadot,
"126PaS7kDWTdtiojd556gD4ZPcxj7KbjrMJj7xZ5i6XKfARE"
)
.unwrap(),
clean_foreign_chain_address(
ForeignChain::Polkadot,
"0x305875a3025d8be7f7048a280aba2bd571126fc171986adc1af58d1f4e02f15e"
)
.unwrap(),
);
assert_eq!(
clean_foreign_chain_address(
ForeignChain::Polkadot,
"126PaS7kDWTdtiojd556gD4ZPcxj7KbjrMJj7xZ5i6XKfARF"
)
.unwrap_err()
.to_string(),
anyhow!("Address is neither valid ss58: 'Invalid checksum' nor hex: 'Invalid character 'P' at position 3'").to_string(),
);
}
}
2 changes: 2 additions & 0 deletions state-chain/chains/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ bech32 = { default-features = false, version = '0.9.1' }
base58 = '0.2.0'

# Other
anyhow = { version = '1.0', default-features = false, optional = true }
hex = { default-features = false, version = '0.4' }
hex-literal = { version = '0.4.1', default-features = false }
serde = { version = '1.0.126', default-features = false, features = [
Expand Down Expand Up @@ -73,6 +74,7 @@ std = [
'sp-core/std',
'sp-core/full_crypto',
'dep:ss58-registry',
'dep:anyhow',
]
runtime-benchmarks = [
'cf-primitives/runtime-benchmarks',
Expand Down
12 changes: 12 additions & 0 deletions state-chain/chains/src/dot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub mod benchmarking;
#[cfg(feature = "std")]
pub mod serializable_address;

use cf_utilities::SliceToArray;
#[cfg(feature = "std")]
pub use serializable_address::*;

Expand Down Expand Up @@ -104,6 +105,17 @@ impl PolkadotPair {
)]
pub struct PolkadotAccountId([u8; 32]);

impl TryFrom<Vec<u8>> for PolkadotAccountId {
type Error = ();

fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
if value.len() != 32 {
return Err(())
}
Ok(Self(value.as_array()))
}
}

impl PolkadotAccountId {
pub const fn from_aliased(account_id: [u8; 32]) -> Self {
Self(account_id)
Expand Down
33 changes: 29 additions & 4 deletions state-chain/chains/src/dot/serializable_address.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::*;
use anyhow::anyhow;
use frame_support::sp_runtime::AccountId32;

#[derive(Debug, Clone)]
Expand All @@ -7,6 +8,24 @@ pub struct SubstrateNetworkAddress {
account_id: AccountId32,
}

impl FromStr for PolkadotAccountId {
type Err = anyhow::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
from_ss58check_with_version(s)
.and_then(TryInto::try_into)
.or_else(|base58_err| {
cf_utilities::clean_hex_address::<PolkadotAccountId>(s).map_err(|hex_err| {
anyhow!(
"Address is neither valid ss58: '{}' nor hex: '{}'",
base58_err,
hex_err.root_cause()
)
})
})
}
}

impl SubstrateNetworkAddress {
pub fn polkadot(account_id: impl Into<AccountId32>) -> Self {
Self {
Expand All @@ -23,15 +42,21 @@ impl serde::Serialize for SubstrateNetworkAddress {
}
}

fn from_ss58check_with_version(
s: &str,
) -> Result<SubstrateNetworkAddress, sp_core::crypto::PublicError> {
use sp_core::crypto::Ss58Codec;
<AccountId32 as Ss58Codec>::from_ss58check_with_version(s).map(
|(account_id, format_specifier)| SubstrateNetworkAddress { format_specifier, account_id },
)
}

impl<'de> serde::Deserialize<'de> for SubstrateNetworkAddress {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use sp_core::crypto::Ss58Codec;
let s = String::deserialize(deserializer)?;
<AccountId32 as Ss58Codec>::from_ss58check_with_version(&s)
.map(|(account_id, format_specifier)| Self { format_specifier, account_id })
from_ss58check_with_version(&String::deserialize(deserializer)?)
.map_err(|_| serde::de::Error::custom("Invalid SS58 address"))
}
}
Expand Down