Skip to content

Commit

Permalink
improve p2p stack (#1755)
Browse files Browse the repository at this point in the history
Signed-off-by: ozkanonur <work@onurozkan.dev>
  • Loading branch information
onur-ozkan committed Apr 24, 2023
1 parent 547a30a commit e21c9d6
Show file tree
Hide file tree
Showing 6 changed files with 36 additions and 15 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
- - Break the loop right after processing any of `SWAP_PREFIX`, `WATCHER_PREFIX`, `TX_HELPER_PREFIX` topic.
- An issue was fixed where we don't have to wait for all EVM nodes to sync the latest account nonce [#1757](https://github.com/KomodoPlatform/atomicDEX-API/pull/1757)
- optimized dev and release compilation profiles and removed ci [#1759](https://github.com/KomodoPlatform/atomicDEX-API/pull/1759)

- use OS generated secrets for cryptographically secure randomness in `maker_swap` and `tendermint_coin::get_sender_trade_fee_for_denom` [#1753](https://github.com/KomodoPlatform/atomicDEX-API/pull/1753)

## v1.0.2-beta - 2023-04-11

Expand Down
14 changes: 10 additions & 4 deletions mm2src/coins/tendermint/tendermint_coin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ use mm2_number::MmNumber;
use parking_lot::Mutex as PaMutex;
use primitives::hash::H256;
use prost::{DecodeError, Message};
use rand::{thread_rng, Rng};
use rpc::v1::types::Bytes as BytesJson;
use serde_json::{self as json, Value as Json};
use std::collections::HashMap;
Expand Down Expand Up @@ -1461,7 +1460,11 @@ impl TendermintCoin {
amount: BigDecimal,
) -> TradePreimageResult<TradeFee> {
const TIME_LOCK: u64 = 1750;
let sec: [u8; 32] = thread_rng().gen();

let mut sec = [0u8; 32];
common::os_rng(&mut sec).map_err(|e| MmError::new(TradePreimageError::InternalError(e.to_string())))?;
drop_mutability!(sec);

let to_address = account_id_from_pubkey_hex(&self.account_prefix, DEX_FEE_ADDR_PUBKEY)
.map_err(|e| MmError::new(TradePreimageError::InternalError(e.into_inner().to_string())))?;

Expand Down Expand Up @@ -2627,7 +2630,6 @@ pub mod tendermint_coin_tests {
use common::{block_on, DEX_FEE_ADDR_RAW_PUBKEY};
use cosmrs::proto::cosmos::tx::v1beta1::{GetTxRequest, GetTxResponse, GetTxsEventResponse};
use crypto::privkey::key_pair_from_seed;
use rand::{thread_rng, Rng};
use std::mem::discriminant;

pub const IRIS_TESTNET_HTLC_PAIR1_SEED: &str = "iris test seed";
Expand Down Expand Up @@ -2731,7 +2733,11 @@ pub mod tendermint_coin_tests {
const UAMOUNT: u64 = 1;
let amount: cosmrs::Decimal = UAMOUNT.into();
let amount_dec = big_decimal_from_sat_unsigned(UAMOUNT, coin.decimals);
let sec: [u8; 32] = thread_rng().gen();

let mut sec = [0u8; 32];
common::os_rng(&mut sec).unwrap();
drop_mutability!(sec);

let time_lock = 1000;

let create_htlc_tx = coin
Expand Down
4 changes: 4 additions & 0 deletions mm2src/common/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ use futures01::{future, Future};
use http::header::CONTENT_TYPE;
use http::Response;
use parking_lot::{Mutex as PaMutex, MutexGuard as PaMutexGuard};
use rand::RngCore;
use rand::{rngs::SmallRng, SeedableRng};
use serde::{de, ser};
use serde_json::{self as json, Value as Json};
Expand Down Expand Up @@ -747,6 +748,9 @@ pub fn writeln(line: &str) {

pub fn small_rng() -> SmallRng { SmallRng::seed_from_u64(now_ms()) }

#[inline(always)]
pub fn os_rng(dest: &mut [u8]) -> Result<(), rand::Error> { rand::rngs::OsRng.try_fill_bytes(dest) }

#[derive(Debug, Clone)]
/// Ordered from low to height inclusive range.
pub struct OrdRange<T>(RangeInclusive<T>);
Expand Down
11 changes: 10 additions & 1 deletion mm2src/mm2_main/src/lp_ordermatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2992,6 +2992,15 @@ fn lp_connect_start_bob(ctx: MmArc, maker_match: MakerMatch, maker_order: MakerO
if let Err(e) = insert_new_swap_to_db(ctx.clone(), maker_coin.ticker(), taker_coin.ticker(), uuid, now).await {
error!("Error {} on new swap insertion", e);
}

let secret = match MakerSwap::generate_secret() {
Ok(s) => s.into(),
Err(e) => {
error!("Error {} on secret generation", e);
return;
},
};

let maker_swap = MakerSwap::new(
ctx.clone(),
alice,
Expand All @@ -3005,7 +3014,7 @@ fn lp_connect_start_bob(ctx: MmArc, maker_match: MakerMatch, maker_order: MakerO
taker_coin,
lock_time,
maker_order.p2p_privkey.map(SerializableSecp256k1Keypair::into_inner),
MakerSwap::generate_secret().into(),
secret,
);
run_maker_swap(RunMakerSwapInput::StartNew(maker_swap), ctx).await;
};
Expand Down
8 changes: 5 additions & 3 deletions mm2src/mm2_main/src/lp_swap/maker_swap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ use mm2_err_handle::prelude::*;
use mm2_number::{BigDecimal, MmNumber};
use parking_lot::Mutex as PaMutex;
use primitives::hash::{H256, H264};
use rand::Rng;
use rpc::v1::types::{Bytes as BytesJson, H256 as H256Json, H264 as H264Json};
use std::any::TypeId;
use std::path::PathBuf;
Expand Down Expand Up @@ -238,8 +237,11 @@ impl MakerSwap {
#[inline]
fn r(&self) -> RwLockReadGuard<MakerSwapMut> { self.mutable.read().unwrap() }

#[inline]
pub fn generate_secret() -> [u8; 32] { rand::thread_rng().gen() }
pub fn generate_secret() -> Result<[u8; 32], rand::Error> {
let mut sec = [0u8; 32];
common::os_rng(&mut sec)?;
Ok(sec)
}

#[inline]
fn secret_hash(&self) -> Vec<u8> {
Expand Down
12 changes: 6 additions & 6 deletions mm2src/mm2_main/tests/docker_tests/swap_watcher_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -683,7 +683,7 @@ fn test_watcher_validate_taker_payment_eth() {
let wait_for_confirmation_until = now_ms() / 1000 + time_lock_duration;
let time_lock = wait_for_confirmation_until as u32;
let amount = BigDecimal::from_str("0.01").unwrap();
let secret_hash = dhash160(&MakerSwap::generate_secret());
let secret_hash = dhash160(&MakerSwap::generate_secret().unwrap());
let watcher_reward = Some(
block_on(watcher_reward_amount(
&MmCoinEnum::from(taker_coin.clone()),
Expand Down Expand Up @@ -809,7 +809,7 @@ fn test_watcher_validate_taker_payment_eth() {
}

// Used to get wrong swap id
let wrong_secret_hash = dhash160(&MakerSwap::generate_secret());
let wrong_secret_hash = dhash160(&MakerSwap::generate_secret().unwrap());
let error = taker_coin
.watcher_validate_taker_payment(coins::WatcherValidatePaymentInput {
payment_tx: taker_payment.tx_hex(),
Expand Down Expand Up @@ -957,7 +957,7 @@ fn test_watcher_validate_taker_payment_erc20() {
let wait_for_confirmation_until = now_ms() / 1000 + time_lock_duration;
let time_lock = wait_for_confirmation_until as u32;

let secret_hash = dhash160(&MakerSwap::generate_secret());
let secret_hash = dhash160(&MakerSwap::generate_secret().unwrap());
let watcher_reward = Some(
block_on(watcher_reward_amount(
&MmCoinEnum::from(taker_coin.clone()),
Expand Down Expand Up @@ -1082,7 +1082,7 @@ fn test_watcher_validate_taker_payment_erc20() {
}

// Used to get wrong swap id
let wrong_secret_hash = dhash160(&MakerSwap::generate_secret());
let wrong_secret_hash = dhash160(&MakerSwap::generate_secret().unwrap());
let error = taker_coin
.watcher_validate_taker_payment(WatcherValidatePaymentInput {
payment_tx: taker_payment.tx_hex(),
Expand Down Expand Up @@ -1577,7 +1577,7 @@ fn test_watcher_validate_taker_payment_utxo() {
let (_ctx, maker_coin, _) = generate_utxo_coin_with_random_privkey("MYCOIN", 1000u64.into());
let maker_pubkey = maker_coin.my_public_key().unwrap();

let secret_hash = dhash160(&MakerSwap::generate_secret());
let secret_hash = dhash160(&MakerSwap::generate_secret().unwrap());

let taker_payment = taker_coin
.send_taker_payment(SendPaymentArgs {
Expand Down Expand Up @@ -1654,7 +1654,7 @@ fn test_watcher_validate_taker_payment_utxo() {
_ => panic!("Expected `WrongPaymentTx` {INVALID_SENDER_ERR_LOG}, found {:?}", error),
}

let wrong_secret_hash = dhash160(&MakerSwap::generate_secret());
let wrong_secret_hash = dhash160(&MakerSwap::generate_secret().unwrap());
let error = taker_coin
.watcher_validate_taker_payment(WatcherValidatePaymentInput {
payment_tx: taker_payment.tx_hex(),
Expand Down

0 comments on commit e21c9d6

Please sign in to comment.