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

[r2r] Zhtlc orders is_mine bug #1489

Merged
merged 35 commits into from
Oct 18, 2022
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
1afa0c2
WIP rough implementation
laruh Sep 19, 2022
232aead
WIP orderbook_rpc
laruh Sep 20, 2022
43f5c81
WIP orderbook_rpc_v2
laruh Sep 20, 2022
4c00c7a
WIP tests
laruh Sep 20, 2022
3327ee2
Merge remote-tracking branch 'origin/dev' into ZHTLC_orders_ismine_bug
laruh Sep 21, 2022
a7152e6
WIP CoinActivationResult
laruh Sep 21, 2022
eac838c
WIP
laruh Sep 21, 2022
30d73ce
WIP add target_arch for protocol matching
laruh Sep 21, 2022
7f6bf70
Merge remote-tracking branch 'origin/dev' into ZHTLC_orders_ismine_bug
laruh Sep 22, 2022
0b4f9ba
WIP check_point_block added
laruh Sep 22, 2022
0b86048
WIP fix a typo
laruh Sep 22, 2022
30127e0
Merge remote-tracking branch 'origin/dev' into ZHTLC_orders_ismine_bug
laruh Sep 26, 2022
41cd026
Merge remote-tracking branch 'origin/dev' into ZHTLC_orders_ismine_bug
laruh Sep 26, 2022
c4b9c6f
Merge remote-tracking branch 'origin/dev' into ZHTLC_orders_ismine_bug
laruh Sep 27, 2022
f597c5f
WIP
laruh Sep 29, 2022
81ddd02
Merge remote-tracking branch 'origin/dev' into ZHTLC_orders_ismine_bug
laruh Sep 29, 2022
7977953
WIP valid check_point_block for zombie
laruh Sep 29, 2022
454c74e
notes added
laruh Oct 3, 2022
905d0d5
fix is_mine_zhtlc
laruh Oct 4, 2022
09840b9
remove mutex
laruh Oct 5, 2022
70c5415
wip add_pubkey
laruh Oct 10, 2022
91e3471
added my_p2p_pubkeys for wasm
laruh Oct 10, 2022
9c2e5bb
added remove_pubkey function
laruh Oct 10, 2022
5eebd2d
Merge remote-tracking branch 'origin/dev' into ZHTLC_orders_ismine_bug
laruh Oct 10, 2022
be6aa1d
r2r
laruh Oct 11, 2022
f711b02
Merge remote-tracking branch 'origin/dev' into ZHTLC_orders_ismine_bug
laruh Oct 11, 2022
d39b300
use one is_mine func
laruh Oct 12, 2022
9335dfe
little fix
laruh Oct 12, 2022
112a207
remove unnecessary code
laruh Oct 13, 2022
33fdfe8
little fix
laruh Oct 13, 2022
37dee5f
add check_point_block 290_000 for test
laruh Oct 14, 2022
55c1964
is_my_order remove pub
laruh Oct 14, 2022
6ede115
move my_p2p_pubkeys in Orderbook
laruh Oct 16, 2022
1a02369
Merge remote-tracking branch 'origin/dev' into ZHTLC_orders_ismine_bug
laruh Oct 17, 2022
a558c31
remove my_p2p_pubkeys.insert from orders_kick_start
laruh Oct 17, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 90 additions & 5 deletions mm2src/mm2_main/src/lp_ordermatch/orderbook_rpc.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::{orderbook_address, subscribe_to_orderbook_topic, OrdermatchContext, RpcOrderbookEntry};
use crate::mm2::lp_ordermatch::{addr_format_from_protocol_info, RpcOrderbookEntryV2};
use coins::{address_by_coin_conf_and_pubkey_str, coin_conf, is_wallet_only_conf};
use coins::{address_by_coin_conf_and_pubkey_str, coin_conf, is_wallet_only_conf, CoinProtocol};
use common::log::warn;
use common::{now_ms, HttpStatusCode};
use crypto::CryptoCtx;
Expand Down Expand Up @@ -111,6 +111,38 @@ pub fn is_my_order(my_pub: &Option<String>, order_pubkey: &str) -> bool {
my_pub.as_ref().map(|my| my == order_pubkey).unwrap_or(false)
}

// ZHTLC protocol coin uses random keypair to sign P2P messages per every order.
// So, each ZHTLC order has unique «pubkey» field that doesn’t match node persistent pubkey derived from passphrase.
// We can compare pubkeys from maker_orders and from asks or bids, to find our order.
pub fn is_mine_zhtlc(my_orders_pubkeys: &Vec<String>, my_pub: &Option<String>, order_pubkey: &str) -> bool {
let mut is_mine_zhtlc = false;
for my_pubkey in my_orders_pubkeys {
if my_pubkey == order_pubkey {
is_mine_zhtlc = true;
break;
}
}
drop_mutability!(is_mine_zhtlc);
let is_my_order = is_my_order(my_pub, order_pubkey);
is_mine_zhtlc || is_my_order
}

async fn get_my_orders_pubkeys(ctx: &MmArc) -> Vec<String> {
let ordermatch_ctx = OrdermatchContext::from_ctx(ctx).expect("from_ctx failed");
let my_orders = ordermatch_ctx.maker_orders_ctx.lock().orders.clone();
let mut res = Vec::new();
for (_, order_mutex) in my_orders {
artemii235 marked this conversation as resolved.
Show resolved Hide resolved
let order = order_mutex.lock().await;
if let Some(p2p_privkey) = order.p2p_privkey {
drop(order);
let pubsecp = hex::encode(p2p_privkey.public_slice());
res.push(pubsecp)
}
}
drop_mutability!(res);
res
}

pub async fn orderbook_rpc(ctx: MmArc, req: Json) -> Result<Response<Vec<u8>>, String> {
let req: OrderbookReq = try_s!(json::from_value(req));
if req.base == req.rel {
Expand All @@ -137,6 +169,21 @@ pub async fn orderbook_rpc(ctx: MmArc, req: Json) -> Result<Response<Vec<u8>>, S
if base_ticker == rel_ticker && base_coin_conf["protocol"] == rel_coin_conf["protocol"] {
return ERR!("Base and rel coins have the same orderbook tickers and protocols.");
}
let base_coin_protocol: CoinProtocol = try_s!(json::from_value(base_coin_conf["protocol"].clone()));
artemii235 marked this conversation as resolved.
Show resolved Hide resolved
let rel_coin_protocol: CoinProtocol = try_s!(json::from_value(rel_coin_conf["protocol"].clone()));
let is_zhtlc_base = match base_coin_protocol {
#[cfg(not(target_arch = "wasm32"))]
CoinProtocol::ZHTLC { .. } => true,
_ => false,
};
let is_zhtlc_rel = match rel_coin_protocol {
#[cfg(not(target_arch = "wasm32"))]
CoinProtocol::ZHTLC { .. } => true,
_ => false,
};
let is_zhtlc = is_zhtlc_base || is_zhtlc_rel;
// have to create my_orders_pubkeys before orderbook, because orderbook is not `Send`
let my_orders_pubkeys = get_my_orders_pubkeys(&ctx).await;

try_s!(subscribe_to_orderbook_topic(&ctx, &base_ticker, &rel_ticker, request_orderbook).await);
let orderbook = ordermatch_ctx.orderbook.lock();
Expand All @@ -162,7 +209,11 @@ pub async fn orderbook_rpc(ctx: MmArc, req: Json) -> Result<Response<Vec<u8>>, S
&ask.pubkey,
address_format,
));
let is_mine = is_my_order(&my_pubsecp, &ask.pubkey);
let is_mine = if is_zhtlc {
is_mine_zhtlc(&my_orders_pubkeys, &my_pubsecp, &ask.pubkey)
} else {
is_my_order(&my_pubsecp, &ask.pubkey)
};
orderbook_entries.push(ask.as_rpc_entry_ask(address, is_mine));
}
orderbook_entries
Expand All @@ -189,7 +240,11 @@ pub async fn orderbook_rpc(ctx: MmArc, req: Json) -> Result<Response<Vec<u8>>, S
&bid.pubkey,
address_format,
));
let is_mine = is_my_order(&my_pubsecp, &bid.pubkey);
let is_mine = if is_zhtlc {
is_mine_zhtlc(&my_orders_pubkeys, &my_pubsecp, &bid.pubkey)
} else {
is_my_order(&my_pubsecp, &bid.pubkey)
};
orderbook_entries.push(bid.as_rpc_entry_bid(address, is_mine));
}
orderbook_entries
Expand Down Expand Up @@ -227,12 +282,18 @@ pub enum OrderbookRpcError {
CoinConfigNotFound(String),
CoinIsWalletOnly(String),
P2PSubscribeError(String),
InvalidJson(String),
}

impl From<serde_json::Error> for OrderbookRpcError {
fn from(e: serde_json::Error) -> Self { OrderbookRpcError::InvalidJson(e.to_string()) }
}

impl HttpStatusCode for OrderbookRpcError {
fn status_code(&self) -> StatusCode {
match self {
OrderbookRpcError::BaseRelSame
| OrderbookRpcError::InvalidJson(_)
| OrderbookRpcError::BaseRelSameOrderbookTickersAndProtocols
| OrderbookRpcError::CoinConfigNotFound(_)
| OrderbookRpcError::CoinIsWalletOnly(_) => StatusCode::BAD_REQUEST,
Expand Down Expand Up @@ -300,6 +361,22 @@ pub async fn orderbook_rpc_v2(
return MmError::err(OrderbookRpcError::BaseRelSameOrderbookTickersAndProtocols);
}

let base_coin_protocol: CoinProtocol = json::from_value(base_coin_conf["protocol"].clone())?;
artemii235 marked this conversation as resolved.
Show resolved Hide resolved
let rel_coin_protocol: CoinProtocol = json::from_value(rel_coin_conf["protocol"].clone())?;
let is_zhtlc_base = match base_coin_protocol {
#[cfg(not(target_arch = "wasm32"))]
CoinProtocol::ZHTLC { .. } => true,
_ => false,
};
let is_zhtlc_rel = match rel_coin_protocol {
#[cfg(not(target_arch = "wasm32"))]
CoinProtocol::ZHTLC { .. } => true,
_ => false,
};
let is_zhtlc = is_zhtlc_base || is_zhtlc_rel;
// have to create my_orders_pubkeys before orderbook, because orderbook is not `Send`
let my_orders_pubkeys = get_my_orders_pubkeys(&ctx).await;

let request_orderbook = true;
subscribe_to_orderbook_topic(&ctx, &base_ticker, &rel_ticker, request_orderbook)
.await
Expand Down Expand Up @@ -331,7 +408,11 @@ pub async fn orderbook_rpc_v2(
continue;
},
};
let is_mine = is_my_order(&my_pubsecp, &ask.pubkey);
let is_mine = if is_zhtlc {
is_mine_zhtlc(&my_orders_pubkeys, &my_pubsecp, &ask.pubkey)
} else {
is_my_order(&my_pubsecp, &ask.pubkey)
};
orderbook_entries.push(ask.as_rpc_v2_entry_ask(address, is_mine));
}
orderbook_entries
Expand Down Expand Up @@ -361,7 +442,11 @@ pub async fn orderbook_rpc_v2(
continue;
},
};
let is_mine = is_my_order(&my_pubsecp, &bid.pubkey);
let is_mine = if is_zhtlc {
is_mine_zhtlc(&my_orders_pubkeys, &my_pubsecp, &bid.pubkey)
} else {
is_my_order(&my_pubsecp, &bid.pubkey)
};
orderbook_entries.push(bid.as_rpc_v2_entry_bid(address, is_mine));
}
orderbook_entries
Expand Down
8 changes: 4 additions & 4 deletions mm2src/mm2_main/src/mm2_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use uuid::Uuid;
use mm2_test_helpers::for_tests::init_z_coin_native;

#[cfg(all(feature = "zhtlc-native-tests", not(target_arch = "wasm32")))]
async fn enable_z_coin(mm: &MarketMakerIt, coin: &str) -> ZcoinActivationResult {
async fn enable_z_coin(mm: &MarketMakerIt, coin: &str) -> CoinActivationResult {
sergeyboyko0791 marked this conversation as resolved.
Show resolved Hide resolved
let init = init_z_coin_native(mm, coin).await;
let init: RpcV2Response<InitTaskResult> = json::from_value(init).unwrap();
let timeout = now_ms() + 120000;
Expand All @@ -41,7 +41,7 @@ async fn enable_z_coin(mm: &MarketMakerIt, coin: &str) -> ZcoinActivationResult

let status = init_z_coin_status(mm, init.result.task_id).await;
let status: RpcV2Response<InitZcoinStatus> = json::from_value(status).unwrap();
if let InitZcoinStatus::Ready(rpc_result) = status.result {
if let InitZcoinStatus::Ok(rpc_result) = status.result {
match rpc_result {
MmRpcResult::Ok { result } => break result,
MmRpcResult::Err(e) => panic!("{} initialization error {:?}", coin, e),
Expand Down Expand Up @@ -181,7 +181,7 @@ async fn enable_z_coin_light(
coin: &str,
electrums: &[&str],
lightwalletd_urls: &[&str],
) -> ZcoinActivationResult {
) -> CoinActivationResult {
let init = init_z_coin_light(mm, coin, electrums, lightwalletd_urls).await;
let init: RpcV2Response<InitTaskResult> = json::from_value(init).unwrap();
let timeout = now_ms() + 12000000;
Expand All @@ -194,7 +194,7 @@ async fn enable_z_coin_light(
let status = init_z_coin_status(mm, init.result.task_id).await;
println!("Status {}", json::to_string(&status).unwrap());
let status: RpcV2Response<InitZcoinStatus> = json::from_value(status).unwrap();
if let InitZcoinStatus::Ready(rpc_result) = status.result {
if let InitZcoinStatus::Ok(rpc_result) = status.result {
match rpc_result {
MmRpcResult::Ok { result } => {
break result;
Expand Down
4 changes: 2 additions & 2 deletions mm2src/mm2_main/src/mm2_tests/structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -623,7 +623,7 @@ pub enum EnableCoinBalance {

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ZcoinActivationResult {
pub struct CoinActivationResult {
pub ticker: String,
pub current_block: u64,
pub wallet_balance: EnableCoinBalance,
Expand Down Expand Up @@ -652,7 +652,7 @@ pub enum MmRpcResult<T> {
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, tag = "status", content = "details")]
pub enum InitZcoinStatus {
Ready(MmRpcResult<ZcoinActivationResult>),
Ok(MmRpcResult<CoinActivationResult>),
InProgress(Json),
UserActionRequired(Json),
}
Expand Down
12 changes: 9 additions & 3 deletions mm2src/mm2_test_helpers/src/for_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,13 @@ pub fn zombie_conf() -> Json {
"hrp_sapling_payment_address": "zs",
"b58_pubkey_address_prefix": [ 28, 184 ],
"b58_script_address_prefix": [ 28, 189 ]
}
},
"check_point_block": {
"height": 269618,
"time": 1662970615,
"hash": "69F4995F708B298B83AFF3C3BA12D08DAD8B2B594F7768076759A39C72220400",
"sapling_tree": "013EAB5E0567940A457A72C6A0BFEEC586832DECAE6187610BB095B6017F5B1F36000C000001D09AE7E35BDE3061DCD093496DE772686C77158660AE1647EBBF97A3BFE5984A015ECECB8E6853B8B15D9CFCFA246CC90291B53623F5BAE73A2B5A7B255653362301242613B9D3F753CE664352DE7EADDD83182DBBC445102521F9D1179D2F0750260001778BDB17D276001E0D073EA63146627916655BAF797B2B61DE811141D5CAB80A01F9D97B45043D23B65C62C0622DF7508D19092585FB0F84A54F0095D9B4EFBC4301E2A080B34FDB810559FE0418A21EBDFB6F860DE386AA54A6C1F3FA09767900000000015B031401A77FE57EAA149E9467BAE0DA17002421AA1798D6F93875BE79ECA95F"
},
}
},
"required_confirmations":0
Expand Down Expand Up @@ -1659,7 +1665,7 @@ pub async fn init_z_coin_light(mm: &MarketMakerIt, coin: &str, electrums: &[&str
let request = mm
.rpc(&json! ({
"userpass": mm.userpass,
"method": "init_z_coin",
"method": "task::enable_z_coin::init",
"mmrpc": "2.0",
"params": {
"ticker": coin,
Expand All @@ -1684,7 +1690,7 @@ pub async fn init_z_coin_status(mm: &MarketMakerIt, task_id: u64) -> Json {
let request = mm
.rpc(&json! ({
"userpass": mm.userpass,
"method": "init_z_coin_status",
"method": "task::enable_z_coin::status",
"mmrpc": "2.0",
"params": {
"task_id": task_id,
Expand Down