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

Implement TryFrom<String> for PrincipalData #300

Merged
merged 11 commits into from
Oct 21, 2023
2 changes: 1 addition & 1 deletion devenv/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ You can access the [Stacks Explorer](https://github.com/hirosystems/explorer)
at:

```
http://127.0.0.1:3020/?chain=testnet
http://127.0.0.1:3020/?chain=testnet&api=http://127.0.0.1:3999
```
It's important to use the above URL, as it can parse blocks properly.

Expand Down
7 changes: 3 additions & 4 deletions sbtc-cli/src/commands/deposit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
};
use clap::Parser;
use sbtc_core::operations::op_return::deposit::build_deposit_transaction;
use stacks_core::address::StacksAddress;
use stacks_core::utils::PrincipalData;
use url::Url;

use crate::commands::utils;
Expand Down Expand Up @@ -68,13 +68,12 @@

wallet.sync(&blockchain, SyncOptions::default())?;

let recipient_address =
StacksAddress::try_from(deposit.recipient.as_str())?;
let stx_recipient = PrincipalData::try_from(deposit.recipient.to_string())?;

Check warning on line 71 in sbtc-cli/src/commands/deposit.rs

View check run for this annotation

Codecov / codecov/patch

sbtc-cli/src/commands/deposit.rs#L71

Added line #L71 was not covered by tests
friedger marked this conversation as resolved.
Show resolved Hide resolved
let sbtc_wallet_address = BitcoinAddress::from_str(&deposit.sbtc_wallet)?;

let tx = build_deposit_transaction(
wallet,
recipient_address.into(),
stx_recipient,

Check warning on line 76 in sbtc-cli/src/commands/deposit.rs

View check run for this annotation

Codecov / codecov/patch

sbtc-cli/src/commands/deposit.rs#L76

Added line #L76 was not covered by tests
sbtc_wallet_address,
deposit.amount,
deposit.network,
Expand Down
4 changes: 2 additions & 2 deletions stacks-core/src/crypto/wif.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
{
Ok(())
} else {
Err(StacksError::InvalidData("WIF is invalid"))
Err(StacksError::InvalidData("WIF is invalid".into()))

Check warning on line 56 in stacks-core/src/crypto/wif.rs

View check run for this annotation

Codecov / codecov/patch

stacks-core/src/crypto/wif.rs#L56

Added line #L56 was not covered by tests
}
}

Expand All @@ -62,7 +62,7 @@
match WIFPrefix::from_repr(self.0[0]) {
Some(WIFPrefix::Mainnet) => Ok(Network::Mainnet),
Some(WIFPrefix::Testnet) => Ok(Network::Testnet),
_ => Err(StacksError::InvalidData("Unknown network byte")),
_ => Err(StacksError::InvalidData("Unknown network byte".into())),

Check warning on line 65 in stacks-core/src/crypto/wif.rs

View check run for this annotation

Codecov / codecov/patch

stacks-core/src/crypto/wif.rs#L65

Added line #L65 was not covered by tests
}
}

Expand Down
2 changes: 1 addition & 1 deletion stacks-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ pub enum StacksError {
CodecError(#[from] CodecError),
#[error("Invalid data: {0}")]
/// Invalid data
InvalidData(&'static str),
InvalidData(String),
/// BIP32 Error
#[error("BIP32 error: {0}")]
BIP32(#[from] bdk::bitcoin::util::bip32::Error),
Expand Down
79 changes: 79 additions & 0 deletions stacks-core/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
address::{AddressVersion, StacksAddress},
codec::Codec,
contract_name::ContractName,
StacksError,
};

#[derive(PartialEq, Eq, Debug, Clone)]
Expand Down Expand Up @@ -111,6 +112,38 @@
}
}

impl TryFrom<String> for PrincipalData {
type Error = StacksError;

fn try_from(value: String) -> Result<Self, Self::Error> {
let parts: Vec<&str> = value.split('.').collect();

match parts.len() {
1 => {
let address = StacksAddress::try_from(parts[0])?;
Ok(Self::Standard(StandardPrincipalData::from(address)))

Check warning on line 124 in stacks-core/src/utils.rs

View check run for this annotation

Codecov / codecov/patch

stacks-core/src/utils.rs#L123-L124

Added lines #L123 - L124 were not covered by tests
}
2 => {
let address = StacksAddress::try_from(parts[0])?;
let contract_name =
ContractName::new(parts[1]).map_err(|err| {
StacksError::InvalidData(format!(
"Invalid contract name from {value}: {err}"
))
})?;

Ok(Self::Contract(
StandardPrincipalData::from(address),
contract_name,
))
}
_ => Err(StacksError::InvalidData(format!(
"Principal data from {value} may contain at most 1 dot character"
))),

Check warning on line 142 in stacks-core/src/utils.rs

View check run for this annotation

Codecov / codecov/patch

stacks-core/src/utils.rs#L140-L142

Added lines #L140 - L142 were not covered by tests
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -212,4 +245,50 @@

assert_eq!(deserialized, expected_principal_data);
}

#[test]
fn should_principal_data_try_from_string() {
// addr = ST000000000000000000002AMW42H
let addr = StacksAddress::new(
AddressVersion::TestnetSingleSig,
Hash160Hasher::default(),
);
let principal_data: PrincipalData = PrincipalData::try_from(
"ST000000000000000000002AMW42H.helloworld".to_string(),
)
.unwrap();

assert_eq!(
principal_data,
PrincipalData::Contract(
StandardPrincipalData(addr.version(), addr.clone()),
ContractName::new("helloworld").unwrap(),
)
);
}

#[test]
fn should_fail_to_convert_invalid_string_to_principal_data() {
// try invalid address
let mut result =
PrincipalData::try_from("ST123.helloworld".to_string());

assert_eq!(
result.unwrap_err().to_string(),
StacksError::C32Error(crate::c32::C32Error::InvalidAddress(
"ST123".into()
))
.to_string()
);

// try contract name with a space
result = PrincipalData::try_from(
"ST000000000000000000002AMW42H.hello contract".to_string(),
);

assert_eq!(
result.unwrap_err().to_string(),
StacksError::InvalidData("Invalid contract name from ST000000000000000000002AMW42H.hello contract: Format should follow the contract name specification".into()).to_string()
);
}
}
Loading