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 bdk::{
};
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 @@ pub fn build_deposit_tx(deposit: &DepositArgs) -> anyhow::Result<()> {

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())?;
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,
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 @@ impl WIF {
{
Ok(())
} else {
Err(StacksError::InvalidData("WIF is invalid"))
Err(StacksError::InvalidData("WIF is invalid".into()))
}
}

Expand All @@ -62,7 +62,7 @@ impl WIF {
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())),
}
}

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
76 changes: 76 additions & 0 deletions stacks-core/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::{
address::{AddressVersion, StacksAddress},
codec::Codec,
contract_name::ContractName,
StacksError,
};

#[derive(PartialEq, Eq, Debug, Clone)]
Expand Down Expand Up @@ -111,6 +112,38 @@ impl From<StacksAddress> for PrincipalData {
}
}

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)))
}
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"
))),
}
}
}

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

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(),
"Could not crackford32 encode or decode: Invalid C32 address: ST123"
CAGS295 marked this conversation as resolved.
Show resolved Hide resolved
);

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

assert_eq!(
result.unwrap_err().to_string(),
"Invalid data: Invalid contract name"
);
}
}
Loading