Skip to content

Commit

Permalink
provide trait AddrToString to be able to properly convert address to …
Browse files Browse the repository at this point in the history
…string for StoredNegotiationData
  • Loading branch information
laruh committed Jan 7, 2025
1 parent 62afdff commit a1bb59f
Show file tree
Hide file tree
Showing 6 changed files with 46 additions and 30 deletions.
6 changes: 4 additions & 2 deletions mm2src/coins/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6980,8 +6980,6 @@ impl ParseCoinAssocTypes for EthCoin {
}
}

fn addr_to_string(&self, address: &Self::Address) -> String { eth_addr_to_hex(address) }

fn parse_address(&self, address: &str) -> Result<Self::Address, Self::AddressParseError> {
// crate `Address::from_str` supports both address variants with and without `0x` prefix
Address::from_str(address).map_to_mm(|e| EthAssocTypesError::InvalidHexString(e.to_string()))
Expand Down Expand Up @@ -7016,6 +7014,10 @@ impl ToBytes for Address {
fn to_bytes(&self) -> Vec<u8> { self.0.to_vec() }
}

impl AddrToString for Address {
fn addr_to_string(&self) -> String { eth_addr_to_hex(self) }
}

impl ToBytes for BigUint {
fn to_bytes(&self) -> Vec<u8> { self.to_bytes_be() }
}
Expand Down
20 changes: 11 additions & 9 deletions mm2src/coins/lp_coins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1534,10 +1534,20 @@ pub trait ToBytes {
fn to_bytes(&self) -> Vec<u8>;
}

/// Should convert coin `Self::Address` type into a properly formatted string representation.
///
/// Don't use `to_string` directly on `Self::Address` types in generic TPU code!
/// It may produce abbreviated or non-standard formats (e.g. `ethereum_types::Address` will be like this `0x7cc9…3874`),
/// which are not guaranteed to be parsable back into the original `Address` type.
/// This function should ensure the resulting string is consistently formatted and fully reversible.
pub trait AddrToString {
fn addr_to_string(&self) -> String;
}

/// Defines associated types specific to each coin (Pubkey, Address, etc.)
#[async_trait]
pub trait ParseCoinAssocTypes {
type Address: Send + Sync + fmt::Display;
type Address: Send + Sync + fmt::Display + AddrToString;
type AddressParseError: fmt::Debug + Send + fmt::Display;
type Pubkey: ToBytes + Send + Sync;
type PubkeyParseError: fmt::Debug + Send + fmt::Display;
Expand All @@ -1550,14 +1560,6 @@ pub trait ParseCoinAssocTypes {

async fn my_addr(&self) -> Self::Address;

/// Converts coin `Self::Address` type into a properly formatted string representation.
///
/// Don't use `to_string` directly on `Self::Address` types in generic TPU code!
/// It may produce abbreviated or non-standard formats (e.g. `ethereum_types::Address` will be like this `0x7cc9…3874`),
/// which are not guaranteed to be parsable back into the original `Address` type.
/// This function should ensure the resulting string is consistently formatted and fully reversible.
fn addr_to_string(&self, address: &Self::Address) -> String;

fn parse_address(&self, address: &str) -> Result<Self::Address, Self::AddressParseError>;

fn parse_pubkey(&self, pubkey: &[u8]) -> Result<Self::Pubkey, Self::PubkeyParseError>;
Expand Down
21 changes: 15 additions & 6 deletions mm2src/coins/test_coin.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#![allow(clippy::all)]

use super::{CoinBalance, CommonSwapOpsV2, FindPaymentSpendError, FundingTxSpend, HistorySyncState, MarketCoinOps,
MmCoin, RawTransactionFut, RawTransactionRequest, RefundTakerPaymentArgs, SearchForFundingSpendErr,
SwapOps, TradeFee, TransactionEnum, TransactionFut};
use super::{AddrToString, CoinBalance, CommonSwapOpsV2, FindPaymentSpendError, FundingTxSpend, HistorySyncState,
MarketCoinOps, MmCoin, RawTransactionFut, RawTransactionRequest, RefundTakerPaymentArgs,
SearchForFundingSpendErr, SwapOps, TradeFee, TransactionEnum, TransactionFut};
use crate::coin_errors::ValidatePaymentResult;
use crate::{coin_errors::MyAddressError, BalanceFut, CanRefundHtlc, CheckIfMyPaymentSentArgs, CoinFutSpawner,
ConfirmPaymentInput, FeeApproxStage, FoundSwapTxSpend, GenPreimageResult, GenTakerFundingSpendArgs,
Expand All @@ -29,6 +29,7 @@ use mm2_number::{BigDecimal, MmNumber};
use mocktopus::macros::*;
use rpc::v1::types::Bytes as BytesJson;
use serde_json::Value as Json;
use std::fmt::{Display, Formatter};
use std::ops::Deref;
use std::sync::Arc;

Expand Down Expand Up @@ -441,9 +442,19 @@ impl ToBytes for TestSig {
fn to_bytes(&self) -> Vec<u8> { vec![] }
}

pub struct TestAddress {}

impl AddrToString for TestAddress {
fn addr_to_string(&self) -> String { unimplemented!() }
}

impl Display for TestAddress {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { unimplemented!() }
}

#[async_trait]
impl ParseCoinAssocTypes for TestCoin {
type Address = String;
type Address = TestAddress;
type AddressParseError = String;
type Pubkey = TestPubkey;
type PubkeyParseError = String;
Expand All @@ -456,8 +467,6 @@ impl ParseCoinAssocTypes for TestCoin {

async fn my_addr(&self) -> Self::Address { todo!() }

fn addr_to_string(&self, address: &Self::Address) -> String { unimplemented!() }

fn parse_address(&self, address: &str) -> Result<Self::Address, Self::AddressParseError> { todo!() }

fn parse_pubkey(&self, pubkey: &[u8]) -> Result<Self::Pubkey, Self::PubkeyParseError> { unimplemented!() }
Expand Down
14 changes: 8 additions & 6 deletions mm2src/coins/utxo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,10 @@ use utxo_signer::{TxProvider, TxProviderError, UtxoSignTxError, UtxoSignTxResult
use self::rpc_clients::{electrum_script_hash, ElectrumClient, ElectrumConnectionSettings, EstimateFeeMethod,
EstimateFeeMode, NativeClient, UnspentInfo, UnspentMap, UtxoRpcClientEnum, UtxoRpcError,
UtxoRpcFut, UtxoRpcResult};
use super::{big_decimal_from_sat_unsigned, BalanceError, BalanceFut, BalanceResult, CoinBalance, CoinFutSpawner,
CoinsContext, DerivationMethod, FeeApproxStage, FoundSwapTxSpend, HistorySyncState, KmdRewardsDetails,
MarketCoinOps, MmCoin, NumConversError, NumConversResult, PrivKeyActivationPolicy, PrivKeyPolicy,
PrivKeyPolicyNotAllowed, RawTransactionFut, TradeFee, TradePreimageError, TradePreimageFut,
use super::{big_decimal_from_sat_unsigned, AddrToString, BalanceError, BalanceFut, BalanceResult, CoinBalance,
CoinFutSpawner, CoinsContext, DerivationMethod, FeeApproxStage, FoundSwapTxSpend, HistorySyncState,
KmdRewardsDetails, MarketCoinOps, MmCoin, NumConversError, NumConversResult, PrivKeyActivationPolicy,
PrivKeyPolicy, PrivKeyPolicyNotAllowed, RawTransactionFut, TradeFee, TradePreimageError, TradePreimageFut,
TradePreimageResult, Transaction, TransactionDetails, TransactionEnum, TransactionErr,
UnexpectedDerivationMethod, VerificationError, WithdrawError, WithdrawRequest};
use crate::coin_balance::{EnableCoinScanPolicy, EnabledCoinBalanceParams, HDAddressBalanceScanner};
Expand Down Expand Up @@ -1028,6 +1028,10 @@ impl ToBytes for Signature {
fn to_bytes(&self) -> Vec<u8> { self.to_vec() }
}

impl AddrToString for Address {
fn addr_to_string(&self) -> String { self.to_string() }
}

#[async_trait]
impl<T: UtxoCommonOps> ParseCoinAssocTypes for T {
type Address = Address;
Expand All @@ -1053,8 +1057,6 @@ impl<T: UtxoCommonOps> ParseCoinAssocTypes for T {
}
}

fn addr_to_string(&self, address: &Self::Address) -> String { address.to_string() }

fn parse_address(&self, address: &str) -> Result<Self::Address, Self::AddressParseError> {
self.address_from_str(address)
}
Expand Down
11 changes: 6 additions & 5 deletions mm2src/mm2_main/src/lp_swap/maker_swap_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ use crate::lp_swap::{broadcast_swap_v2_msg_every, check_balance_for_maker_swap,
use crate::lp_swap::{swap_v2_pb::*, NO_REFUND_FEE};
use async_trait::async_trait;
use bitcrypto::{dhash160, sha256};
use coins::{CanRefundHtlc, ConfirmPaymentInput, DexFee, FeeApproxStage, FundingTxSpend, GenTakerFundingSpendArgs,
GenTakerPaymentSpendArgs, MakerCoinSwapOpsV2, MmCoin, ParseCoinAssocTypes, RefundMakerPaymentSecretArgs,
RefundMakerPaymentTimelockArgs, SearchForFundingSpendErr, SendMakerPaymentArgs, SwapTxTypeWithSecretHash,
TakerCoinSwapOpsV2, ToBytes, TradePreimageValue, Transaction, TxPreimageWithSig, ValidateTakerFundingArgs};
use coins::{AddrToString, CanRefundHtlc, ConfirmPaymentInput, DexFee, FeeApproxStage, FundingTxSpend,
GenTakerFundingSpendArgs, GenTakerPaymentSpendArgs, MakerCoinSwapOpsV2, MmCoin, ParseCoinAssocTypes,
RefundMakerPaymentSecretArgs, RefundMakerPaymentTimelockArgs, SearchForFundingSpendErr,
SendMakerPaymentArgs, SwapTxTypeWithSecretHash, TakerCoinSwapOpsV2, ToBytes, TradePreimageValue,
Transaction, TxPreimageWithSig, ValidateTakerFundingArgs};
use common::executor::abortable_queue::AbortableQueue;
use common::executor::{AbortableSystem, Timer};
use common::log::{debug, error, info, warn};
Expand Down Expand Up @@ -924,7 +925,7 @@ impl<MakerCoin: MmCoin + MakerCoinSwapOpsV2, TakerCoin: MmCoin + TakerCoinSwapOp
taker_coin_htlc_pub: state_machine.taker_coin.derive_htlc_pubkey_v2_bytes(&unique_data),
maker_coin_swap_contract: state_machine.maker_coin.swap_contract_address().map(|bytes| bytes.0),
taker_coin_swap_contract: state_machine.taker_coin.swap_contract_address().map(|bytes| bytes.0),
taker_coin_address: state_machine.taker_coin.addr_to_string(&taker_coin_address),
taker_coin_address: taker_coin_address.addr_to_string(),
};
debug!("Sending maker negotiation message {:?}", maker_negotiation_msg);
let swap_msg = SwapMessage {
Expand Down
4 changes: 2 additions & 2 deletions mm2src/mm2_main/src/lp_swap/taker_swap_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::lp_swap::{broadcast_swap_v2_msg_every, check_balance_for_taker_swap,
use crate::lp_swap::{swap_v2_pb::*, NO_REFUND_FEE};
use async_trait::async_trait;
use bitcrypto::{dhash160, sha256};
use coins::{CanRefundHtlc, ConfirmPaymentInput, DexFee, FeeApproxStage, GenTakerFundingSpendArgs,
use coins::{AddrToString, CanRefundHtlc, ConfirmPaymentInput, DexFee, FeeApproxStage, GenTakerFundingSpendArgs,
GenTakerPaymentSpendArgs, MakerCoinSwapOpsV2, MmCoin, ParseCoinAssocTypes, RefundFundingSecretArgs,
RefundTakerPaymentArgs, SendTakerFundingArgs, SpendMakerPaymentArgs, SwapTxTypeWithSecretHash,
TakerCoinSwapOpsV2, ToBytes, TradeFee, TradePreimageValue, Transaction, TxPreimageWithSig,
Expand Down Expand Up @@ -1184,7 +1184,7 @@ impl<MakerCoin: ParseCoinAssocTypes, TakerCoin: ParseCoinAssocTypes> Negotiation
StoredNegotiationData {
maker_payment_locktime: self.maker_payment_locktime,
maker_secret_hash: self.maker_secret_hash.clone().into(),
taker_coin_maker_address: self.taker_coin_maker_address.to_string(),
taker_coin_maker_address: self.taker_coin_maker_address.addr_to_string(),
maker_coin_htlc_pub_from_maker: self.maker_coin_htlc_pub_from_maker.to_bytes().into(),
taker_coin_htlc_pub_from_maker: self.taker_coin_htlc_pub_from_maker.to_bytes().into(),
maker_coin_swap_contract: self.maker_coin_swap_contract.clone().map(|b| b.into()),
Expand Down

0 comments on commit a1bb59f

Please sign in to comment.