Skip to content

Commit

Permalink
impl detect_secret_hash_algo_v2 function
Browse files Browse the repository at this point in the history
  • Loading branch information
laruh committed Nov 27, 2024
1 parent cf76cab commit c1a5063
Show file tree
Hide file tree
Showing 8 changed files with 83 additions and 48 deletions.
15 changes: 15 additions & 0 deletions mm2src/coins/lp_coins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ pub mod watcher_common;

pub mod coin_errors;
use coin_errors::{MyAddressError, ValidatePaymentError, ValidatePaymentFut, ValidatePaymentResult};
use crypto::secret_hash_algo::SecretHashAlgo;

#[doc(hidden)]
#[cfg(test)]
Expand Down Expand Up @@ -3563,6 +3564,20 @@ impl MmCoinEnum {
pub fn is_eth(&self) -> bool { matches!(self, MmCoinEnum::EthCoin(_)) }

fn is_platform_coin(&self) -> bool { self.ticker() == self.platform_ticker() }

pub fn maker_secret_hash_algo_v2(&self) -> SecretHashAlgo {
match self {
MmCoinEnum::EthCoin(_) => SecretHashAlgo::SHA256,
_ => SecretHashAlgo::DHASH160,
}
}

pub fn taker_secret_hash_algo_v2(&self) -> SecretHashAlgo {
match self {
MmCoinEnum::EthCoin(_) => SecretHashAlgo::SHA256,
_ => SecretHashAlgo::DHASH160,
}
}
}

#[async_trait]
Expand Down
1 change: 1 addition & 0 deletions mm2src/crypto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub mod hw_rpc_task;
mod key_derivation;
pub mod mnemonic;
pub mod privkey;
pub mod secret_hash_algo;
mod shared_db_id;
mod slip21;
mod standard_hd_path;
Expand Down
39 changes: 39 additions & 0 deletions mm2src/crypto/src/secret_hash_algo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use bitcrypto::{dhash160, sha256};
use derive_more::Display;
use std::convert::TryFrom;

/// Algorithm used to hash swap secret.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Default)]
pub enum SecretHashAlgo {
/// ripemd160(sha256(secret))
#[default]
DHASH160 = 1,
/// sha256(secret)
SHA256 = 2,
}

#[derive(Debug, Display)]
pub struct UnsupportedSecretHashAlgo(u8);

impl std::error::Error for UnsupportedSecretHashAlgo {}

impl TryFrom<u8> for SecretHashAlgo {
type Error = UnsupportedSecretHashAlgo;

fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
1 => Ok(SecretHashAlgo::DHASH160),
2 => Ok(SecretHashAlgo::SHA256),
unsupported => Err(UnsupportedSecretHashAlgo(unsupported)),
}
}
}

impl SecretHashAlgo {
pub fn hash_secret(&self, secret: &[u8]) -> Vec<u8> {
match self {
SecretHashAlgo::DHASH160 => dhash160(secret).take().into(),
SecretHashAlgo::SHA256 => sha256(secret).take().into(),
}
}
}
11 changes: 6 additions & 5 deletions mm2src/mm2_main/src/lp_ordermatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,17 +75,18 @@ use crate::lp_network::{broadcast_p2p_msg, request_any_relay, request_one_peer,
use crate::lp_swap::maker_swap_v2::{self, MakerSwapStateMachine, MakerSwapStorage};
use crate::lp_swap::taker_swap_v2::{self, TakerSwapStateMachine, TakerSwapStorage};
use crate::lp_swap::{calc_max_maker_vol, check_balance_for_maker_swap, check_balance_for_taker_swap,
check_other_coin_balance_for_swap, detect_secret_hash_algo, dex_fee_amount_from_taker_coin,
check_other_coin_balance_for_swap, detect_secret_hash_algo_v2, dex_fee_amount_from_taker_coin,
generate_secret, get_max_maker_vol, insert_new_swap_to_db, is_pubkey_banned, lp_atomic_locktime,
p2p_keypair_and_peer_id_to_broadcast, p2p_private_and_peer_id_to_broadcast, run_maker_swap,
run_taker_swap, swap_v2_topic, AtomicLocktimeVersion, CheckBalanceError, CheckBalanceResult,
CoinVolumeInfo, MakerSwap, RunMakerSwapInput, RunTakerSwapInput, SecretHashAlgo,
SwapConfirmationsSettings, TakerSwap, LEGACY_SWAP_TYPE};
CoinVolumeInfo, MakerSwap, RunMakerSwapInput, RunTakerSwapInput, SwapConfirmationsSettings,
TakerSwap, LEGACY_SWAP_TYPE};

#[cfg(any(test, feature = "run-docker-tests"))]
use crate::lp_swap::taker_swap::FailAt;

pub use best_orders::{best_orders_rpc, best_orders_rpc_v2};
use crypto::secret_hash_algo::SecretHashAlgo;
pub use orderbook_depth::orderbook_depth_rpc;
pub use orderbook_rpc::{orderbook_rpc, orderbook_rpc_v2};

Expand Down Expand Up @@ -3046,7 +3047,7 @@ fn lp_connect_start_bob(ctx: MmArc, maker_match: MakerMatch, maker_order: MakerO
}

let params = StateMachineParams {
secret_hash_algo: &detect_secret_hash_algo(&maker_coin, &taker_coin),
secret_hash_algo: &detect_secret_hash_algo_v2(&maker_coin, &taker_coin),
uuid: &uuid,
my_conf_settings: &my_conf_settings,
locktime: &lock_time,
Expand Down Expand Up @@ -3285,7 +3286,7 @@ fn lp_connected_alice(ctx: MmArc, taker_order: TakerOrder, taker_match: TakerMat
},
};
let params = StateMachineParams {
secret_hash_algo: &detect_secret_hash_algo(&maker_coin, &taker_coin),
secret_hash_algo: &detect_secret_hash_algo_v2(&maker_coin, &taker_coin),
uuid: &uuid,
my_conf_settings: &my_conf_settings,
locktime: &locktime,
Expand Down
53 changes: 15 additions & 38 deletions mm2src/mm2_main/src/lp_swap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ use super::lp_network::P2PRequestResult;
use crate::lp_network::{broadcast_p2p_msg, Libp2pPeerId, P2PProcessError, P2PProcessResult, P2PRequestError};
use crate::lp_swap::maker_swap_v2::{MakerSwapStateMachine, MakerSwapStorage};
use crate::lp_swap::taker_swap_v2::{TakerSwapStateMachine, TakerSwapStorage};
use bitcrypto::{dhash160, sha256};
use bitcrypto::sha256;
use coins::{lp_coinfind, lp_coinfind_or_err, CoinFindError, DexFee, MmCoin, MmCoinEnum, TradeFee, TransactionEnum};
use common::log::{debug, warn};
use common::now_sec;
Expand All @@ -83,7 +83,6 @@ use secp256k1::{PublicKey, SecretKey, Signature};
use serde::Serialize;
use serde_json::{self as json, Value as Json};
use std::collections::{HashMap, HashSet};
use std::convert::TryFrom;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use std::str::FromStr;
Expand Down Expand Up @@ -118,6 +117,7 @@ mod trade_preimage;

pub use check_balance::{check_other_coin_balance_for_swap, CheckBalanceError, CheckBalanceResult};
use coins::utxo::utxo_standard::UtxoStandardCoin;
use crypto::secret_hash_algo::SecretHashAlgo;
use crypto::CryptoCtx;
use keys::{KeyPair, SECP_SIGN, SECP_VERIFY};
use maker_swap::MakerSwapEvent;
Expand Down Expand Up @@ -1624,42 +1624,6 @@ pub async fn active_swaps_rpc(ctx: MmArc, req: Json) -> Result<Response<Vec<u8>>
Ok(try_s!(Response::builder().body(res)))
}

/// Algorithm used to hash swap secret.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Default)]
pub enum SecretHashAlgo {
/// ripemd160(sha256(secret))
#[default]
DHASH160 = 1,
/// sha256(secret)
SHA256 = 2,
}

#[derive(Debug, Display)]
pub struct UnsupportedSecretHashAlgo(u8);

impl std::error::Error for UnsupportedSecretHashAlgo {}

impl TryFrom<u8> for SecretHashAlgo {
type Error = UnsupportedSecretHashAlgo;

fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
1 => Ok(SecretHashAlgo::DHASH160),
2 => Ok(SecretHashAlgo::SHA256),
unsupported => Err(UnsupportedSecretHashAlgo(unsupported)),
}
}
}

impl SecretHashAlgo {
fn hash_secret(&self, secret: &[u8]) -> Vec<u8> {
match self {
SecretHashAlgo::DHASH160 => dhash160(secret).take().into(),
SecretHashAlgo::SHA256 => sha256(secret).take().into(),
}
}
}

// Todo: Maybe add a secret_hash_algo method to the SwapOps trait instead
/// Selects secret hash algorithm depending on types of coins being swapped
#[cfg(not(target_arch = "wasm32"))]
Expand All @@ -1684,6 +1648,19 @@ pub fn detect_secret_hash_algo(maker_coin: &MmCoinEnum, taker_coin: &MmCoinEnum)
}
}

pub fn detect_secret_hash_algo_v2(maker_coin: &MmCoinEnum, taker_coin: &MmCoinEnum) -> SecretHashAlgo {
let maker_algo = maker_coin.maker_secret_hash_algo_v2();
let taker_algo = taker_coin.taker_secret_hash_algo_v2();
if matches!(
(maker_algo, taker_algo),
(SecretHashAlgo::SHA256, _) | (_, SecretHashAlgo::SHA256)
) {
SecretHashAlgo::SHA256
} else {
SecretHashAlgo::DHASH160
}
}

pub struct SwapPubkeys {
pub maker: String,
pub taker: String,
Expand Down
5 changes: 3 additions & 2 deletions mm2src/mm2_main/src/lp_swap/maker_swap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use super::{broadcast_my_swap_status, broadcast_p2p_tx_msg, broadcast_swap_msg_e
get_locked_amount, recv_swap_msg, swap_topic, taker_payment_spend_deadline, tx_helper_topic,
wait_for_maker_payment_conf_until, AtomicSwap, LockedAmount, MySwapInfo, NegotiationDataMsg,
NegotiationDataV2, NegotiationDataV3, RecoveredSwap, RecoveredSwapAction, SavedSwap, SavedSwapIo,
SavedTradeFee, SecretHashAlgo, SwapConfirmationsSettings, SwapError, SwapMsg, SwapPubkeys, SwapTxDataMsg,
SwapsContext, TransactionIdentifier, INCLUDE_REFUND_FEE, NO_REFUND_FEE, TAKER_FEE_VALIDATION_ATTEMPTS,
SavedTradeFee, SwapConfirmationsSettings, SwapError, SwapMsg, SwapPubkeys, SwapTxDataMsg, SwapsContext,
TransactionIdentifier, INCLUDE_REFUND_FEE, NO_REFUND_FEE, TAKER_FEE_VALIDATION_ATTEMPTS,
TAKER_FEE_VALIDATION_RETRY_DELAY_SECS, WAIT_CONFIRM_INTERVAL_SEC};
use crate::lp_dispatcher::{DispatcherContext, LpEvents};
use crate::lp_network::subscribe_to_topic;
Expand All @@ -25,6 +25,7 @@ use common::log::{debug, error, info, warn};
use common::{bits256, executor::Timer, now_ms, DEX_FEE_ADDR_RAW_PUBKEY};
use common::{now_sec, wait_until_sec};
use crypto::privkey::SerializableSecp256k1Keypair;
use crypto::secret_hash_algo::SecretHashAlgo;
use crypto::CryptoCtx;
use futures::{compat::Future01CompatExt, select, FutureExt};
use keys::KeyPair;
Expand Down
3 changes: 2 additions & 1 deletion mm2src/mm2_main/src/lp_swap/maker_swap_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use super::{swap_v2_topic, LockedAmount, LockedAmountInfo, SavedTradeFee, SwapsC
NEGOTIATION_TIMEOUT_SEC};
use crate::lp_swap::maker_swap::MakerSwapPreparedParams;
use crate::lp_swap::swap_lock::SwapLock;
use crate::lp_swap::{broadcast_swap_v2_msg_every, check_balance_for_maker_swap, recv_swap_v2_msg, SecretHashAlgo,
use crate::lp_swap::{broadcast_swap_v2_msg_every, check_balance_for_maker_swap, recv_swap_v2_msg,
SwapConfirmationsSettings, TransactionIdentifier, MAKER_SWAP_V2_TYPE, MAX_STARTED_AT_DIFF};
use crate::lp_swap::{swap_v2_pb::*, NO_REFUND_FEE};
use async_trait::async_trait;
Expand All @@ -17,6 +17,7 @@ use common::executor::{AbortableSystem, Timer};
use common::log::{debug, error, info, warn};
use common::{now_sec, Future01CompatExt, DEX_FEE_ADDR_RAW_PUBKEY};
use crypto::privkey::SerializableSecp256k1Keypair;
use crypto::secret_hash_algo::SecretHashAlgo;
use keys::KeyPair;
use mm2_core::mm_ctx::MmArc;
use mm2_err_handle::prelude::*;
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 @@ -3,8 +3,7 @@ use super::{LockedAmount, LockedAmountInfo, SavedTradeFee, SwapsContext, TakerSw
NEGOTIATE_SEND_INTERVAL, NEGOTIATION_TIMEOUT_SEC};
use crate::lp_swap::swap_lock::SwapLock;
use crate::lp_swap::{broadcast_swap_v2_msg_every, check_balance_for_taker_swap, recv_swap_v2_msg, swap_v2_topic,
SecretHashAlgo, SwapConfirmationsSettings, TransactionIdentifier, MAX_STARTED_AT_DIFF,
TAKER_SWAP_V2_TYPE};
SwapConfirmationsSettings, TransactionIdentifier, MAX_STARTED_AT_DIFF, TAKER_SWAP_V2_TYPE};
use crate::lp_swap::{swap_v2_pb::*, NO_REFUND_FEE};
use async_trait::async_trait;
use bitcrypto::{dhash160, sha256};
Expand All @@ -18,6 +17,7 @@ use common::executor::{AbortableSystem, Timer};
use common::log::{debug, error, info, warn};
use common::{Future01CompatExt, DEX_FEE_ADDR_RAW_PUBKEY};
use crypto::privkey::SerializableSecp256k1Keypair;
use crypto::secret_hash_algo::SecretHashAlgo;
use keys::KeyPair;
use mm2_core::mm_ctx::MmArc;
use mm2_err_handle::prelude::*;
Expand Down

0 comments on commit c1a5063

Please sign in to comment.