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

feat(trading-proto-upgrade): wasm DB, kickstart, refund states, v2 RPCs #2015

Merged
merged 47 commits into from
Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
354e918
WIP. Adding fields to MySwapsFiltersTable.
artemii235 Oct 26, 2023
a9fb7b3
WIP. SwapDb modifications.
artemii235 Oct 27, 2023
37c26f5
WASM WIP.
artemii235 Nov 7, 2023
2d22180
Merge remote-tracking branch 'origin/dev' into swap-proto-upgrade-ite…
artemii235 Nov 7, 2023
4e4db07
WIP WASM DB.
Nov 7, 2023
f3d3be3
Merge remote-tracking branch 'origin/dev' into swap-proto-upgrade-ite…
artemii235 Nov 8, 2023
7c92429
WASM WIP.
artemii235 Nov 8, 2023
b803441
WIP WASM DB.
Nov 8, 2023
1363d94
WASM WIP. Refactor.
artemii235 Nov 9, 2023
0b46e02
WIP. WASM trade_v2_test_rick_and_morty is green.
Nov 9, 2023
69e2a0e
WIP. Error handling.
artemii235 Nov 10, 2023
4d0bf50
WIP. Refactoring.
artemii235 Nov 10, 2023
b53bab7
WIP refactoring. WASM trade fails intentionally.
Nov 10, 2023
57b7a4b
WIP. Trade v2 test is green on both native and WASM.
artemii235 Nov 13, 2023
19d8408
WIP. Implementing storing on state machine's start.
artemii235 Nov 13, 2023
afb9a55
WIP. WASM compilation fails.
Nov 13, 2023
225e06c
WIP. Implementing kickstart. Added Dockerized test.
artemii235 Nov 14, 2023
84f8bb3
WIP. Implementing kickstart.
Nov 14, 2023
96e847e
WIP. Implementing kickstart.
artemii235 Nov 15, 2023
a37aa81
WIP. Implementing kickstart.
Nov 15, 2023
1bcbcfd
WIP. Kickstart PoC works on native.
artemii235 Nov 16, 2023
eeb45b4
WIP. Implementing kickstart. Error handling.
Nov 16, 2023
e269c45
WIP. Added BoolAsInt for WASM.
Nov 17, 2023
a52c55a
Merge remote-tracking branch 'origin/dev' into swap-proto-upgrade-ite…
Nov 20, 2023
a2c959a
WIP. Error handling.
Nov 20, 2023
d1dd632
WIP. Adding support of SwapLock to new protocol.
artemii235 Nov 20, 2023
318283a
WIP. Implemented SwapLock for upgraded swaps.
artemii235 Nov 21, 2023
50ff69f
WIP. Remove code duplication for upgraded swaps kickstart handling.
Nov 21, 2023
a6be79c
WIP. Implemented swaps data migration (is_finished) on native.
artemii235 Nov 22, 2023
63ad3d1
WIP. Adding SwapsMigrationTable.
Nov 22, 2023
a700bc5
WIP. Implemented swaps data migration on WASM.
Nov 23, 2023
2164c0f
WIP. Preventing deactivation of coins used in new swaps.
Nov 23, 2023
1cc6728
Merge remote-tracking branch 'origin/dev' into swap-proto-upgrade-ite…
artemii235 Nov 24, 2023
76ec639
WIP. Context clean up. Maker payment refund.
artemii235 Nov 24, 2023
8688b2b
WIP. Implemented taker funding and payment refund.
Nov 24, 2023
424b876
WIP. Return V2 swaps in my_recent_swaps V1 RPC.
artemii235 Nov 27, 2023
17d7608
WIP. Implementing V2 RPCs.
artemii235 Nov 27, 2023
98a17a8
WIP. V2 RPCs.
Nov 27, 2023
5dd0cb4
WIP. V2 RPCs.
Nov 27, 2023
11968b6
WIP. Finished V2 RPCs (for now).
artemii235 Nov 28, 2023
2c927af
Fix WASM Clippy.
Nov 29, 2023
89f5ffa
Review fixes.
Nov 30, 2023
7628efc
Fix review notes.
artemii235 Dec 1, 2023
c984d43
Review fix.
artemii235 Dec 4, 2023
765c63b
Use HD account 1 for both nodes in trade_v2_test_rick_and_morty.
artemii235 Dec 4, 2023
bae1f48
Merge remote-tracking branch 'origin/dev' into swap-proto-upgrade-ite…
artemii235 Dec 5, 2023
8313bc4
Merge remote-tracking branch 'origin/dev' into swap-proto-upgrade-ite…
artemii235 Dec 13, 2023
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ scripts/mm2/seed/unparsed.txt
/MM_VERSION
/MM_VERSION.tmp
/target
/targettest
/clippytarget

# Subcrate artefacts
/mm2src/*/target
Expand Down
8 changes: 4 additions & 4 deletions mm2src/coins/lp_coins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1310,13 +1310,13 @@ pub trait ToBytes {
/// Defines associated types specific to each coin (Pubkey, Address, etc.)
pub trait CoinAssocTypes {
type Pubkey: ToBytes + Send + Sync;
type PubkeyParseError: Send + std::fmt::Display;
type PubkeyParseError: fmt::Debug + Send + fmt::Display;
type Tx: Transaction + Send + Sync;
type TxParseError: Send + std::fmt::Display;
type TxParseError: fmt::Debug + Send + fmt::Display;
type Preimage: ToBytes + Send + Sync;
type PreimageParseError: Send + std::fmt::Display;
type PreimageParseError: fmt::Debug + Send + fmt::Display;
type Sig: ToBytes + Send + Sync;
type SigParseError: Send + std::fmt::Display;
type SigParseError: fmt::Debug + Send + fmt::Display;

fn parse_pubkey(&self, pubkey: &[u8]) -> Result<Self::Pubkey, Self::PubkeyParseError>;

Expand Down
90 changes: 90 additions & 0 deletions mm2src/common/bool_as_int.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};

/// A wrapper struct representing a boolean value as an integer (0 or 1).
#[derive(Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub struct BoolAsInt(bool);

impl BoolAsInt {
/// Creates a new `BoolAsInt` instance from a boolean value.
pub fn new(value: bool) -> Self { BoolAsInt(value) }

/// Retrieves the inner boolean value.
pub fn as_bool(&self) -> bool { self.0 }
}

impl From<bool> for BoolAsInt {
fn from(value: bool) -> Self { BoolAsInt(value) }
}

impl Serialize for BoolAsInt {
/// Serializes the `BoolAsInt` into a single-byte integer (0 or 1).
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_u8(self.0 as u8)
}
}

impl<'de> Deserialize<'de> for BoolAsInt {
/// Deserializes a single-byte integer (0 or 1) into a `BoolAsInt`.
///
/// # Errors
///
/// Returns an error if the value is not 0 or 1.
fn deserialize<D>(deserializer: D) -> Result<BoolAsInt, D::Error>
where
D: Deserializer<'de>,
{
let value = u8::deserialize(deserializer)?;

match value {
0 => Ok(BoolAsInt(false)),
1 => Ok(BoolAsInt(true)),
_ => Err(de::Error::custom("Value must be 0 or 1")),
}
}
}

#[cfg(test)]
mod tests {
use super::*;

/// Tests the serialization of `BoolAsInt`.
#[test]
fn test_serialization() {
let bool_value = BoolAsInt::new(true);
let serialized = serde_json::to_string(&bool_value).unwrap();
assert_eq!(serialized, "1");
}

/// Tests the deserialization of `BoolAsInt` for a value of 0.
#[test]
fn test_deserialization() {
let deserialized: BoolAsInt = serde_json::from_str("0").unwrap();
assert_eq!(deserialized, BoolAsInt::new(false));
}

/// Tests the round trip of serialization and deserialization for `BoolAsInt`.
#[test]
fn test_round_trip() {
let bool_value = BoolAsInt::new(true);
let serialized = serde_json::to_string(&bool_value).unwrap();
let deserialized: BoolAsInt = serde_json::from_str(&serialized).unwrap();
assert_eq!(deserialized, bool_value);
}

/// Tests the deserialization error case when the value is not 0 or 1.
#[test]
fn test_deserialization_error() {
let result: Result<BoolAsInt, _> = serde_json::from_str("2");
assert!(result.is_err());
}

/// Tests the `as_bool` method to retrieve the inner boolean value.
#[test]
fn test_as_bool() {
let bool_value = BoolAsInt::new(true);
assert!(bool_value.as_bool());
}
}
1 change: 1 addition & 0 deletions mm2src/common/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ pub mod write_safe;
#[macro_use]
pub mod log;

pub mod bool_as_int;
pub mod crash_reports;
pub mod custom_futures;
pub mod custom_iter;
Expand Down
6 changes: 4 additions & 2 deletions mm2src/crypto/src/privkey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ impl From<KeysError> for PrivKeyError {
fn from(e: KeysError) -> Self { PrivKeyError::InvalidPrivKey(e.to_string()) }
}

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

fn private_from_seed(seed: &str) -> PrivKeyResult<Private> {
match seed.parse() {
Ok(private) => return Ok(private),
Expand Down Expand Up @@ -133,7 +135,7 @@ impl PartialEq for SerializableSecp256k1Keypair {
impl Eq for SerializableSecp256k1Keypair {}

impl SerializableSecp256k1Keypair {
fn new(key: [u8; 32]) -> PrivKeyResult<Self> {
pub fn new(key: [u8; 32]) -> PrivKeyResult<Self> {
Ok(SerializableSecp256k1Keypair {
inner: key_pair_from_secret(&key)?,
})
Expand All @@ -143,7 +145,7 @@ impl SerializableSecp256k1Keypair {

pub fn public_slice(&self) -> &[u8] { self.inner.public_slice() }

fn priv_key(&self) -> [u8; 32] { self.inner.private().secret.take() }
pub fn priv_key(&self) -> [u8; 32] { self.inner.private().secret.take() }

pub fn random() -> Self {
SerializableSecp256k1Keypair {
Expand Down
11 changes: 11 additions & 0 deletions mm2src/mm2_db/src/indexed_db/drivers/upgrader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,17 @@ pub enum OnUpgradeError {
ErrorOpeningTable { table: String, description: String },
#[display(fmt = "Error occurred due to creating the '{}' index: {}", index, description)]
ErrorCreatingIndex { index: String, description: String },
#[display(
fmt = "Upgrade attempt to an unsupported version: {}, old: {}, new: {}",
unsupported_version,
old_version,
new_version
)]
UnsupportedVersion {
unsupported_version: u32,
old_version: u32,
new_version: u32,
},
}

pub struct DbUpgrader {
Expand Down
9 changes: 7 additions & 2 deletions mm2src/mm2_main/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use db_common::sqlite::run_optimization_pragmas;
use db_common::sqlite::rusqlite::{params_from_iter, Result as SqlResult};
use mm2_core::mm_ctx::MmArc;

use my_swaps::fill_my_swaps_from_json_statements;
use my_swaps::{fill_my_swaps_from_json_statements, set_is_finished_for_legacy_swaps_statements};
use stats_swaps::create_and_fill_stats_swaps_from_json_statements;

const SELECT_MIGRATION: &str = "SELECT * FROM migration ORDER BY current_migration DESC LIMIT 1;";
Expand All @@ -22,7 +22,7 @@ fn get_current_migration(ctx: &MmArc) -> SqlResult<i64> {
conn.query_row(SELECT_MIGRATION, [], |row| row.get(0))
}

pub async fn init_and_migrate_db(ctx: &MmArc) -> SqlResult<()> {
pub async fn init_and_migrate_sql_db(ctx: &MmArc) -> SqlResult<()> {
info!("Checking the current SQLite migration");
match get_current_migration(ctx) {
Ok(current_migration) => {
Expand Down Expand Up @@ -105,6 +105,10 @@ fn migration_9() -> Vec<(&'static str, Vec<String>)> {
db_common::sqlite::execute_batch(my_swaps::TRADING_PROTO_UPGRADE_MIGRATION)
}

async fn migration_10(ctx: &MmArc) -> Vec<(&'static str, Vec<String>)> {
set_is_finished_for_legacy_swaps_statements(ctx).await
}

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 @@ -116,6 +120,7 @@ async fn statements_for_migration(ctx: &MmArc, current_migration: i64) -> Option
7 => Some(migration_7()),
8 => Some(migration_8()),
9 => Some(migration_9()),
10 => Some(migration_10(ctx).await),
_ => None,
}
}
Expand Down
Loading
Loading