Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
8 changes: 8 additions & 0 deletions mm2src/mm2_main/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,13 @@ fn migration_12() -> Vec<(&'static str, Vec<String>)> {
]
}

fn migration_13() -> Vec<(&'static str, Vec<String>)> {
vec![
(my_swaps::ADD_SWAP_VERSION_FIELD, vec![]), // Step 1: Add new column
(my_swaps::SET_LEGACY_SWAP_VERSION, vec![]), // Step 2: Update old rows
]
}

async fn statements_for_migration(ctx: &MmArc, current_migration: i64) -> Option<Vec<(&'static str, Vec<String>)>> {
match current_migration {
1 => Some(migration_1(ctx).await),
Expand All @@ -133,6 +140,7 @@ async fn statements_for_migration(ctx: &MmArc, current_migration: i64) -> Option
10 => Some(migration_10(ctx).await),
11 => Some(migration_11()),
12 => Some(migration_12()),
13 => Some(migration_13()),
_ => None,
}
}
Expand Down
18 changes: 13 additions & 5 deletions mm2src/mm2_main/src/database/my_swaps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,12 @@ pub const TRADING_PROTO_UPGRADE_MIGRATION: &[&str] = &[
"ALTER TABLE my_swaps ADD COLUMN taker_coin_nota BOOLEAN;",
];

/// Adds Swap Protocol version column to `my_swaps` table
pub const ADD_SWAP_VERSION_FIELD: &str = "ALTER TABLE my_swaps ADD COLUMN swap_version INTEGER;";
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be useful to add the version to stats_swaps table as well. It should be done in another PR though as this is should be merged soon.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just noticed that currently we don't need the swap version in my_swaps table as we have swap_type https://github.com/KomodoPlatform/komodo-defi-framework/blob/731e605fc2b53b9f4afa9e13e3682c5be7ed9cf6/mm2src/mm2_main/src/database/my_swaps.rs#L89 https://github.com/KomodoPlatform/komodo-defi-framework/blob/39515a9f3ea1089bb462e99c8cafb1049a920dbd/mm2src/mm2_main/src/lp_swap.rs#L152-L154 but version can be different from type in the future, for instance MAKER_SWAP_V2_TYPE which s TPU Maker can have multiple versions but one type. Just thought to mention this and the redundancy we have.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just noticed that currently we don't need the swap version in my_swaps table as we have swap_type

From what I see these TYPE consts were provided to separate legacy and swap_v2 taker/maker data formats in database. I think it is something different from swap protocol version.

Well may be in practice we will see, will taker/maker types be different from swap protocol version or not.

ps: This field is useful for MySwapForRpc, as it can be retrieved from both get_taker_swap_data_for_rpc and get_maker_swap_data_for_rpc. Having a ready swap_version field simplifies the process of determining the swap version.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I understand, that's why I said currently :)
What I meant was that we could have converted this type to the version without adding a new column for now, that's all. But I like having version explicitly and resolving this comment.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving it only for stats_swaps #2324 (comment)

/// Sets default value for `swap_version` to `1` for existing rows
pub const SET_LEGACY_SWAP_VERSION: &str = "UPDATE my_swaps SET swap_version = 1 WHERE swap_version IS NULL;";
pub const ADD_OTHER_P2P_PUBKEY_FIELD: &str = "ALTER TABLE my_swaps ADD COLUMN other_p2p_pub BLOB;";
// Storing rational numbers as text to maintain precision
/// Storing rational numbers as text to maintain precision
pub const ADD_DEX_FEE_BURN_FIELD: &str = "ALTER TABLE my_swaps ADD COLUMN dex_fee_burn TEXT;";

/// The query to insert swap on migration 1, during this migration swap_type column doesn't exist
Expand Down Expand Up @@ -97,7 +101,8 @@ const INSERT_MY_SWAP_V2: &str = r#"INSERT INTO my_swaps (
maker_coin_nota,
taker_coin_confs,
taker_coin_nota,
other_p2p_pub
other_p2p_pub,
swap_version
) VALUES (
:my_coin,
:other_coin,
Expand All @@ -118,7 +123,8 @@ const INSERT_MY_SWAP_V2: &str = r#"INSERT INTO my_swaps (
:maker_coin_nota,
:taker_coin_confs,
:taker_coin_nota,
:other_p2p_pub
:other_p2p_pub,
:swap_version
);"#;

pub fn insert_new_swap_v2(ctx: &MmArc, params: &[(&str, &dyn ToSql)]) -> SqlResult<()> {
Expand Down Expand Up @@ -311,7 +317,8 @@ pub const SELECT_MY_SWAP_V2_FOR_RPC_BY_UUID: &str = r#"SELECT
maker_coin_confs,
maker_coin_nota,
taker_coin_confs,
taker_coin_nota
taker_coin_nota,
swap_version
FROM my_swaps
WHERE uuid = :uuid;
"#;
Expand All @@ -337,7 +344,8 @@ pub const SELECT_MY_SWAP_V2_BY_UUID: &str = r#"SELECT
taker_coin_confs,
taker_coin_nota,
p2p_privkey,
other_p2p_pub
other_p2p_pub,
swap_version
FROM my_swaps
WHERE uuid = :uuid;
"#;
Expand Down
73 changes: 60 additions & 13 deletions mm2src/mm2_main/src/lp_ordermatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ use crate::lp_swap::{calc_max_maker_vol, check_balance_for_maker_swap, check_bal
run_taker_swap, swap_v2_topic, AtomicLocktimeVersion, CheckBalanceError, CheckBalanceResult,
CoinVolumeInfo, MakerSwap, RunMakerSwapInput, RunTakerSwapInput, SwapConfirmationsSettings,
TakerSwap, LEGACY_SWAP_TYPE};
use crate::swap_versioning::{legacy_swap_version, SwapVersion};

#[cfg(any(test, feature = "run-docker-tests"))]
use crate::lp_swap::taker_swap::FailAt;
Expand Down Expand Up @@ -139,6 +140,8 @@ const TRIE_STATE_HISTORY_TIMEOUT: u64 = 3;
const TRIE_ORDER_HISTORY_TIMEOUT: u64 = 300;
#[cfg(test)]
const TRIE_ORDER_HISTORY_TIMEOUT: u64 = 3;
/// Current swap protocol version
const SWAP_VERSION_DEFAULT: u8 = 2;

pub type OrderbookP2PHandlerResult = Result<(), MmError<OrderbookP2PHandlerError>>;

Expand Down Expand Up @@ -1178,12 +1181,12 @@ pub struct TakerRequest {
#[serde(default)]
match_by: MatchBy,
conf_settings: Option<OrderConfirmationsSettings>,
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub base_protocol_info: Option<Vec<u8>>,
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rel_protocol_info: Option<Vec<u8>>,
#[serde(default, skip_serializing_if = "SwapVersion::is_legacy")]
pub swap_version: SwapVersion,
}

impl TakerRequest {
Expand All @@ -1204,6 +1207,7 @@ impl TakerRequest {
conf_settings: Some(message.conf_settings),
base_protocol_info: message.base_protocol_info,
rel_protocol_info: message.rel_protocol_info,
swap_version: message.swap_version,
}
}

Expand Down Expand Up @@ -1249,6 +1253,7 @@ impl From<TakerOrder> for new_protocol::OrdermatchMessage {
conf_settings: taker_order.request.conf_settings.unwrap(),
base_protocol_info: taker_order.request.base_protocol_info,
rel_protocol_info: taker_order.request.rel_protocol_info,
swap_version: taker_order.request.swap_version,
})
}
}
Expand All @@ -1274,6 +1279,7 @@ pub struct TakerOrderBuilder<'a> {
min_volume: Option<MmNumber>,
timeout: u64,
save_in_history: bool,
swap_version: u8,
}

pub enum TakerOrderBuildError {
Expand Down Expand Up @@ -1353,6 +1359,7 @@ impl<'a> TakerOrderBuilder<'a> {
order_type: OrderType::GoodTillCancelled,
timeout: TAKER_ORDER_TIMEOUT,
save_in_history: true,
swap_version: SWAP_VERSION_DEFAULT,
}
}

Expand Down Expand Up @@ -1416,6 +1423,12 @@ impl<'a> TakerOrderBuilder<'a> {
self
}

/// When a new [TakerOrderBuilder::new] is created, it sets [SWAP_VERSION_DEFAULT].
/// However, if user has not specified in the config to use TPU V2,
/// the TakerOrderBuilder's swap_version is changed to legacy.
/// In the future alls users will be using TPU V2 by default without "use_trading_proto_v2" configuration.
pub fn set_legacy_swap_v(&mut self) { self.swap_version = legacy_swap_version() }

/// Validate fields and build
#[allow(clippy::result_large_err)]
pub fn build(self) -> Result<TakerOrder, TakerOrderBuildError> {
Expand Down Expand Up @@ -1504,6 +1517,7 @@ impl<'a> TakerOrderBuilder<'a> {
conf_settings: self.conf_settings,
base_protocol_info: Some(base_protocol_info),
rel_protocol_info: Some(rel_protocol_info),
swap_version: SwapVersion::from(self.swap_version),
},
matches: Default::default(),
min_volume,
Expand Down Expand Up @@ -1544,6 +1558,7 @@ impl<'a> TakerOrderBuilder<'a> {
conf_settings: self.conf_settings,
base_protocol_info: Some(base_protocol_info),
rel_protocol_info: Some(rel_protocol_info),
swap_version: SwapVersion::from(self.swap_version),
},
matches: HashMap::new(),
min_volume: Default::default(),
Expand Down Expand Up @@ -1705,6 +1720,8 @@ pub struct MakerOrder {
/// A custom priv key for more privacy to prevent linking orders of the same node between each other
/// Commonly used with privacy coins (ARRR, ZCash, etc.)
p2p_privkey: Option<SerializableSecp256k1Keypair>,
#[serde(default, skip_serializing_if = "SwapVersion::is_legacy")]
pub swap_version: SwapVersion,
}

pub struct MakerOrderBuilder<'a> {
Expand All @@ -1717,6 +1734,7 @@ pub struct MakerOrderBuilder<'a> {
rel_orderbook_ticker: Option<String>,
conf_settings: Option<OrderConfirmationsSettings>,
save_in_history: bool,
swap_version: u8,
}

pub enum MakerOrderBuildError {
Expand Down Expand Up @@ -1866,6 +1884,7 @@ impl<'a> MakerOrderBuilder<'a> {
price: 0.into(),
conf_settings: None,
save_in_history: true,
swap_version: SWAP_VERSION_DEFAULT,
}
}

Expand Down Expand Up @@ -1904,6 +1923,12 @@ impl<'a> MakerOrderBuilder<'a> {
self
}

/// When a new [MakerOrderBuilder::new] is created, it sets [SWAP_VERSION_DEFAULT].
/// However, if user has not specified in the config to use TPU V2,
/// the MakerOrderBuilder's swap_version is changed to legacy.
/// In the future alls users will be using TPU V2 by default without "use_trading_proto_v2" configuration.
pub fn set_legacy_swap_v(&mut self) { self.swap_version = legacy_swap_version() }

/// Build MakerOrder
#[allow(clippy::result_large_err)]
pub fn build(self) -> Result<MakerOrder, MakerOrderBuildError> {
Expand Down Expand Up @@ -1960,6 +1985,7 @@ impl<'a> MakerOrderBuilder<'a> {
base_orderbook_ticker: self.base_orderbook_ticker,
rel_orderbook_ticker: self.rel_orderbook_ticker,
p2p_privkey,
swap_version: SwapVersion::from(self.swap_version),
})
}

Expand All @@ -1984,6 +2010,7 @@ impl<'a> MakerOrderBuilder<'a> {
base_orderbook_ticker: None,
rel_orderbook_ticker: None,
p2p_privkey: None,
swap_version: SwapVersion::from(self.swap_version),
}
}
}
Expand Down Expand Up @@ -2114,6 +2141,7 @@ impl From<TakerOrder> for MakerOrder {
base_orderbook_ticker: taker_order.base_orderbook_ticker,
rel_orderbook_ticker: taker_order.rel_orderbook_ticker,
p2p_privkey: taker_order.p2p_privkey,
swap_version: taker_order.request.swap_version,
},
// The "buy" taker order is recreated with reversed pair as Maker order is always considered as "sell"
TakerAction::Buy => {
Expand All @@ -2136,6 +2164,7 @@ impl From<TakerOrder> for MakerOrder {
base_orderbook_ticker: taker_order.rel_orderbook_ticker,
rel_orderbook_ticker: taker_order.base_orderbook_ticker,
p2p_privkey: taker_order.p2p_privkey,
swap_version: taker_order.request.swap_version,
}
},
}
Expand Down Expand Up @@ -2182,12 +2211,12 @@ pub struct MakerReserved {
sender_pubkey: H256Json,
dest_pub_key: H256Json,
conf_settings: Option<OrderConfirmationsSettings>,
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub base_protocol_info: Option<Vec<u8>>,
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rel_protocol_info: Option<Vec<u8>>,
#[serde(default, skip_serializing_if = "SwapVersion::is_legacy")]
pub swap_version: SwapVersion,
}

impl MakerReserved {
Expand Down Expand Up @@ -2215,6 +2244,7 @@ impl MakerReserved {
conf_settings: Some(message.conf_settings),
base_protocol_info: message.base_protocol_info,
rel_protocol_info: message.rel_protocol_info,
swap_version: message.swap_version,
}
}
}
Expand All @@ -2231,6 +2261,7 @@ impl From<MakerReserved> for new_protocol::OrdermatchMessage {
conf_settings: maker_reserved.conf_settings.unwrap(),
base_protocol_info: maker_reserved.base_protocol_info,
rel_protocol_info: maker_reserved.rel_protocol_info,
swap_version: maker_reserved.swap_version,
})
}
}
Expand Down Expand Up @@ -3052,8 +3083,11 @@ fn lp_connect_start_bob(ctx: MmArc, maker_match: MakerMatch, maker_order: MakerO
},
};

// TODO add alice swap protocol version check once protocol versioning is implemented
if !ctx.use_trading_proto_v2() {
let alice_swap_v = maker_match.request.swap_version;
let bob_swap_v = maker_order.swap_version;

// Start a legacy swap if either the taker or maker uses the legacy swap protocol (version 1)
if alice_swap_v.is_legacy() || bob_swap_v.is_legacy() {
let params = LegacySwapParams {
maker_coin: &maker_coin,
taker_coin: &taker_coin,
Expand Down Expand Up @@ -3188,6 +3222,7 @@ async fn start_maker_swap_state_machine<
lock_duration: *params.locktime,
taker_p2p_pubkey: *taker_p2p_pubkey,
require_taker_payment_spend_confirm: true,
swap_version: maker_order.swap_version.version,
};
#[allow(clippy::box_default)]
maker_swap_state_machine
Expand Down Expand Up @@ -3273,8 +3308,11 @@ fn lp_connected_alice(ctx: MmArc, taker_order: TakerOrder, taker_match: TakerMat
uuid
);

// TODO add bob swap protocol version check once protocol versioning is implemented
if !ctx.use_trading_proto_v2() {
let bob_swap_v = taker_match.reserved.swap_version;
let alice_swap_v = taker_order.request.swap_version;

// Start a legacy swap if either the maker or taker uses the legacy swap protocol (version 1)
if bob_swap_v.is_legacy() || alice_swap_v.is_legacy() {
let params = LegacySwapParams {
maker_coin: &maker_coin,
taker_coin: &taker_coin,
Expand Down Expand Up @@ -3425,6 +3463,7 @@ async fn start_taker_swap_state_machine<
maker_p2p_pubkey: *maker_p2p_pubkey,
require_maker_payment_confirm_before_funding_spend: true,
require_maker_payment_spend_confirm: true,
swap_version: taker_order.request.swap_version.version,
};
#[allow(clippy::box_default)]
taker_swap_state_machine
Expand Down Expand Up @@ -3945,6 +3984,7 @@ async fn process_taker_request(ctx: MmArc, from_pubkey: H256Json, taker_request:
}),
base_protocol_info: Some(base_coin.coin_protocol_info(None)),
rel_protocol_info: Some(rel_coin.coin_protocol_info(Some(rel_amount.clone()))),
swap_version: order.swap_version,
};
let topic = order.orderbook_topic();
log::debug!("Request matched sending reserved {:?}", reserved);
Expand Down Expand Up @@ -4192,6 +4232,10 @@ pub async fn lp_auto_buy(
.with_save_in_history(input.save_in_history)
.with_base_orderbook_ticker(ordermatch_ctx.orderbook_ticker(base_coin.ticker()))
.with_rel_orderbook_ticker(ordermatch_ctx.orderbook_ticker(rel_coin.ticker()));
if !ctx.use_trading_proto_v2() {
order_builder.set_legacy_swap_v();
}

if let Some(timeout) = input.timeout {
order_builder = order_builder.with_timeout(timeout);
}
Expand Down Expand Up @@ -4929,14 +4973,17 @@ pub async fn create_maker_order(ctx: &MmArc, req: SetPriceReq) -> Result<MakerOr
rel_confs: req.rel_confs.unwrap_or_else(|| rel_coin.required_confirmations()),
rel_nota: req.rel_nota.unwrap_or_else(|| rel_coin.requires_notarization()),
};
let builder = MakerOrderBuilder::new(&base_coin, &rel_coin)
let mut builder = MakerOrderBuilder::new(&base_coin, &rel_coin)
.with_max_base_vol(volume.clone())
.with_min_base_vol(req.min_volume)
.with_price(req.price.clone())
.with_conf_settings(conf_settings)
.with_save_in_history(req.save_in_history)
.with_base_orderbook_ticker(ordermatch_ctx.orderbook_ticker(base_coin.ticker()))
.with_rel_orderbook_ticker(ordermatch_ctx.orderbook_ticker(rel_coin.ticker()));
if !ctx.use_trading_proto_v2() {
builder.set_legacy_swap_v();
}

let new_order = try_s!(builder.build());

Expand Down
3 changes: 3 additions & 0 deletions mm2src/mm2_main/src/lp_ordermatch/my_orders_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,7 @@ mod tests {
use super::*;
use crate::lp_ordermatch::ordermatch_wasm_db::{ItemId, MyFilteringHistoryOrdersTable};
use crate::lp_ordermatch::{OrdermatchContext, TakerRequest};
use crate::swap_versioning::SwapVersion;
use common::{new_uuid, now_ms};
use futures::compat::Future01CompatExt;
use itertools::Itertools;
Expand Down Expand Up @@ -724,6 +725,7 @@ mod tests {
base_orderbook_ticker: None,
rel_orderbook_ticker: None,
p2p_privkey: None,
swap_version: SwapVersion::default(),
}
}

Expand All @@ -742,6 +744,7 @@ mod tests {
conf_settings: None,
base_protocol_info: None,
rel_protocol_info: None,
swap_version: SwapVersion::default(),
},
matches: HashMap::new(),
created_at: now_ms(),
Expand Down
Loading