From 6621f5c3f84e86f5d7504ed484ccbeaad6a75230 Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Mon, 25 Sep 2023 16:29:18 +0300 Subject: [PATCH 1/2] add rustfmt `group_imports` rule Signed-off-by: onur-ozkan --- rustfmt.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/rustfmt.toml b/rustfmt.toml index 55d1bb5ff2..8b85dd3c94 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -47,3 +47,6 @@ tab_spaces = 4 # Use field initialize shorthand if possible. # https://github.com/rust-lang/rustfmt/blob/master/Configurations.md#use_field_init_shorthand use_field_init_shorthand = true + +# Automatic grouping and ordering +group_imports = "StdExternalCrate" From 75fcea925253a95265608cb36aef3a5a7a890e63 Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Thu, 12 Oct 2023 09:59:39 +0300 Subject: [PATCH 2/2] bless whole source with rustfmt Signed-off-by: onur-ozkan --- .../activation_scheme_impl.rs | 4 +- .../init_activation_scheme.rs | 7 +- mm2src/adex_cli/src/adex_config.rs | 7 +- .../src/adex_proc/response_handler.rs | 10 +-- .../adex_proc/response_handler/orderbook.rs | 5 +- mm2src/adex_cli/src/cli.rs | 7 +- mm2src/adex_cli/src/helpers.rs | 7 +- mm2src/adex_cli/src/logging.rs | 5 +- mm2src/adex_cli/src/scenarios/init_mm2_cfg.rs | 7 +- .../src/scenarios/inquire_extentions.rs | 3 +- mm2src/adex_cli/src/scenarios/mm2_proc_mng.rs | 10 ++- mm2src/adex_cli/src/scenarios/mod.rs | 3 +- mm2src/adex_cli/src/tests/mod.rs | 1 + mm2src/adex_cli/src/transport.rs | 10 +-- mm2src/coins/coin_balance.rs | 18 +++-- mm2src/coins/coin_errors.rs | 8 +- mm2src/coins/eth.rs | 31 ++++--- mm2src/coins/eth/eth_tests.rs | 5 +- mm2src/coins/eth/eth_wasm_tests.rs | 5 +- mm2src/coins/eth/v2_activation.rs | 5 +- .../eth/web3_transport/http_transport.rs | 12 +-- .../eth/web3_transport/metamask_transport.rs | 10 ++- mm2src/coins/eth/web3_transport/mod.rs | 3 +- mm2src/coins/hd_confirm_address.rs | 3 +- mm2src/coins/hd_pubkey.rs | 3 +- mm2src/coins/hd_wallet.rs | 13 +-- .../coins/hd_wallet_storage/mock_storage.rs | 3 +- mm2src/coins/hd_wallet_storage/mod.rs | 13 +-- .../coins/hd_wallet_storage/sqlite_storage.rs | 10 ++- .../coins/hd_wallet_storage/wasm_storage.rs | 7 +- mm2src/coins/lightning.rs | 50 ++++++------ mm2src/coins/lightning/ln_conf.rs | 3 +- mm2src/coins/lightning/ln_db.rs | 3 +- mm2src/coins/lightning/ln_errors.rs | 8 +- mm2src/coins/lightning/ln_events.rs | 16 ++-- .../lightning/ln_filesystem_persister.rs | 26 +++--- mm2src/coins/lightning/ln_p2p.rs | 8 +- mm2src/coins/lightning/ln_platform.rs | 24 +++--- mm2src/coins/lightning/ln_serialization.rs | 17 ++-- mm2src/coins/lightning/ln_sql.rs | 22 ++--- mm2src/coins/lightning/ln_storage.rs | 7 +- mm2src/coins/lightning/ln_utils.rs | 22 ++--- mm2src/coins/lp_coins.rs | 29 +++---- mm2src/coins/lp_price.rs | 10 ++- mm2src/coins/my_tx_history_v2.rs | 23 +++--- mm2src/coins/nft.rs | 23 +++--- mm2src/coins/nft/nft_errors.rs | 7 +- mm2src/coins/nft/nft_structs.rs | 18 ++--- mm2src/coins/nft/nft_tests.rs | 6 +- mm2src/coins/nft/storage/db_test_helpers.rs | 12 +-- mm2src/coins/nft/storage/mod.rs | 10 ++- mm2src/coins/nft/storage/sql_storage.rs | 20 ++--- mm2src/coins/nft/storage/wasm/mod.rs | 3 +- mm2src/coins/nft/storage/wasm/nft_idb.rs | 3 +- mm2src/coins/nft/storage/wasm/wasm_storage.rs | 22 ++--- mm2src/coins/qrc20.rs | 64 ++++++++------- mm2src/coins/qrc20/history.rs | 15 ++-- mm2src/coins/qrc20/qrc20_tests.rs | 12 +-- mm2src/coins/qrc20/rpc_clients.rs | 3 +- mm2src/coins/qrc20/swap.rs | 7 +- mm2src/coins/rpc_command/account_balance.rs | 15 ++-- mm2src/coins/rpc_command/get_enabled_coins.rs | 3 +- mm2src/coins/rpc_command/get_new_address.rs | 22 ++--- .../hd_account_balance_rpc_error.rs | 8 +- .../coins/rpc_command/init_account_balance.rs | 13 +-- .../coins/rpc_command/init_create_account.rs | 16 ++-- .../init_scan_for_new_addresses.rs | 12 +-- mm2src/coins/rpc_command/init_withdraw.rs | 5 +- .../rpc_command/lightning/close_channel.rs | 3 +- .../rpc_command/lightning/connect_to_node.rs | 12 +-- .../rpc_command/lightning/generate_invoice.rs | 9 ++- .../lightning/get_channel_details.rs | 7 +- .../lightning/get_claimable_balances.rs | 5 +- .../lightning/get_payment_details.rs | 7 +- .../rpc_command/lightning/list_channels.rs | 9 ++- .../lightning/list_payments_by_filter.rs | 7 +- .../rpc_command/lightning/open_channel.rs | 19 ++--- .../rpc_command/lightning/send_payment.rs | 9 ++- .../rpc_command/lightning/trusted_nodes.rs | 7 +- .../rpc_command/lightning/update_channel.rs | 5 +- mm2src/coins/solana.rs | 42 +++++----- mm2src/coins/solana/solana_common.rs | 10 ++- mm2src/coins/solana/solana_common_tests.rs | 8 +- .../coins/solana/solana_decode_tx_helpers.rs | 6 +- mm2src/coins/solana/solana_tests.rs | 16 ++-- mm2src/coins/solana/spl.rs | 40 ++++----- mm2src/coins/solana/spl_tests.rs | 8 +- mm2src/coins/tendermint/ibc/transfer_v1.rs | 8 +- mm2src/coins/tendermint/iris/htlc.rs | 7 +- .../tendermint/rpc/tendermint_native_rpc.rs | 10 ++- .../tendermint/rpc/tendermint_wasm_rpc.rs | 6 +- mm2src/coins/tendermint/tendermint_coin.rs | 81 ++++++++++--------- mm2src/coins/tendermint/tendermint_token.rs | 42 +++++----- .../tendermint/tendermint_tx_history_v2.rs | 17 ++-- mm2src/coins/test_coin.rs | 26 +++--- mm2src/coins/tx_history_storage/mod.rs | 10 ++- .../sql_tx_history_storage_v2.rs | 14 ++-- .../tx_history_storage/tx_history_v2_tests.rs | 24 +++--- mm2src/coins/tx_history_storage/wasm/mod.rs | 3 +- .../tx_history_storage/wasm/tx_history_db.rs | 5 +- .../wasm/tx_history_storage_v1.rs | 6 +- .../wasm/tx_history_storage_v2.rs | 13 +-- mm2src/coins/utxo.rs | 26 +++--- mm2src/coins/utxo/bch.rs | 31 +++---- mm2src/coins/utxo/bchd_grpc.rs | 14 ++-- mm2src/coins/utxo/qtum.rs | 21 ++--- mm2src/coins/utxo/qtum_delegation.rs | 28 ++++--- mm2src/coins/utxo/rpc_clients.rs | 32 ++++---- mm2src/coins/utxo/slp.rs | 62 +++++++------- mm2src/coins/utxo/spv.rs | 3 +- mm2src/coins/utxo/tx_cache/dummy_tx_cache.rs | 6 +- mm2src/coins/utxo/tx_cache/fs_tx_cache.rs | 12 +-- mm2src/coins/utxo/tx_cache/mod.rs | 7 +- .../utxo/utxo_block_header_storage/mod.rs | 24 +++--- .../sql_block_header_storage.rs | 9 ++- .../wasm/indexeddb_block_header_storage.rs | 5 +- mm2src/coins/utxo/utxo_builder/mod.rs | 5 +- .../utxo/utxo_builder/utxo_arc_builder.rs | 24 +++--- .../utxo/utxo_builder/utxo_coin_builder.rs | 28 ++++--- .../utxo/utxo_builder/utxo_conf_builder.rs | 14 ++-- mm2src/coins/utxo/utxo_common.rs | 71 ++++++++-------- .../utxo_common/utxo_tx_history_v2_common.rs | 30 +++---- mm2src/coins/utxo/utxo_common_tests.rs | 22 ++--- mm2src/coins/utxo/utxo_standard.rs | 13 +-- mm2src/coins/utxo/utxo_tests.rs | 55 +++++++------ mm2src/coins/utxo/utxo_tx_history_v2.rs | 28 ++++--- mm2src/coins/utxo/utxo_wasm_tests.rs | 7 +- mm2src/coins/utxo/utxo_withdraw.rs | 16 ++-- mm2src/coins/utxo_signer/src/lib.rs | 3 +- mm2src/coins/utxo_signer/src/sign_common.rs | 3 +- mm2src/coins/utxo_signer/src/sign_params.rs | 3 +- mm2src/coins/utxo_signer/src/with_key_pair.rs | 7 +- mm2src/coins/utxo_signer/src/with_trezor.rs | 7 +- mm2src/coins/watcher_common.rs | 3 +- mm2src/coins/z_coin.rs | 72 +++++++++-------- mm2src/coins/z_coin/storage/blockdb/mod.rs | 3 +- mm2src/coins/z_coin/storage/walletdb/mod.rs | 3 +- mm2src/coins/z_coin/z_coin_errors.rs | 16 ++-- mm2src/coins/z_coin/z_coin_native_tests.rs | 5 +- mm2src/coins/z_coin/z_htlc.rs | 17 ++-- mm2src/coins/z_coin/z_rpc.rs | 10 ++- .../src/bch_with_tokens_activation.rs | 12 +-- mm2src/coins_activation/src/context.rs | 8 +- .../src/erc20_token_activation.rs | 8 +- .../src/eth_with_token_activation.rs | 14 ++-- mm2src/coins_activation/src/l2/init_l2.rs | 13 +-- .../coins_activation/src/l2/init_l2_error.rs | 6 +- .../src/lightning_activation.rs | 12 +-- .../src/platform_coin_with_tokens.rs | 3 +- mm2src/coins_activation/src/prelude.rs | 3 +- .../src/slp_token_activation.rs | 8 +- .../src/solana_with_tokens_activation.rs | 18 +++-- .../src/spl_token_activation.rs | 8 +- .../standalone_coin/init_standalone_coin.rs | 14 ++-- .../init_standalone_coin_error.rs | 6 +- .../src/tendermint_token_activation.rs | 8 +- .../src/tendermint_with_assets_activation.rs | 14 ++-- mm2src/coins_activation/src/token.rs | 5 +- .../src/utxo_activation/common_impl.rs | 14 ++-- .../utxo_activation/init_qtum_activation.rs | 24 +++--- .../init_utxo_standard_activation.rs | 24 +++--- .../init_utxo_standard_activation_error.rs | 6 +- .../init_utxo_standard_statuses.rs | 3 +- .../utxo_standard_activation_result.rs | 6 +- .../coins_activation/src/z_coin_activation.rs | 16 ++-- mm2src/common/build.rs | 3 +- mm2src/common/common.rs | 33 ++++---- mm2src/common/crash_reports.rs | 3 +- mm2src/common/custom_futures/repeatable.rs | 19 +++-- mm2src/common/custom_futures/timeout.rs | 8 +- .../abortable_system/abortable_queue.rs | 12 +-- .../abortable_system/graceful_shutdown.rs | 8 +- .../common/executor/abortable_system/mod.rs | 13 +-- .../executor/abortable_system/simple_map.rs | 12 +-- mm2src/common/executor/native_executor.rs | 5 +- mm2src/common/executor/spawner.rs | 3 +- mm2src/common/executor/wasm_executor.rs | 12 +-- mm2src/common/jsonrpc_client.rs | 5 +- mm2src/common/log.rs | 27 ++++--- mm2src/common/log/native_log.rs | 3 +- mm2src/common/log/wasm_log.rs | 13 +-- mm2src/common/seri.rs | 3 +- .../common/shared_ref_counter/src/enable.rs | 3 +- mm2src/common/time_cache.rs | 5 +- mm2src/common/wasm.rs | 6 +- mm2src/common/wio.rs | 5 +- mm2src/crypto/src/bip32_child.rs | 8 +- mm2src/crypto/src/crypto_ctx.rs | 22 ++--- mm2src/crypto/src/global_hd_ctx.rs | 14 ++-- mm2src/crypto/src/hw_client.rs | 10 ++- mm2src/crypto/src/hw_ctx.rs | 20 ++--- mm2src/crypto/src/hw_error.rs | 3 +- mm2src/crypto/src/hw_rpc_task.rs | 10 ++- mm2src/crypto/src/lib.rs | 17 ++-- mm2src/crypto/src/metamask_ctx.rs | 11 +-- mm2src/crypto/src/metamask_login.rs | 6 +- mm2src/crypto/src/shared_db_id.rs | 3 +- mm2src/crypto/src/standard_hd_path.rs | 12 ++- mm2src/crypto/src/xpub.rs | 3 +- mm2src/db_common/src/sql_condition.rs | 5 +- mm2src/db_common/src/sql_constraint.rs | 10 ++- mm2src/db_common/src/sql_create.rs | 10 ++- mm2src/db_common/src/sql_delete.rs | 5 +- mm2src/db_common/src/sql_insert.rs | 8 +- mm2src/db_common/src/sql_query.rs | 7 +- mm2src/db_common/src/sql_update.rs | 7 +- mm2src/db_common/src/sqlite.rs | 10 +-- mm2src/derives/enum_from/src/from_inner.rs | 3 +- .../derives/enum_from/src/from_stringify.rs | 3 +- mm2src/derives/enum_from/src/from_trait.rs | 3 +- mm2src/derives/enum_from/src/lib.rs | 3 +- mm2src/derives/ser_error_derive/src/lib.rs | 5 +- mm2src/hw_common/src/transport/libusb.rs | 8 +- .../hw_common/src/transport/webusb_driver.rs | 3 +- mm2src/mm2_bin_lib/build.rs | 7 +- mm2src/mm2_bin_lib/src/lib.rs | 3 +- mm2src/mm2_bin_lib/src/mm2_native_lib.rs | 14 ++-- mm2src/mm2_bin_lib/src/mm2_wasm_lib.rs | 3 +- mm2src/mm2_bitcoin/chain/src/block.rs | 6 +- mm2src/mm2_bitcoin/chain/src/block_header.rs | 6 +- mm2src/mm2_bitcoin/chain/src/lib.rs | 6 +- mm2src/mm2_bitcoin/chain/src/merkle_root.rs | 3 +- mm2src/mm2_bitcoin/chain/src/read_and_hash.rs | 3 +- mm2src/mm2_bitcoin/chain/src/transaction.rs | 8 +- mm2src/mm2_bitcoin/crypto/src/lib.rs | 6 +- mm2src/mm2_bitcoin/keys/src/address.rs | 7 +- mm2src/mm2_bitcoin/keys/src/display.rs | 1 + mm2src/mm2_bitcoin/keys/src/error.rs | 3 +- mm2src/mm2_bitcoin/keys/src/keypair.rs | 9 ++- mm2src/mm2_bitcoin/keys/src/lib.rs | 11 ++- mm2src/mm2_bitcoin/keys/src/private.rs | 11 ++- mm2src/mm2_bitcoin/keys/src/public.rs | 6 +- mm2src/mm2_bitcoin/keys/src/segwitaddress.rs | 3 +- mm2src/mm2_bitcoin/keys/src/signature.rs | 3 +- mm2src/mm2_bitcoin/primitives/src/bytes.rs | 3 +- mm2src/mm2_bitcoin/primitives/src/hash.rs | 5 +- .../mm2_bitcoin/rpc/src/v1/types/address.rs | 6 +- .../src/v1/types/block_template_request.rs | 3 +- mm2src/mm2_bitcoin/rpc/src/v1/types/bytes.rs | 8 +- .../rpc/src/v1/types/get_block_response.rs | 6 +- .../rpc/src/v1/types/get_tx_out_response.rs | 3 +- mm2src/mm2_bitcoin/rpc/src/v1/types/hash.rs | 15 ++-- mm2src/mm2_bitcoin/rpc/src/v1/types/script.rs | 6 +- .../rpc/src/v1/types/transaction.rs | 18 +++-- mm2src/mm2_bitcoin/rpc/src/v1/types/uint.rs | 8 +- mm2src/mm2_bitcoin/script/src/error.rs | 1 + mm2src/mm2_bitcoin/script/src/num.rs | 3 +- mm2src/mm2_bitcoin/script/src/opcode.rs | 3 +- mm2src/mm2_bitcoin/script/src/script.rs | 6 +- mm2src/mm2_bitcoin/script/src/sign.rs | 5 +- mm2src/mm2_bitcoin/script/src/stack.rs | 4 +- .../serialization/src/compact_integer.rs | 4 +- mm2src/mm2_bitcoin/serialization/src/impls.rs | 3 +- mm2src/mm2_bitcoin/serialization/src/lib.rs | 3 +- mm2src/mm2_bitcoin/serialization/src/list.rs | 1 + .../mm2_bitcoin/serialization/src/reader.rs | 3 +- .../mm2_bitcoin/serialization/src/stream.rs | 5 +- mm2src/mm2_bitcoin/spv_validation/src/conf.rs | 10 ++- .../spv_validation/src/helpers_validation.rs | 17 ++-- mm2src/mm2_bitcoin/spv_validation/src/lib.rs | 4 +- .../spv_validation/src/spv_proof.rs | 6 +- .../mm2_bitcoin/spv_validation/src/storage.rs | 3 +- mm2src/mm2_bitcoin/spv_validation/src/work.rs | 16 ++-- mm2src/mm2_core/src/event_dispatcher.rs | 16 ++-- mm2src/mm2_core/src/mm_ctx.rs | 15 ++-- mm2src/mm2_db/src/indexed_db/be_big_uint.rs | 8 +- mm2src/mm2_db/src/indexed_db/db_driver.rs | 7 +- mm2src/mm2_db/src/indexed_db/db_lock.rs | 6 +- .../mm2_db/src/indexed_db/drivers/builder.rs | 6 +- .../src/indexed_db/drivers/cursor/cursor.rs | 10 ++- .../indexed_db/drivers/cursor/empty_cursor.rs | 3 +- .../drivers/cursor/multi_key_bound_cursor.rs | 8 +- .../drivers/cursor/multi_key_cursor.rs | 3 +- .../drivers/cursor/single_key_bound_cursor.rs | 3 +- .../drivers/cursor/single_key_cursor.rs | 3 +- .../src/indexed_db/drivers/object_store.rs | 8 +- .../src/indexed_db/drivers/transaction.rs | 10 ++- .../mm2_db/src/indexed_db/indexed_cursor.rs | 19 +++-- mm2src/mm2_db/src/indexed_db/indexed_db.rs | 13 +-- mm2src/mm2_err_handle/src/lib.rs | 3 +- mm2src/mm2_err_handle/src/map_to_mm_fut.rs | 6 +- mm2src/mm2_err_handle/src/mm_error.rs | 16 ++-- mm2src/mm2_err_handle/src/mm_json_error.rs | 6 +- mm2src/mm2_eth/src/address.rs | 6 +- mm2src/mm2_eth/src/eip712.rs | 3 +- mm2src/mm2_eth/src/eip712_encode.rs | 10 ++- mm2src/mm2_eth/src/recovery.rs | 6 +- mm2src/mm2_event_stream/src/behaviour.rs | 3 +- mm2src/mm2_event_stream/src/controller.rs | 3 +- mm2src/mm2_event_stream/src/lib.rs | 3 +- mm2src/mm2_git/src/github_client.rs | 4 +- mm2src/mm2_gui_storage/src/account/mod.rs | 6 +- .../account/storage/account_storage_tests.rs | 8 +- .../src/account/storage/mod.rs | 10 ++- .../src/account/storage/sqlite_storage.rs | 16 ++-- .../src/account/storage/wasm_storage.rs | 10 ++- mm2src/mm2_gui_storage/src/context.rs | 6 +- mm2src/mm2_gui_storage/src/rpc_commands.rs | 12 +-- mm2src/mm2_io/src/file_lock.rs | 6 +- mm2src/mm2_io/src/fs.rs | 11 +-- mm2src/mm2_main/src/database.rs | 4 +- mm2src/mm2_main/src/database/my_orders.rs | 8 +- mm2src/mm2_main/src/database/my_swaps.rs | 8 +- mm2src/mm2_main/src/database/stats_nodes.rs | 8 +- mm2src/mm2_main/src/database/stats_swaps.rs | 6 +- mm2src/mm2_main/src/lp_dispatcher.rs | 10 ++- mm2src/mm2_main/src/lp_init/init_context.rs | 8 +- mm2src/mm2_main/src/lp_init/init_hw.rs | 6 +- mm2src/mm2_main/src/lp_init/init_metamask.rs | 6 +- mm2src/mm2_main/src/lp_message_service.rs | 14 ++-- mm2src/mm2_main/src/lp_native_dex.rs | 11 +-- mm2src/mm2_main/src/lp_network.rs | 3 +- mm2src/mm2_main/src/lp_ordermatch.rs | 24 +++--- .../mm2_main/src/lp_ordermatch/best_orders.rs | 9 ++- mm2src/mm2_main/src/lp_ordermatch/lp_bot.rs | 12 +-- .../src/lp_ordermatch/my_orders_storage.rs | 35 ++++---- .../src/lp_ordermatch/new_protocol.rs | 6 +- .../lp_ordermatch/order_requests_tracker.rs | 6 +- .../src/lp_ordermatch/orderbook_depth.rs | 8 +- .../src/lp_ordermatch/ordermatch_wasm_db.rs | 11 +-- .../src/lp_ordermatch/simple_market_maker.rs | 29 ++++--- .../simple_market_maker_tests.rs | 5 +- mm2src/mm2_main/src/lp_stats.rs | 7 +- mm2src/mm2_main/src/lp_swap.rs | 26 +++--- mm2src/mm2_main/src/lp_swap/check_balance.rs | 5 +- mm2src/mm2_main/src/lp_swap/maker_swap.rs | 47 ++++++----- mm2src/mm2_main/src/lp_swap/maker_swap_v2.rs | 19 ++--- .../mm2_main/src/lp_swap/max_maker_vol_rpc.rs | 3 +- .../mm2_main/src/lp_swap/my_swaps_storage.rs | 24 +++--- mm2src/mm2_main/src/lp_swap/pubkey_banning.rs | 6 +- .../src/lp_swap/recreate_swap_data.rs | 16 ++-- mm2src/mm2_main/src/lp_swap/saved_swap.rs | 20 +++-- mm2src/mm2_main/src/lp_swap/swap_lock.rs | 27 ++++--- mm2src/mm2_main/src/lp_swap/swap_wasm_db.rs | 11 +-- mm2src/mm2_main/src/lp_swap/swap_watcher.rs | 16 ++-- mm2src/mm2_main/src/lp_swap/taker_swap.rs | 47 ++++++----- mm2src/mm2_main/src/lp_swap/taker_swap_v2.rs | 19 ++--- mm2src/mm2_main/src/lp_swap/trade_preimage.rs | 10 ++- mm2src/mm2_main/src/mm2.rs | 28 +++---- .../src/notification/telegram/telegram.rs | 12 ++- mm2src/mm2_main/src/ordermatch_tests.rs | 12 +-- mm2src/mm2_main/src/rpc.rs | 20 +++-- .../mm2_main/src/rpc/dispatcher/dispatcher.rs | 26 +++--- .../src/rpc/dispatcher/dispatcher_legacy.rs | 11 +-- .../src/rpc/lp_commands/lp_commands_legacy.rs | 7 +- mm2src/mm2_main/src/rpc/rate_limiter.rs | 10 ++- mm2src/mm2_main/src/wasm_tests.rs | 3 +- .../docker_tests/docker_ordermatch_tests.rs | 10 ++- .../tests/docker_tests/docker_tests_common.rs | 27 +++---- .../tests/docker_tests/docker_tests_inner.rs | 18 +++-- .../tests/docker_tests/qrc20_tests.rs | 14 ++-- .../mm2_main/tests/docker_tests/slp_tests.rs | 10 ++- .../tests/docker_tests/solana_tests.rs | 3 +- .../tests/docker_tests/swap_proto_v2_tests.rs | 3 +- .../tests/docker_tests/swap_watcher_tests.rs | 14 ++-- .../swaps_confs_settings_sync_tests.rs | 10 ++- .../docker_tests/swaps_file_lock_tests.rs | 10 ++- mm2src/mm2_main/tests/docker_tests_main.rs | 1 + .../tests/integration_tests_common/mod.rs | 7 +- .../tests/mm2_tests/bch_and_slp_tests.rs | 7 +- .../tests/mm2_tests/best_orders_tests.rs | 16 ++-- mm2src/mm2_main/tests/mm2_tests/eth_tests.rs | 7 +- .../tests/mm2_tests/lightning_tests.rs | 8 +- .../tests/mm2_tests/mm2_tests_inner.rs | 21 ++--- .../tests/mm2_tests/orderbook_sync_tests.rs | 14 ++-- .../mm2_tests/tendermint_ibc_asset_tests.rs | 6 +- .../tests/mm2_tests/tendermint_tests.rs | 9 ++- .../mm2_main/tests/mm2_tests/z_coin_tests.rs | 16 ++-- mm2src/mm2_metamask/src/eip_1193_provider.rs | 5 +- mm2src/mm2_metamask/src/metamask.rs | 5 +- mm2src/mm2_metrics/src/lib.rs | 10 +-- mm2src/mm2_metrics/src/mm_metrics.rs | 20 ++--- mm2src/mm2_metrics/src/recorder.rs | 7 +- mm2src/mm2_net/src/grpc_web.rs | 9 ++- mm2src/mm2_net/src/ip_addr.rs | 12 +-- mm2src/mm2_net/src/native_http.rs | 10 +-- mm2src/mm2_net/src/native_tls/acceptor.rs | 12 +-- mm2src/mm2_net/src/native_tls/builder.rs | 6 +- mm2src/mm2_net/src/network_event.rs | 3 +- mm2src/mm2_net/src/p2p.rs | 3 +- mm2src/mm2_net/src/sse_handler.rs | 3 +- mm2src/mm2_net/src/transport.rs | 1 - mm2src/mm2_net/src/wasm_http.rs | 9 ++- mm2src/mm2_net/src/wasm_ws.rs | 17 ++-- mm2src/mm2_number/src/big_int_str.rs | 6 +- mm2src/mm2_number/src/bigdecimal_custom.rs | 3 +- mm2src/mm2_number/src/fraction.rs | 5 +- mm2src/mm2_number/src/lib.rs | 8 +- mm2src/mm2_number/src/mm_number.rs | 16 ++-- mm2src/mm2_number/src/mm_number_multi_repr.rs | 7 +- mm2src/mm2_p2p/src/behaviours/atomicdex.rs | 20 ++--- mm2src/mm2_p2p/src/behaviours/mod.rs | 11 +-- .../mm2_p2p/src/behaviours/peers_exchange.rs | 9 ++- mm2src/mm2_p2p/src/behaviours/ping.rs | 3 +- .../src/behaviours/request_response.rs | 5 +- mm2src/mm2_p2p/src/lib.rs | 19 ++--- mm2src/mm2_p2p/src/network.rs | 3 +- mm2src/mm2_p2p/src/relay_address.rs | 6 +- mm2src/mm2_p2p/src/swarm_runtime.rs | 5 +- mm2src/mm2_rpc/src/data/legacy.rs | 6 +- mm2src/mm2_rpc/src/data/legacy/orders.rs | 6 +- mm2src/mm2_rpc/src/data/legacy/wallet.rs | 3 +- mm2src/mm2_rpc/src/wasm_rpc.rs | 5 +- mm2src/mm2_state_machine/src/state_machine.rs | 11 ++- .../src/storable_state_machine.rs | 9 ++- mm2src/mm2_test_helpers/src/for_tests.rs | 25 +++--- mm2src/mm2_test_helpers/src/structs.rs | 10 ++- mm2src/rpc_task/src/handle.rs | 10 ++- mm2src/rpc_task/src/lib.rs | 5 +- mm2src/rpc_task/src/manager.rs | 16 ++-- mm2src/rpc_task/src/rpc_common.rs | 3 +- mm2src/rpc_task/src/task.rs | 3 +- mm2src/trezor/src/client.rs | 10 ++- mm2src/trezor/src/error.rs | 7 +- mm2src/trezor/src/proto/mod.rs | 5 +- mm2src/trezor/src/response.rs | 13 +-- mm2src/trezor/src/response_processor.rs | 5 +- mm2src/trezor/src/result_handler.rs | 3 +- mm2src/trezor/src/transport/mod.rs | 5 +- mm2src/trezor/src/transport/protocol.rs | 7 +- mm2src/trezor/src/transport/usb.rs | 13 +-- mm2src/trezor/src/transport/webusb.rs | 10 +-- mm2src/trezor/src/trezor_rpc_task.rs | 11 +-- mm2src/trezor/src/utxo/prev_tx.rs | 3 +- mm2src/trezor/src/utxo/sign_utxo.rs | 5 +- mm2src/trezor/src/utxo/unsigned_tx.rs | 5 +- mm2src/trezor/src/utxo/utxo_command.rs | 3 +- 427 files changed, 2681 insertions(+), 2034 deletions(-) diff --git a/mm2src/adex_cli/src/activation_scheme_db/activation_scheme_impl.rs b/mm2src/adex_cli/src/activation_scheme_db/activation_scheme_impl.rs index 63c89e5efc..c58628294f 100644 --- a/mm2src/adex_cli/src/activation_scheme_db/activation_scheme_impl.rs +++ b/mm2src/adex_cli/src/activation_scheme_db/activation_scheme_impl.rs @@ -1,8 +1,8 @@ -use anyhow::{anyhow, bail, Result}; -use serde_json::Value as Json; use std::collections::HashMap; +use anyhow::{anyhow, bail, Result}; use common::log::{debug, error}; +use serde_json::Value as Json; use super::init_activation_scheme::get_activation_scheme_path; use crate::helpers::read_json_file; diff --git a/mm2src/adex_cli/src/activation_scheme_db/init_activation_scheme.rs b/mm2src/adex_cli/src/activation_scheme_db/init_activation_scheme.rs index b0dd8c956c..ac24098e9c 100644 --- a/mm2src/adex_cli/src/activation_scheme_db/init_activation_scheme.rs +++ b/mm2src/adex_cli/src/activation_scheme_db/init_activation_scheme.rs @@ -1,11 +1,12 @@ +use std::fs::OpenOptions; +use std::io::Write; +use std::path::PathBuf; + use anyhow::{anyhow, Result}; use common::log::{error, info}; use http::StatusCode; use itertools::Itertools; use mm2_net::transport::slurp_url; -use std::fs::OpenOptions; -use std::io::Write; -use std::path::PathBuf; use crate::adex_config::AdexConfigImpl; use crate::error_anyhow; diff --git a/mm2src/adex_cli/src/adex_config.rs b/mm2src/adex_cli/src/adex_config.rs index aee4fec2d7..374c859be6 100644 --- a/mm2src/adex_cli/src/adex_config.rs +++ b/mm2src/adex_cli/src/adex_config.rs @@ -1,11 +1,12 @@ +use std::fmt::{Display, Formatter}; +use std::fs; +use std::path::{Path, PathBuf}; + use anyhow::{anyhow, bail, Result}; use directories::ProjectDirs; use inquire::Password; use log::{error, info, warn}; use serde::{Deserialize, Serialize}; -use std::fmt::{Display, Formatter}; -use std::fs; -use std::path::{Path, PathBuf}; use crate::adex_proc::SmartFractPrecision; use crate::helpers::rewrite_json_file; diff --git a/mm2src/adex_cli/src/adex_proc/response_handler.rs b/mm2src/adex_cli/src/adex_proc/response_handler.rs index 74a0838136..248a1202f3 100644 --- a/mm2src/adex_cli/src/adex_proc/response_handler.rs +++ b/mm2src/adex_cli/src/adex_proc/response_handler.rs @@ -2,22 +2,22 @@ #[path = "response_handler/smart_fraction_fmt.rs"] mod smart_fraction_fmt; -pub(crate) use smart_fraction_fmt::SmartFractPrecision; +use std::cell::RefCell; +use std::fmt::Debug; +use std::io::Write; use anyhow::{anyhow, Result}; +use common::{write_safe::io::WriteSafeIO, write_safe_io, writeln_safe_io}; use itertools::Itertools; use log::{error, info}; use mm2_rpc::data::legacy::{BalanceResponse, CoinInitResponse, GetEnabledResponse, Mm2RpcResult, MmVersionResponse, OrderbookResponse, SellBuyResponse, Status}; use serde_json::Value as Json; -use std::cell::RefCell; -use std::fmt::Debug; -use std::io::Write; +pub(crate) use smart_fraction_fmt::SmartFractPrecision; use super::OrderbookConfig; use crate::adex_config::AdexConfig; use crate::error_anyhow; -use common::{write_safe::io::WriteSafeIO, write_safe_io, writeln_safe_io}; pub(crate) trait ResponseHandler { fn print_response(&self, response: Json) -> Result<()>; diff --git a/mm2src/adex_cli/src/adex_proc/response_handler/orderbook.rs b/mm2src/adex_cli/src/adex_proc/response_handler/orderbook.rs index c3641f5aa5..57b4dca335 100644 --- a/mm2src/adex_cli/src/adex_proc/response_handler/orderbook.rs +++ b/mm2src/adex_cli/src/adex_proc/response_handler/orderbook.rs @@ -1,8 +1,9 @@ -use mm2_number::bigdecimal::ToPrimitive; -use mm2_rpc::data::legacy::{AggregatedOrderbookEntry, OrderConfirmationsSettings}; use std::cmp::Ordering; use std::fmt::{Display, Formatter}; +use mm2_number::bigdecimal::ToPrimitive; +use mm2_rpc::data::legacy::{AggregatedOrderbookEntry, OrderConfirmationsSettings}; + use super::{smart_fraction_fmt::{SmartFractPrecision, SmartFractionFmt}, OrderbookConfig}; diff --git a/mm2src/adex_cli/src/cli.rs b/mm2src/adex_cli/src/cli.rs index 3ab9672a1c..be31e187d2 100644 --- a/mm2src/adex_cli/src/cli.rs +++ b/mm2src/adex_cli/src/cli.rs @@ -1,12 +1,13 @@ +use std::collections::HashSet; +use std::mem::take; +use std::str::FromStr; + use anyhow::Result; use clap::{ArgAction, Args, Parser, Subcommand, ValueEnum}; use common::serde_derive::Serialize; use mm2_number::{bigdecimal::ParseBigDecimalError, BigDecimal, MmNumber}; use mm2_rpc::data::legacy::{MatchBy, OrderType, SellBuyRequest}; use rpc::v1::types::H256 as H256Json; -use std::collections::HashSet; -use std::mem::take; -use std::str::FromStr; use uuid::Uuid; use crate::adex_config::{get_config, set_config, AdexConfig}; diff --git a/mm2src/adex_cli/src/helpers.rs b/mm2src/adex_cli/src/helpers.rs index 6d6cef2a90..1111138943 100644 --- a/mm2src/adex_cli/src/helpers.rs +++ b/mm2src/adex_cli/src/helpers.rs @@ -1,12 +1,13 @@ -use anyhow::{anyhow, Result}; -use common::log::error; -use serde::{Deserialize, Serialize}; use std::fs; use std::io::Write; use std::ops::Deref; #[cfg(unix)] use std::os::unix::fs::PermissionsExt; use std::path::Path; +use anyhow::{anyhow, Result}; +use common::log::error; +use serde::{Deserialize, Serialize}; + use crate::error_anyhow; pub(crate) fn rewrite_data_file(data: T, file: &str) -> Result<()> diff --git a/mm2src/adex_cli/src/logging.rs b/mm2src/adex_cli/src/logging.rs index d02c6d6a31..fbe5974c60 100644 --- a/mm2src/adex_cli/src/logging.rs +++ b/mm2src/adex_cli/src/logging.rs @@ -1,8 +1,9 @@ #[cfg(not(any(test, target_arch = "wasm32")))] -use log::LevelFilter; -#[cfg(not(any(test, target_arch = "wasm32")))] use std::io::Write; +#[cfg(not(any(test, target_arch = "wasm32")))] +use log::LevelFilter; + #[cfg(not(any(test, target_arch = "wasm32")))] pub(super) fn init_logging() { let mut builder = env_logger::builder(); diff --git a/mm2src/adex_cli/src/scenarios/init_mm2_cfg.rs b/mm2src/adex_cli/src/scenarios/init_mm2_cfg.rs index d58b035f73..2803d80604 100644 --- a/mm2src/adex_cli/src/scenarios/init_mm2_cfg.rs +++ b/mm2src/adex_cli/src/scenarios/init_mm2_cfg.rs @@ -1,3 +1,7 @@ +use std::net::Ipv4Addr; +use std::ops::Not; +use std::path::Path; + use anyhow::{anyhow, Result}; use bip39::{Language, Mnemonic, MnemonicType}; use common::log::{error, info}; @@ -5,9 +9,6 @@ use common::password_policy; use inquire::{validator::Validation, Confirm, CustomType, CustomUserError, Text}; use passwords::PasswordGenerator; use serde::Serialize; -use std::net::Ipv4Addr; -use std::ops::Not; -use std::path::Path; use super::inquire_extentions::{InquireOption, DEFAULT_DEFAULT_OPTION_BOOL_FORMATTER, DEFAULT_OPTION_BOOL_FORMATTER, OPTION_BOOL_PARSER}; diff --git a/mm2src/adex_cli/src/scenarios/inquire_extentions.rs b/mm2src/adex_cli/src/scenarios/inquire_extentions.rs index e1d40d7a6b..5ebdd70454 100644 --- a/mm2src/adex_cli/src/scenarios/inquire_extentions.rs +++ b/mm2src/adex_cli/src/scenarios/inquire_extentions.rs @@ -1,6 +1,7 @@ -use inquire::parser::DEFAULT_BOOL_PARSER; use std::str::FromStr; +use inquire::parser::DEFAULT_BOOL_PARSER; + #[derive(Clone)] pub(super) enum InquireOption { Some(T), diff --git a/mm2src/adex_cli/src/scenarios/mm2_proc_mng.rs b/mm2src/adex_cli/src/scenarios/mm2_proc_mng.rs index 36a864b5f8..70af063d06 100644 --- a/mm2src/adex_cli/src/scenarios/mm2_proc_mng.rs +++ b/mm2src/adex_cli/src/scenarios/mm2_proc_mng.rs @@ -1,13 +1,13 @@ -use anyhow::{anyhow, Result}; -use common::log::{error, info}; use std::env; use std::path::PathBuf; -use crate::error_anyhow; - +use anyhow::{anyhow, Result}; +use common::log::{error, info}; #[cfg(not(target_os = "macos"))] use sysinfo::{PidExt, ProcessExt, System, SystemExt}; +use crate::error_anyhow; + #[cfg(windows)] mod reexport { pub(super) use std::ffi::CString; @@ -15,6 +15,7 @@ mod reexport { pub(super) use std::mem::size_of; pub(super) use std::ptr::null; pub(super) use std::u32; + pub(super) use winapi::um::processthreadsapi::{CreateProcessA, OpenProcess, TerminateProcess, PROCESS_INFORMATION, STARTUPINFOA}; pub(super) use winapi::um::winnt::{PROCESS_TERMINATE, SYNCHRONIZE}; @@ -48,6 +49,7 @@ mod macos_reexport { pub(super) use std::process::Command; pub(super) use std::thread::sleep; pub(super) use std::time::Duration; + pub(super) use sysinfo::{ProcessExt, System, SystemExt}; pub(super) const LAUNCHCTL_MM2_ID: &str = "com.komodoproject.mm2"; } diff --git a/mm2src/adex_cli/src/scenarios/mod.rs b/mm2src/adex_cli/src/scenarios/mod.rs index 070748c83c..f923da17ad 100644 --- a/mm2src/adex_cli/src/scenarios/mod.rs +++ b/mm2src/adex_cli/src/scenarios/mod.rs @@ -7,11 +7,10 @@ use anyhow::Result; use init_coins::init_coins; use init_mm2_cfg::init_mm2_cfg; use log::info; +pub(super) use mm2_proc_mng::{get_status, start_process, stop_process}; use super::activation_scheme_db::init_activation_scheme; -pub(super) use mm2_proc_mng::{get_status, start_process, stop_process}; - pub(super) async fn init(cfg_file: &str, coins_file: &str) { let _ = init_impl(cfg_file, coins_file).await; } async fn init_impl(cfg_file: &str, coins_file: &str) -> Result<()> { diff --git a/mm2src/adex_cli/src/tests/mod.rs b/mm2src/adex_cli/src/tests/mod.rs index 9777a268da..b478760197 100644 --- a/mm2src/adex_cli/src/tests/mod.rs +++ b/mm2src/adex_cli/src/tests/mod.rs @@ -1,5 +1,6 @@ use std::io::Write; use std::time::Duration; + use tokio::io::AsyncWriteExt; use tokio::net::{TcpListener, TcpStream}; diff --git a/mm2src/adex_cli/src/transport.rs b/mm2src/adex_cli/src/transport.rs index 92e28c0655..f5ef19f057 100644 --- a/mm2src/adex_cli/src/transport.rs +++ b/mm2src/adex_cli/src/transport.rs @@ -1,11 +1,10 @@ use anyhow::{anyhow, bail, Result}; use async_trait::async_trait; -use http::{HeaderMap, StatusCode}; -use serde::{Deserialize, Serialize}; - use common::log::{error, warn}; +use http::{HeaderMap, StatusCode}; use hyper_dangerous::get_hyper_client_dangerous; use mm2_net::native_http::SlurpHttpClient; +use serde::{Deserialize, Serialize}; use crate::{error_anyhow, error_bail, warn_bail}; @@ -85,12 +84,13 @@ impl Response for (StatusCode, HeaderMap, Vec) { mod hyper_dangerous { + use std::sync::Arc; + use std::time::SystemTime; + use hyper::{client::HttpConnector, Body, Client}; use hyper_rustls::{HttpsConnector, HttpsConnectorBuilder}; use rustls::client::{ServerCertVerified, ServerCertVerifier}; use rustls::{RootCertStore, DEFAULT_CIPHER_SUITES, DEFAULT_VERSIONS}; - use std::sync::Arc; - use std::time::SystemTime; use super::*; diff --git a/mm2src/coins/coin_balance.rs b/mm2src/coins/coin_balance.rs index 8dca163419..8fa843be51 100644 --- a/mm2src/coins/coin_balance.rs +++ b/mm2src/coins/coin_balance.rs @@ -1,8 +1,7 @@ -use crate::hd_pubkey::HDXPubExtractor; -use crate::hd_wallet::{HDAccountOps, HDAddressId, HDWalletCoinOps, HDWalletOps, NewAccountCreatingError, - NewAddressDerivingError}; -use crate::{BalanceError, BalanceResult, CoinBalance, CoinWithDerivationMethod, DerivationMethod, HDAddress, - MarketCoinOps}; +use std::collections::HashMap; +use std::ops::Range; +use std::{fmt, iter}; + use async_trait::async_trait; use common::log::{debug, info}; use crypto::{Bip44Chain, RpcDerivationPath}; @@ -10,9 +9,12 @@ use futures::compat::Future01CompatExt; use mm2_err_handle::prelude::*; use mm2_number::BigDecimal; #[cfg(test)] use mocktopus::macros::*; -use std::collections::HashMap; -use std::ops::Range; -use std::{fmt, iter}; + +use crate::hd_pubkey::HDXPubExtractor; +use crate::hd_wallet::{HDAccountOps, HDAddressId, HDWalletCoinOps, HDWalletOps, NewAccountCreatingError, + NewAddressDerivingError}; +use crate::{BalanceError, BalanceResult, CoinBalance, CoinWithDerivationMethod, DerivationMethod, HDAddress, + MarketCoinOps}; pub type AddressIdRange = Range; diff --git a/mm2src/coins/coin_errors.rs b/mm2src/coins/coin_errors.rs index c9672082c7..e28bcda2e3 100644 --- a/mm2src/coins/coin_errors.rs +++ b/mm2src/coins/coin_errors.rs @@ -1,9 +1,11 @@ -use crate::{eth::Web3RpcError, my_tx_history_v2::MyTxHistoryErrorV2, utxo::rpc_clients::UtxoRpcError, DelegationError, - NumConversError, TxHistoryError, UnexpectedDerivationMethod, WithdrawError}; +use std::num::TryFromIntError; + use futures01::Future; use mm2_err_handle::prelude::MmError; use spv_validation::helpers_validation::SPVError; -use std::num::TryFromIntError; + +use crate::{eth::Web3RpcError, my_tx_history_v2::MyTxHistoryErrorV2, utxo::rpc_clients::UtxoRpcError, DelegationError, + NumConversError, TxHistoryError, UnexpectedDerivationMethod, WithdrawError}; /// Helper type used as result for swap payment validation function(s) pub type ValidatePaymentFut = Box> + Send>; diff --git a/mm2src/coins/eth.rs b/mm2src/coins/eth.rs index 8514af4ab6..69cba24f23 100644 --- a/mm2src/coins/eth.rs +++ b/mm2src/coins/eth.rs @@ -20,9 +20,14 @@ // // Copyright © 2022 AtomicDEX. All rights reserved. // -use super::eth::Action::{Call, Create}; -use crate::lp_price::get_base_price_in_rel; -use crate::nft::nft_structs::{ContractType, ConvertChain, TransactionNftDetails, WithdrawErc1155, WithdrawErc721}; +use std::collections::HashMap; +use std::convert::{TryFrom, TryInto}; +use std::ops::Deref; +#[cfg(not(target_arch = "wasm32"))] use std::path::PathBuf; +use std::str::FromStr; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; +use std::sync::{Arc, Mutex}; + use async_trait::async_trait; use bitcrypto::{keccak256, ripemd160, sha256}; use common::custom_futures::repeatable::{Ready, Retry, RetryOnError}; @@ -60,18 +65,15 @@ use secp256k1::PublicKey; use serde_json::{self as json, Value as Json}; use serialization::{CompactInteger, Serializable, Stream}; use sha3::{Digest, Keccak256}; -use std::collections::HashMap; -use std::convert::{TryFrom, TryInto}; -use std::ops::Deref; -#[cfg(not(target_arch = "wasm32"))] use std::path::PathBuf; -use std::str::FromStr; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; -use std::sync::{Arc, Mutex}; use web3::types::{Action as TraceAction, BlockId, BlockNumber, Bytes, CallRequest, FilterBuilder, Log, Trace, TraceFilterBuilder, Transaction as Web3Transaction, TransactionId, U64}; use web3::{self, Web3}; use web3_transport::{http_transport::HttpTransportNode, EthFeeHistoryNamespace, Web3Transport}; +use super::eth::Action::{Call, Create}; +use crate::lp_price::get_base_price_in_rel; +use crate::nft::nft_structs::{ContractType, ConvertChain, TransactionNftDetails, WithdrawErc1155, WithdrawErc721}; + cfg_wasm32! { use crypto::MetamaskArc; use ethereum_types::{H264, H520}; @@ -79,6 +81,8 @@ cfg_wasm32! { use web3::types::TransactionRequest; } +pub use rlp; + use super::watcher_common::{validate_watcher_reward, REWARD_GAS_AMOUNT}; use super::{coin_conf, lp_coinfind_or_err, AsyncMutex, BalanceError, BalanceFut, CheckIfMyPaymentSentArgs, CoinBalance, CoinFutSpawner, CoinProtocol, CoinTransportMetrics, CoinsContext, ConfirmPaymentInput, @@ -99,20 +103,21 @@ use super::{coin_conf, lp_coinfind_or_err, AsyncMutex, BalanceError, BalanceFut, WithdrawError, WithdrawFee, WithdrawFut, WithdrawRequest, WithdrawResult, EARLY_CONFIRMATION_ERR_LOG, INVALID_CONTRACT_ADDRESS_ERR_LOG, INVALID_PAYMENT_STATE_ERR_LOG, INVALID_RECEIVER_ERR_LOG, INVALID_SENDER_ERR_LOG, INVALID_SWAP_ID_ERR_LOG}; -pub use rlp; #[cfg(test)] mod eth_tests; #[cfg(target_arch = "wasm32")] mod eth_wasm_tests; mod web3_transport; #[path = "eth/v2_activation.rs"] pub mod v2_activation; -use crate::nft::{find_wallet_nft_amount, WithdrawNftResult}; use v2_activation::{build_address_and_priv_key_policy, EthActivationV2Error}; +use crate::nft::{find_wallet_nft_amount, WithdrawNftResult}; + mod nonce; -use crate::{PrivKeyPolicy, TransactionResult, WithdrawFrom}; use nonce::ParityNonce; +use crate::{PrivKeyPolicy, TransactionResult, WithdrawFrom}; + /// https://github.com/artemii235/etomic-swap/blob/master/contracts/EtomicSwap.sol /// Dev chain (195.201.137.5:8565) contract address: 0x83965C539899cC0F918552e5A26915de40ee8852 /// Ropsten: https://ropsten.etherscan.io/address/0x7bc1bbdd6a0a722fc9bffc49c921b685ecb84b94 diff --git a/mm2src/coins/eth/eth_tests.rs b/mm2src/coins/eth/eth_tests.rs index dfeff254f9..7723478b81 100644 --- a/mm2src/coins/eth/eth_tests.rs +++ b/mm2src/coins/eth/eth_tests.rs @@ -1,5 +1,3 @@ -use super::*; -use crate::IguanaPrivKey; use common::{block_on, now_sec, wait_until_sec}; use crypto::privkey::key_pair_from_seed; use ethkey::{Generator, Random}; @@ -10,6 +8,9 @@ use mm2_test_helpers::{for_tests::{eth_jst_testnet_conf, eth_testnet_conf, ETH_D get_passphrase}; use mocktopus::mocking::*; +use super::*; +use crate::IguanaPrivKey; + /// The gas price for the tests const GAS_PRICE: u64 = 50_000_000_000; // `GAS_PRICE` increased by 3% diff --git a/mm2src/coins/eth/eth_wasm_tests.rs b/mm2src/coins/eth/eth_wasm_tests.rs index ae0d5482df..c1f4254811 100644 --- a/mm2src/coins/eth/eth_wasm_tests.rs +++ b/mm2src/coins/eth/eth_wasm_tests.rs @@ -1,11 +1,12 @@ -use super::*; -use crate::lp_coininit; use crypto::CryptoCtx; use mm2_core::mm_ctx::MmCtxBuilder; use mm2_test_helpers::for_tests::{ETH_DEV_NODE, ETH_DEV_SWAP_CONTRACT}; use wasm_bindgen_test::*; use web_sys::console; +use super::*; +use crate::lp_coininit; + wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] diff --git a/mm2src/coins/eth/v2_activation.rs b/mm2src/coins/eth/v2_activation.rs index fddf8da03f..d62d2a1bd0 100644 --- a/mm2src/coins/eth/v2_activation.rs +++ b/mm2src/coins/eth/v2_activation.rs @@ -1,5 +1,3 @@ -use super::*; -#[cfg(target_arch = "wasm32")] use crate::EthMetamaskPolicy; use common::executor::AbortedError; use crypto::{CryptoCtxError, StandardHDCoinAddress}; use enum_from::EnumFromTrait; @@ -7,6 +5,9 @@ use mm2_err_handle::common_errors::WithInternal; #[cfg(target_arch = "wasm32")] use mm2_metamask::{from_metamask_error, MetamaskError, MetamaskRpcError, WithMetamaskRpcError}; +use super::*; +#[cfg(target_arch = "wasm32")] use crate::EthMetamaskPolicy; + #[derive(Clone, Debug, Deserialize, Display, EnumFromTrait, PartialEq, Serialize, SerializeErrorType)] #[serde(tag = "error_type", content = "error_data")] pub enum EthActivationV2Error { diff --git a/mm2src/coins/eth/web3_transport/http_transport.rs b/mm2src/coins/eth/web3_transport/http_transport.rs index ac45850f1d..a1b82a4638 100644 --- a/mm2src/coins/eth/web3_transport/http_transport.rs +++ b/mm2src/coins/eth/web3_transport/http_transport.rs @@ -1,18 +1,20 @@ -use crate::eth::{web3_transport::Web3SendOut, EthCoin, GuiAuthMessages, RpcTransportEventHandler, - RpcTransportEventHandlerShared, Web3RpcError}; +#[cfg(not(target_arch = "wasm32"))] use std::ops::Deref; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + use common::APPLICATION_JSON; use futures::lock::Mutex as AsyncMutex; use http::header::CONTENT_TYPE; use jsonrpc_core::{Call, Response}; use mm2_net::transport::{GuiAuthValidation, GuiAuthValidationGenerator}; use serde_json::Value as Json; -#[cfg(not(target_arch = "wasm32"))] use std::ops::Deref; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::Arc; use web3::error::{Error, TransportError}; use web3::helpers::{build_request, to_result_from_output, to_string}; use web3::{RequestId, Transport}; +use crate::eth::{web3_transport::Web3SendOut, EthCoin, GuiAuthMessages, RpcTransportEventHandler, + RpcTransportEventHandlerShared, Web3RpcError}; + #[derive(Serialize, Clone)] pub struct AuthPayload<'a> { #[serde(flatten)] diff --git a/mm2src/coins/eth/web3_transport/metamask_transport.rs b/mm2src/coins/eth/web3_transport/metamask_transport.rs index 5fe71d8dc2..1331ed9661 100644 --- a/mm2src/coins/eth/web3_transport/metamask_transport.rs +++ b/mm2src/coins/eth/web3_transport/metamask_transport.rs @@ -1,12 +1,14 @@ -use crate::eth::web3_transport::Web3SendOut; -use crate::RpcTransportEventHandlerShared; +use std::fmt; +use std::sync::Arc; + use jsonrpc_core::Call; use mm2_metamask::{detect_metamask_provider, Eip1193Provider, MetamaskResult, MetamaskSession}; use serde_json::Value as Json; -use std::fmt; -use std::sync::Arc; use web3::{RequestId, Transport}; +use crate::eth::web3_transport::Web3SendOut; +use crate::RpcTransportEventHandlerShared; + pub(crate) struct MetamaskEthConfig { /// The `ChainId` that the MetaMask wallet should be targeted on each RPC. pub chain_id: u64, diff --git a/mm2src/coins/eth/web3_transport/mod.rs b/mm2src/coins/eth/web3_transport/mod.rs index f8b7d62fbd..57d9bbd82f 100644 --- a/mm2src/coins/eth/web3_transport/mod.rs +++ b/mm2src/coins/eth/web3_transport/mod.rs @@ -1,4 +1,3 @@ -use crate::RpcTransportEventHandlerShared; use ethereum_types::U256; use futures::future::BoxFuture; use jsonrpc_core::Call; @@ -11,6 +10,8 @@ use web3::helpers::{self, CallFuture}; use web3::types::BlockNumber; use web3::{Error, RequestId, Transport}; +use crate::RpcTransportEventHandlerShared; + pub(crate) mod http_transport; #[cfg(target_arch = "wasm32")] pub(crate) mod metamask_transport; diff --git a/mm2src/coins/hd_confirm_address.rs b/mm2src/coins/hd_confirm_address.rs index d6ee019855..234f36a698 100644 --- a/mm2src/coins/hd_confirm_address.rs +++ b/mm2src/coins/hd_confirm_address.rs @@ -163,9 +163,10 @@ where #[cfg(test)] pub(crate) mod for_tests { - use super::*; use mocktopus::macros::mockable; + use super::*; + #[derive(Default)] pub struct MockableConfirmAddress; diff --git a/mm2src/coins/hd_pubkey.rs b/mm2src/coins/hd_pubkey.rs index 9bb122bee1..ee3fef051c 100644 --- a/mm2src/coins/hd_pubkey.rs +++ b/mm2src/coins/hd_pubkey.rs @@ -1,4 +1,3 @@ -use crate::hd_wallet::NewAccountCreatingError; use async_trait::async_trait; use crypto::hw_rpc_task::HwConnectStatuses; use crypto::trezor::trezor_rpc_task::{TrezorRpcTaskProcessor, TryIntoUserAction}; @@ -10,6 +9,8 @@ use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; use rpc_task::{RpcTask, RpcTaskError, RpcTaskHandle}; +use crate::hd_wallet::NewAccountCreatingError; + const SHOW_PUBKEY_ON_DISPLAY: bool = false; #[derive(Clone)] diff --git a/mm2src/coins/hd_wallet.rs b/mm2src/coins/hd_wallet.rs index 6124393ef1..c83a2de848 100644 --- a/mm2src/coins/hd_wallet.rs +++ b/mm2src/coins/hd_wallet.rs @@ -1,18 +1,19 @@ -use crate::hd_confirm_address::{HDConfirmAddress, HDConfirmAddressError}; -use crate::hd_pubkey::HDXPubExtractor; -use crate::hd_wallet_storage::HDWalletStorageError; -use crate::{BalanceError, WithdrawError}; +use std::collections::BTreeMap; + use async_trait::async_trait; use crypto::{Bip32DerPathError, Bip32Error, Bip44Chain, ChildNumber, DerivationPath, HwError, StandardHDPath, StandardHDPathError}; use derive_more::Display; +pub use futures::lock::{MappedMutexGuard as AsyncMappedMutexGuard, Mutex as AsyncMutex, MutexGuard as AsyncMutexGuard}; use itertools::Itertools; use mm2_err_handle::prelude::*; use rpc_task::RpcTaskError; use serde::Serialize; -use std::collections::BTreeMap; -pub use futures::lock::{MappedMutexGuard as AsyncMappedMutexGuard, Mutex as AsyncMutex, MutexGuard as AsyncMutexGuard}; +use crate::hd_confirm_address::{HDConfirmAddress, HDConfirmAddressError}; +use crate::hd_pubkey::HDXPubExtractor; +use crate::hd_wallet_storage::HDWalletStorageError; +use crate::{BalanceError, WithdrawError}; pub type HDAccountsMap = BTreeMap; pub type HDAccountsMutex = AsyncMutex>; diff --git a/mm2src/coins/hd_wallet_storage/mock_storage.rs b/mm2src/coins/hd_wallet_storage/mock_storage.rs index 2fbbc19f4c..5518645255 100644 --- a/mm2src/coins/hd_wallet_storage/mock_storage.rs +++ b/mm2src/coins/hd_wallet_storage/mock_storage.rs @@ -1,8 +1,9 @@ -use crate::hd_wallet_storage::{HDAccountStorageItem, HDWalletId, HDWalletStorageInternalOps, HDWalletStorageResult}; use async_trait::async_trait; use mm2_core::mm_ctx::MmArc; #[cfg(test)] use mocktopus::macros::*; +use crate::hd_wallet_storage::{HDAccountStorageItem, HDWalletId, HDWalletStorageInternalOps, HDWalletStorageResult}; + pub struct HDWalletMockStorage; #[async_trait] diff --git a/mm2src/coins/hd_wallet_storage/mod.rs b/mm2src/coins/hd_wallet_storage/mod.rs index 2c52cf3895..e14ce46669 100644 --- a/mm2src/coins/hd_wallet_storage/mod.rs +++ b/mm2src/coins/hd_wallet_storage/mod.rs @@ -1,4 +1,7 @@ -use crate::hd_wallet::HDWalletCoinOps; +use std::fmt; +use std::fmt::Formatter; +use std::ops::Deref; + use async_trait::async_trait; use crypto::{CryptoCtx, CryptoCtxError, XPub}; use derive_more::Display; @@ -7,9 +10,8 @@ use mm2_err_handle::prelude::*; #[cfg(test)] use mocktopus::macros::*; use primitives::hash::H160; use serde::{Deserialize, Serialize}; -use std::fmt; -use std::fmt::Formatter; -use std::ops::Deref; + +use crate::hd_wallet::HDWalletCoinOps; #[cfg(not(target_arch = "wasm32"))] mod sqlite_storage; #[cfg(target_arch = "wasm32")] mod wasm_storage; @@ -285,11 +287,12 @@ fn display_rmd160(rmd160: &H160) -> String { hex::encode(rmd160.deref()) } #[cfg(any(test, target_arch = "wasm32"))] mod tests { - use super::*; use itertools::Itertools; use mm2_test_helpers::for_tests::mm_ctx_with_custom_db; use primitives::hash::H160; + use super::*; + cfg_wasm32! { use crate::hd_wallet_storage::wasm_storage::get_all_storage_items; use wasm_bindgen_test::*; diff --git a/mm2src/coins/hd_wallet_storage/sqlite_storage.rs b/mm2src/coins/hd_wallet_storage/sqlite_storage.rs index 7d015b3d29..a6948401e5 100644 --- a/mm2src/coins/hd_wallet_storage/sqlite_storage.rs +++ b/mm2src/coins/hd_wallet_storage/sqlite_storage.rs @@ -1,7 +1,8 @@ #![allow(deprecated)] // TODO: remove this once rusqlite is >= 0.29 -use crate::hd_wallet_storage::{HDAccountStorageItem, HDWalletId, HDWalletStorageError, HDWalletStorageInternalOps, - HDWalletStorageResult}; +use std::convert::TryFrom; +use std::sync::MutexGuard; + use async_trait::async_trait; use common::async_blocking; use db_common::owned_named_params; @@ -11,8 +12,9 @@ use db_common::sqlite::{query_single_row_with_named_params, AsSqlNamedParams, Ow use derive_more::Display; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; -use std::convert::TryFrom; -use std::sync::MutexGuard; + +use crate::hd_wallet_storage::{HDAccountStorageItem, HDWalletId, HDWalletStorageError, HDWalletStorageInternalOps, + HDWalletStorageResult}; const CREATE_HD_ACCOUNT_TABLE: &str = "CREATE TABLE IF NOT EXISTS hd_account ( coin VARCHAR(255) NOT NULL, diff --git a/mm2src/coins/hd_wallet_storage/wasm_storage.rs b/mm2src/coins/hd_wallet_storage/wasm_storage.rs index a9e11143e2..46a2a48091 100644 --- a/mm2src/coins/hd_wallet_storage/wasm_storage.rs +++ b/mm2src/coins/hd_wallet_storage/wasm_storage.rs @@ -1,6 +1,3 @@ -use crate::hd_wallet_storage::{HDAccountStorageItem, HDWalletId, HDWalletStorageError, HDWalletStorageInternalOps, - HDWalletStorageResult}; -use crate::CoinsContext; use async_trait::async_trait; use crypto::XPub; use mm2_core::mm_ctx::MmArc; @@ -10,6 +7,10 @@ use mm2_db::indexed_db::{DbIdentifier, DbInstance, DbLocked, DbTable, DbTransact TableSignature, WeakDb}; use mm2_err_handle::prelude::*; +use crate::hd_wallet_storage::{HDAccountStorageItem, HDWalletId, HDWalletStorageError, HDWalletStorageInternalOps, + HDWalletStorageResult}; +use crate::CoinsContext; + const DB_NAME: &str = "hd_wallet"; const DB_VERSION: u32 = 1; /// An index of the `HDAccountTable` table that consists of the following properties: diff --git a/mm2src/coins/lightning.rs b/mm2src/coins/lightning.rs index 59b026121b..b11011ea94 100644 --- a/mm2src/coins/lightning.rs +++ b/mm2src/coins/lightning.rs @@ -10,23 +10,14 @@ mod ln_sql; pub mod ln_storage; pub mod ln_utils; -use crate::coin_errors::MyAddressError; -use crate::lightning::ln_utils::{filter_channels, pay_invoice_with_max_total_cltv_expiry_delta, PaymentError}; -use crate::utxo::rpc_clients::UtxoRpcClientEnum; -use crate::utxo::utxo_common::{big_decimal_from_sat, big_decimal_from_sat_unsigned}; -use crate::utxo::{sat_from_big_decimal, utxo_common, BlockchainNetwork}; -use crate::{BalanceFut, CheckIfMyPaymentSentArgs, CoinBalance, CoinFutSpawner, ConfirmPaymentInput, FeeApproxStage, - FoundSwapTxSpend, HistorySyncState, MakerSwapTakerCoin, MarketCoinOps, MmCoin, MmCoinEnum, - NegotiateSwapContractAddrErr, PaymentInstructionArgs, PaymentInstructions, PaymentInstructionsErr, - RawTransactionError, RawTransactionFut, RawTransactionRequest, RefundError, RefundPaymentArgs, - RefundResult, SearchForSwapTxSpendInput, SendMakerPaymentSpendPreimageInput, SendPaymentArgs, - SignatureError, SignatureResult, SpendPaymentArgs, SwapOps, TakerSwapMakerCoin, TradeFee, - TradePreimageFut, TradePreimageResult, TradePreimageValue, Transaction, TransactionEnum, TransactionErr, - TransactionFut, TransactionResult, TxMarshalingErr, UnexpectedDerivationMethod, UtxoStandardCoin, - ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr, ValidateOtherPubKeyErr, - ValidatePaymentError, ValidatePaymentFut, ValidatePaymentInput, VerificationError, VerificationResult, - WaitForHTLCTxSpendArgs, WatcherOps, WatcherReward, WatcherRewardError, WatcherSearchForSwapTxSpendInput, - WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawError, WithdrawFut, WithdrawRequest}; +use std::collections::{HashMap, HashSet}; +use std::convert::TryInto; +use std::fmt; +use std::io::Cursor; +use std::net::SocketAddr; +use std::str::FromStr; +use std::sync::Arc; + use async_trait::async_trait; use bitcoin::bech32::ToBase32; use bitcoin::hashes::Hash; @@ -71,15 +62,26 @@ use script::TransactionInputSigner; use secp256k1v24::PublicKey; use serde::Deserialize; use serde_json::Value as Json; -use std::collections::{HashMap, HashSet}; -use std::convert::TryInto; -use std::fmt; -use std::io::Cursor; -use std::net::SocketAddr; -use std::str::FromStr; -use std::sync::Arc; use uuid::Uuid; +use crate::coin_errors::MyAddressError; +use crate::lightning::ln_utils::{filter_channels, pay_invoice_with_max_total_cltv_expiry_delta, PaymentError}; +use crate::utxo::rpc_clients::UtxoRpcClientEnum; +use crate::utxo::utxo_common::{big_decimal_from_sat, big_decimal_from_sat_unsigned}; +use crate::utxo::{sat_from_big_decimal, utxo_common, BlockchainNetwork}; +use crate::{BalanceFut, CheckIfMyPaymentSentArgs, CoinBalance, CoinFutSpawner, ConfirmPaymentInput, FeeApproxStage, + FoundSwapTxSpend, HistorySyncState, MakerSwapTakerCoin, MarketCoinOps, MmCoin, MmCoinEnum, + NegotiateSwapContractAddrErr, PaymentInstructionArgs, PaymentInstructions, PaymentInstructionsErr, + RawTransactionError, RawTransactionFut, RawTransactionRequest, RefundError, RefundPaymentArgs, + RefundResult, SearchForSwapTxSpendInput, SendMakerPaymentSpendPreimageInput, SendPaymentArgs, + SignatureError, SignatureResult, SpendPaymentArgs, SwapOps, TakerSwapMakerCoin, TradeFee, + TradePreimageFut, TradePreimageResult, TradePreimageValue, Transaction, TransactionEnum, TransactionErr, + TransactionFut, TransactionResult, TxMarshalingErr, UnexpectedDerivationMethod, UtxoStandardCoin, + ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr, ValidateOtherPubKeyErr, + ValidatePaymentError, ValidatePaymentFut, ValidatePaymentInput, VerificationError, VerificationResult, + WaitForHTLCTxSpendArgs, WatcherOps, WatcherReward, WatcherRewardError, WatcherSearchForSwapTxSpendInput, + WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawError, WithdrawFut, WithdrawRequest}; + const WAIT_FOR_REFUND_INTERVAL: f64 = 60.; pub const DEFAULT_INVOICE_EXPIRY: u32 = 3600; diff --git a/mm2src/coins/lightning/ln_conf.rs b/mm2src/coins/lightning/ln_conf.rs index 80c5047d62..ed8443e9d2 100644 --- a/mm2src/coins/lightning/ln_conf.rs +++ b/mm2src/coins/lightning/ln_conf.rs @@ -1,6 +1,7 @@ -use crate::utxo::BlockchainNetwork; use lightning::util::config::{ChannelConfig, ChannelHandshakeConfig, ChannelHandshakeLimits, UserConfig}; +use crate::utxo::BlockchainNetwork; + #[derive(Clone, Debug, Deserialize, Serialize)] pub struct PlatformCoinConfirmationTargets { pub background: u32, diff --git a/mm2src/coins/lightning/ln_db.rs b/mm2src/coins/lightning/ln_db.rs index 7dd3f81cc2..1bca70c236 100644 --- a/mm2src/coins/lightning/ln_db.rs +++ b/mm2src/coins/lightning/ln_db.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use async_trait::async_trait; use common::{now_sec_i64, PagingOptionsEnum}; use db_common::sqlite::rusqlite::types::FromSqlError; @@ -5,7 +7,6 @@ use derive_more::Display; use lightning::ln::{PaymentHash, PaymentPreimage}; use secp256k1v24::PublicKey; use serde::{Deserialize, Serialize}; -use std::str::FromStr; use uuid::Uuid; #[derive(Clone, Debug, PartialEq, Serialize)] diff --git a/mm2src/coins/lightning/ln_errors.rs b/mm2src/coins/lightning/ln_errors.rs index 5d479e40b6..f0049661b5 100644 --- a/mm2src/coins/lightning/ln_errors.rs +++ b/mm2src/coins/lightning/ln_errors.rs @@ -1,5 +1,5 @@ -use crate::utxo::rpc_clients::UtxoRpcError; -use crate::PrivKeyPolicyNotAllowed; +use std::num::TryFromIntError; + use common::executor::AbortedError; use common::HttpStatusCode; use db_common::sqlite::rusqlite::Error as SqlError; @@ -7,9 +7,11 @@ use derive_more::Display; use http::StatusCode; use mm2_err_handle::prelude::*; use rpc_task::RpcTaskError; -use std::num::TryFromIntError; use uuid::Uuid; +use crate::utxo::rpc_clients::UtxoRpcError; +use crate::PrivKeyPolicyNotAllowed; + pub type EnableLightningResult = Result>; pub type SaveChannelClosingResult = Result>; diff --git a/mm2src/coins/lightning/ln_events.rs b/mm2src/coins/lightning/ln_events.rs index a90b13be82..c530789bf9 100644 --- a/mm2src/coins/lightning/ln_events.rs +++ b/mm2src/coins/lightning/ln_events.rs @@ -1,14 +1,13 @@ -use super::*; -use crate::lightning::ln_db::{DBChannelDetails, HTLCStatus, LightningDB, PaymentType}; -use crate::lightning::ln_errors::{SaveChannelClosingError, SaveChannelClosingResult}; -use crate::lightning::ln_sql::SqliteLightningDB; +use core::time::Duration; +use std::convert::{TryFrom, TryInto}; +use std::sync::Arc; + use bitcoin::blockdata::script::Script; use bitcoin::blockdata::transaction::Transaction; use bitcoin::consensus::encode::serialize_hex; use common::executor::{AbortSettings, SpawnAbortable, SpawnFuture, Timer}; use common::log::{error, info}; use common::{new_uuid, now_sec_i64}; -use core::time::Duration; use futures::compat::Future01CompatExt; use lightning::chain::chaininterface::{ConfirmationTarget, FeeEstimator}; use lightning::chain::keysinterface::SpendableOutputDescriptor; @@ -16,10 +15,13 @@ use lightning::util::events::{Event, EventHandler, PaymentPurpose}; use rand::Rng; use script::{Builder, SignatureVersion}; use secp256k1v24::Secp256k1; -use std::convert::{TryFrom, TryInto}; -use std::sync::Arc; use utxo_signer::with_key_pair::sign_tx; +use super::*; +use crate::lightning::ln_db::{DBChannelDetails, HTLCStatus, LightningDB, PaymentType}; +use crate::lightning::ln_errors::{SaveChannelClosingError, SaveChannelClosingResult}; +use crate::lightning::ln_sql::SqliteLightningDB; + const TRY_LOOP_INTERVAL: f64 = 60.; /// 1 second. const CRITICAL_FUTURE_TIMEOUT: f64 = 1.0; diff --git a/mm2src/coins/lightning/ln_filesystem_persister.rs b/mm2src/coins/lightning/ln_filesystem_persister.rs index d1444a62a6..6b581d6db3 100644 --- a/mm2src/coins/lightning/ln_filesystem_persister.rs +++ b/mm2src/coins/lightning/ln_filesystem_persister.rs @@ -1,5 +1,13 @@ -use crate::lightning::ln_storage::{LightningStorage, NetworkGraph, NodesAddressesMap, NodesAddressesMapShared, Scorer, - TrustedNodesShared}; +use std::collections::{HashMap, HashSet}; +use std::fs; +use std::io::{BufReader, BufWriter, Cursor}; +use std::net::SocketAddr; +use std::ops::Deref; +#[cfg(target_family = "unix")] use std::os::unix::io::AsRawFd; +use std::path::PathBuf; +use std::str::FromStr; +use std::sync::{Arc, Mutex}; + use async_trait::async_trait; use bitcoin::blockdata::constants::genesis_block; use bitcoin::{BlockHash, Network, Txid}; @@ -13,20 +21,12 @@ use lightning::util::persist::KVStorePersister; use lightning::util::ser::{ReadableArgs, Writeable}; use mm2_io::fs::{check_dir_operations, invalid_data_err, read_json, write_json}; use secp256k1v24::PublicKey; -use std::collections::{HashMap, HashSet}; -use std::fs; -use std::io::{BufReader, BufWriter, Cursor}; -use std::net::SocketAddr; -use std::ops::Deref; -use std::path::PathBuf; -use std::str::FromStr; -use std::sync::{Arc, Mutex}; - -#[cfg(target_family = "unix")] use std::os::unix::io::AsRawFd; - #[cfg(target_family = "windows")] use {std::ffi::OsStr, std::os::windows::ffi::OsStrExt}; +use crate::lightning::ln_storage::{LightningStorage, NetworkGraph, NodesAddressesMap, NodesAddressesMapShared, Scorer, + TrustedNodesShared}; + const USE_TMP_FILE: bool = true; pub struct LightningFilesystemPersister { diff --git a/mm2src/coins/lightning/ln_p2p.rs b/mm2src/coins/lightning/ln_p2p.rs index 7db3a0b4e2..fe56cf9ccb 100644 --- a/mm2src/coins/lightning/ln_p2p.rs +++ b/mm2src/coins/lightning/ln_p2p.rs @@ -1,4 +1,6 @@ -use super::*; +use std::net::{IpAddr, Ipv4Addr}; +use std::num::TryFromIntError; + use common::executor::{spawn_abortable, SpawnFuture, Timer}; use common::log::LogState; use derive_more::Display; @@ -11,10 +13,10 @@ use lightning_net_tokio::SocketDescriptor; use mm2_net::ip_addr::fetch_external_ip; use rand::RngCore; use secp256k1v24::PublicKey; -use std::net::{IpAddr, Ipv4Addr}; -use std::num::TryFromIntError; use tokio::net::TcpListener; +use super::*; + const TRY_RECONNECTING_TO_NODE_INTERVAL: f64 = 60.; const BROADCAST_NODE_ANNOUNCEMENT_INTERVAL: u64 = 600; diff --git a/mm2src/coins/lightning/ln_platform.rs b/mm2src/coins/lightning/ln_platform.rs index c4c2f0e655..2dd7c2796b 100644 --- a/mm2src/coins/lightning/ln_platform.rs +++ b/mm2src/coins/lightning/ln_platform.rs @@ -1,12 +1,6 @@ -use super::*; -use crate::lightning::ln_errors::{SaveChannelClosingError, SaveChannelClosingResult}; -use crate::utxo::rpc_clients::{BestBlock as RpcBestBlock, BlockHashOrHeight, ConfirmedTransactionInfo, - ElectrumBlockHeader, ElectrumClient, ElectrumNonce, EstimateFeeMethod, - UtxoRpcClientEnum, UtxoRpcResult}; -use crate::utxo::spv::SimplePaymentVerification; -use crate::utxo::utxo_standard::UtxoStandardCoin; -use crate::utxo::GetConfirmedTxError; -use crate::{CoinFutSpawner, MarketCoinOps, MmCoin, WaitForHTLCTxSpendArgs}; +use std::convert::TryInto; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering, Ordering}; + use bitcoin::blockdata::block::BlockHeader; use bitcoin::blockdata::script::Script; use bitcoin::blockdata::transaction::Transaction; @@ -23,10 +17,18 @@ use lightning::chain::{chaininterface::{BroadcasterInterface, ConfirmationTarget Confirm, Filter, WatchedOutput}; use rpc::v1::types::{Bytes as BytesJson, H256 as H256Json}; use spv_validation::spv_proof::TRY_SPV_PROOF_INTERVAL; -use std::convert::TryInto; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering, Ordering}; use uuid::Uuid; +use super::*; +use crate::lightning::ln_errors::{SaveChannelClosingError, SaveChannelClosingResult}; +use crate::utxo::rpc_clients::{BestBlock as RpcBestBlock, BlockHashOrHeight, ConfirmedTransactionInfo, + ElectrumBlockHeader, ElectrumClient, ElectrumNonce, EstimateFeeMethod, + UtxoRpcClientEnum, UtxoRpcResult}; +use crate::utxo::spv::SimplePaymentVerification; +use crate::utxo::utxo_standard::UtxoStandardCoin; +use crate::utxo::GetConfirmedTxError; +use crate::{CoinFutSpawner, MarketCoinOps, MmCoin, WaitForHTLCTxSpendArgs}; + const CHECK_FOR_NEW_BEST_BLOCK_INTERVAL: f64 = 60.; const TRY_LOOP_INTERVAL: f64 = 60.; const TAKER_PAYMENT_SPEND_SEARCH_INTERVAL: f64 = 10.; diff --git a/mm2src/coins/lightning/ln_serialization.rs b/mm2src/coins/lightning/ln_serialization.rs index 37ece14bee..16509f8496 100644 --- a/mm2src/coins/lightning/ln_serialization.rs +++ b/mm2src/coins/lightning/ln_serialization.rs @@ -1,15 +1,17 @@ -use crate::lightning::ln_db::{DBPaymentsFilter, HTLCStatus, PaymentInfo, PaymentType}; -use crate::lightning::ln_platform::h256_json_from_txid; -use crate::H256Json; +use std::fmt; +use std::net::{SocketAddr, ToSocketAddrs}; +use std::str::FromStr; + use lightning::chain::channelmonitor::Balance; use lightning::ln::channelmanager::ChannelDetails; use secp256k1v24::PublicKey; use serde::{de, Serialize, Serializer}; -use std::fmt; -use std::net::{SocketAddr, ToSocketAddrs}; -use std::str::FromStr; use uuid::Uuid; +use crate::lightning::ln_db::{DBPaymentsFilter, HTLCStatus, PaymentInfo, PaymentType}; +use crate::lightning::ln_platform::h256_json_from_txid; +use crate::H256Json; + // TODO: support connection to onion addresses #[derive(Debug, PartialEq)] pub struct NodeAddress { @@ -368,9 +370,10 @@ impl From for ClaimableBalance { #[cfg(test)] mod tests { - use super::*; use serde_json as json; + use super::*; + #[test] fn test_node_address_serialize() { let node_address = NodeAddress { diff --git a/mm2src/coins/lightning/ln_sql.rs b/mm2src/coins/lightning/ln_sql.rs index 53eab1ac78..98b3f354ce 100644 --- a/mm2src/coins/lightning/ln_sql.rs +++ b/mm2src/coins/lightning/ln_sql.rs @@ -1,8 +1,8 @@ #![allow(deprecated)] // TODO: remove this once rusqlite is >= 0.29 -use crate::lightning::ln_db::{ChannelType, ChannelVisibility, ClosedChannelsFilter, DBChannelDetails, - DBPaymentsFilter, GetClosedChannelsResult, GetPaymentsResult, HTLCStatus, LightningDB, - PaymentInfo, PaymentType}; +use std::convert::TryInto; +use std::str::FromStr; + use async_trait::async_trait; use common::{async_blocking, now_sec_i64, PagingOptionsEnum}; use db_common::owned_named_params; @@ -14,10 +14,12 @@ use db_common::sqlite::{h256_option_slice_from_row, h256_slice_from_row, offset_ OwnedSqlNamedParams, SqlNamedParams, SqliteConnShared, CHECK_TABLE_EXISTS_SQL}; use lightning::ln::{PaymentHash, PaymentPreimage}; use secp256k1v24::PublicKey; -use std::convert::TryInto; -use std::str::FromStr; use uuid::Uuid; +use crate::lightning::ln_db::{ChannelType, ChannelVisibility, ClosedChannelsFilter, DBChannelDetails, + DBPaymentsFilter, GetClosedChannelsResult, GetPaymentsResult, HTLCStatus, LightningDB, + PaymentInfo, PaymentType}; + fn channels_history_table(ticker: &str) -> String { ticker.to_owned() + "_channels_history" } fn payments_history_table(ticker: &str) -> String { ticker.to_owned() + "_payments_history" } @@ -1044,15 +1046,17 @@ impl LightningDB for SqliteLightningDB { #[cfg(test)] mod tests { - use super::*; - use crate::lightning::ln_db::DBChannelDetails; + use std::num::NonZeroUsize; + use std::sync::{Arc, Mutex}; + use common::{block_on, new_uuid}; use db_common::sqlite::rusqlite::Connection; use rand::distributions::Alphanumeric; use rand::{Rng, RngCore}; use secp256k1v24::{Secp256k1, SecretKey}; - use std::num::NonZeroUsize; - use std::sync::{Arc, Mutex}; + + use super::*; + use crate::lightning::ln_db::DBChannelDetails; fn generate_random_channels(num: u64) -> Vec { let mut rng = rand::thread_rng(); diff --git a/mm2src/coins/lightning/ln_storage.rs b/mm2src/coins/lightning/ln_storage.rs index 9ece4d2e8f..81bede49e3 100644 --- a/mm2src/coins/lightning/ln_storage.rs +++ b/mm2src/coins/lightning/ln_storage.rs @@ -1,3 +1,7 @@ +use std::collections::{HashMap, HashSet}; +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; + use async_trait::async_trait; use bitcoin::Network; use common::log::LogState; @@ -5,9 +9,6 @@ use lightning::routing::gossip; use lightning::routing::scoring::ProbabilisticScorer; use parking_lot::Mutex as PaMutex; use secp256k1v24::PublicKey; -use std::collections::{HashMap, HashSet}; -use std::net::SocketAddr; -use std::sync::{Arc, Mutex}; pub type NodesAddressesMap = HashMap; pub type NodesAddressesMapShared = Arc>; diff --git a/mm2src/coins/lightning/ln_utils.rs b/mm2src/coins/lightning/ln_utils.rs index 88af1d68cc..986f2d1947 100644 --- a/mm2src/coins/lightning/ln_utils.rs +++ b/mm2src/coins/lightning/ln_utils.rs @@ -1,9 +1,8 @@ -use super::*; -use crate::lightning::ln_db::LightningDB; -use crate::lightning::ln_platform::{get_best_header, ln_best_block_update_loop, update_best_block}; -use crate::lightning::ln_sql::SqliteLightningDB; -use crate::lightning::ln_storage::{LightningStorage, NodesAddressesMap}; -use crate::utxo::rpc_clients::BestBlock as RpcBestBlock; +use std::collections::hash_map::Entry; +use std::fs::File; +use std::path::PathBuf; +use std::sync::Arc; + use bitcoin::hash_types::BlockHash; use bitcoin_hashes::{sha256d, Hash}; use common::executor::SpawnFuture; @@ -19,10 +18,13 @@ use lightning::util::errors::APIError; use lightning::util::ser::ReadableArgs; use lightning_invoice::payment::{Payer, PaymentError as InvoicePaymentError}; use mm2_core::mm_ctx::MmArc; -use std::collections::hash_map::Entry; -use std::fs::File; -use std::path::PathBuf; -use std::sync::Arc; + +use super::*; +use crate::lightning::ln_db::LightningDB; +use crate::lightning::ln_platform::{get_best_header, ln_best_block_update_loop, update_best_block}; +use crate::lightning::ln_sql::SqliteLightningDB; +use crate::lightning::ln_storage::{LightningStorage, NodesAddressesMap}; +use crate::utxo::rpc_clients::BestBlock as RpcBestBlock; pub const PAYMENT_RETRY_ATTEMPTS: usize = 5; diff --git a/mm2src/coins/lp_coins.rs b/mm2src/coins/lp_coins.rs index eb15ae1ca9..81e8e24307 100644 --- a/mm2src/coins/lp_coins.rs +++ b/mm2src/coins/lp_coins.rs @@ -41,6 +41,19 @@ #[macro_use] extern crate serde_json; #[macro_use] extern crate ser_error_derive; +use std::cmp::Ordering; +use std::collections::hash_map::{HashMap, RawEntryMut}; +use std::collections::HashSet; +use std::fmt; +use std::future::Future as Future03; +use std::num::NonZeroUsize; +use std::ops::{Add, Deref}; +use std::str::FromStr; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering as AtomicOrdering; +use std::sync::Arc; +use std::time::Duration; + use async_trait::async_trait; use base58::FromBase58Error; use bip32::ExtendedPrivateKey; @@ -70,18 +83,6 @@ use parking_lot::Mutex as PaMutex; use rpc::v1::types::{Bytes as BytesJson, H256 as H256Json}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_json::{self as json, Value as Json}; -use std::cmp::Ordering; -use std::collections::hash_map::{HashMap, RawEntryMut}; -use std::collections::HashSet; -use std::fmt; -use std::future::Future as Future03; -use std::num::NonZeroUsize; -use std::ops::{Add, Deref}; -use std::str::FromStr; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::Ordering as AtomicOrdering; -use std::sync::Arc; -use std::time::Duration; use utxo_signer::with_key_pair::UtxoSignWithKeyPairError; use zcash_primitives::transaction::Transaction as ZTransaction; @@ -4316,11 +4317,11 @@ fn coins_conf_check(ctx: &MmArc, coins_en: &Json, ticker: &str, req: Option<&Jso #[cfg(test)] mod tests { - use super::*; - use common::block_on; use mm2_test_helpers::for_tests::RICK; + use super::*; + #[test] fn test_lp_coinfind() { let ctx = mm2_core::mm_ctx::MmCtxBuilder::default().into_mm_arc(); diff --git a/mm2src/coins/lp_price.rs b/mm2src/coins/lp_price.rs index c0834c2efe..946d9dd22f 100644 --- a/mm2src/coins/lp_price.rs +++ b/mm2src/coins/lp_price.rs @@ -1,3 +1,7 @@ +use std::collections::HashMap; +#[cfg(feature = "run-docker-tests")] use std::str::FromStr; +use std::str::Utf8Error; + use common::log::{debug, error}; use common::StatusCode; use mm2_err_handle::prelude::{MmError, OrMmError}; @@ -6,9 +10,6 @@ use mm2_net::transport::SlurpError; use mm2_number::bigdecimal_custom::CheckedDivision; use mm2_number::{BigDecimal, MmNumber}; use num_traits::CheckedDiv; -use std::collections::HashMap; -#[cfg(feature = "run-docker-tests")] use std::str::FromStr; -use std::str::Utf8Error; const PRICE_ENDPOINTS: [&str; 2] = [ "https://prices.komodo.earth/api/v2/tickers", @@ -294,9 +295,10 @@ mod tests { #[test] fn test_get_cex_rates() { - use mm2_number::MmNumber; use std::time::SystemTime; + use mm2_number::MmNumber; + use crate::lp_price::{Provider, TickerInfos, TickerInfosRegistry}; let mut registry = TickerInfosRegistry::default(); diff --git a/mm2src/coins/my_tx_history_v2.rs b/mm2src/coins/my_tx_history_v2.rs index 1635be9e80..579c880762 100644 --- a/mm2src/coins/my_tx_history_v2.rs +++ b/mm2src/coins/my_tx_history_v2.rs @@ -1,10 +1,5 @@ -use crate::hd_wallet::{AddressDerivingError, InvalidBip44ChainError}; -use crate::tendermint::{TENDERMINT_ASSET_PROTOCOL_TYPE, TENDERMINT_COIN_PROTOCOL_TYPE}; -use crate::tx_history_storage::{CreateTxHistoryStorageError, FilteringAddresses, GetTxHistoryFilters, - TxHistoryStorageBuilder, WalletId}; -use crate::utxo::utxo_common::big_decimal_from_sat_unsigned; -use crate::{coin_conf, lp_coinfind_or_err, BlockHeightAndTime, CoinFindError, HDAccountAddressId, HistorySyncState, - MmCoin, MmCoinEnum, Transaction, TransactionDetails, TransactionType, TxFeeDetails, UtxoRpcError}; +use std::collections::HashSet; + use async_trait::async_trait; use bitcrypto::sha256; use common::{calc_total_pages, ten, HttpStatusCode, PagingOptionsEnum, StatusCode}; @@ -17,7 +12,14 @@ use mm2_err_handle::prelude::*; use mm2_number::BigDecimal; use num_traits::ToPrimitive; use rpc::v1::types::{Bytes as BytesJson, ToTxHash}; -use std::collections::HashSet; + +use crate::hd_wallet::{AddressDerivingError, InvalidBip44ChainError}; +use crate::tendermint::{TENDERMINT_ASSET_PROTOCOL_TYPE, TENDERMINT_COIN_PROTOCOL_TYPE}; +use crate::tx_history_storage::{CreateTxHistoryStorageError, FilteringAddresses, GetTxHistoryFilters, + TxHistoryStorageBuilder, WalletId}; +use crate::utxo::utxo_common::big_decimal_from_sat_unsigned; +use crate::{coin_conf, lp_coinfind_or_err, BlockHeightAndTime, CoinFindError, HDAccountAddressId, HistorySyncState, + MmCoin, MmCoinEnum, Transaction, TransactionDetails, TransactionType, TxFeeDetails, UtxoRpcError}; #[derive(Debug)] pub enum RemoveTxResult { @@ -527,12 +529,13 @@ pub async fn z_coin_tx_history_rpc( #[cfg(test)] pub(crate) mod for_tests { - use super::{CoinWithTxHistoryV2, TxHistoryStorage}; - use crate::tx_history_storage::TxHistoryStorageBuilder; use common::block_on; use mm2_core::mm_ctx::MmArc; use mm2_test_helpers::for_tests::mm_ctx_with_custom_db; + use super::{CoinWithTxHistoryV2, TxHistoryStorage}; + use crate::tx_history_storage::TxHistoryStorageBuilder; + pub fn init_storage_for(coin: &Coin) -> (MmArc, impl TxHistoryStorage) { let ctx = mm_ctx_with_custom_db(); let storage = TxHistoryStorageBuilder::new(&ctx).build().unwrap(); diff --git a/mm2src/coins/nft.rs b/mm2src/coins/nft.rs index c84d0cbe24..541bf699a3 100644 --- a/mm2src/coins/nft.rs +++ b/mm2src/coins/nft.rs @@ -8,27 +8,28 @@ pub(crate) mod storage; #[cfg(any(test, target_arch = "wasm32"))] mod nft_tests; -use crate::{coin_conf, get_my_address, MyAddressReq, WithdrawError}; +use std::cmp::Ordering; +use std::str::FromStr; + +use common::{parse_rfc3339_to_timestamp, APPLICATION_JSON}; +use crypto::StandardHDCoinAddress; +use ethereum_types::Address; +use http::header::ACCEPT; +use mm2_err_handle::map_to_mm::MapToMmResult; +use mm2_number::BigDecimal; use nft_errors::{GetInfoFromUriError, GetNftInfoError, UpdateNftError}; use nft_structs::{Chain, ContractType, ConvertChain, Nft, NftFromMoralis, NftList, NftListReq, NftMetadataReq, NftTransferHistory, NftTransferHistoryFromMoralis, NftTransfersReq, NftsTransferHistoryList, TransactionNftDetails, UpdateNftReq, WithdrawNftReq}; +use regex::Regex; +use serde_json::Value as Json; use crate::eth::{eth_addr_to_hex, get_eth_address, withdraw_erc1155, withdraw_erc721}; use crate::nft::nft_errors::ProtectFromSpamError; use crate::nft::nft_structs::{NftCommon, NftCtx, NftTransferCommon, RefreshMetadataReq, TransferMeta, TransferStatus, UriMeta}; use crate::nft::storage::{NftListStorageOps, NftStorageBuilder, NftTransferHistoryStorageOps}; -use common::{parse_rfc3339_to_timestamp, APPLICATION_JSON}; -use crypto::StandardHDCoinAddress; -use ethereum_types::Address; -use http::header::ACCEPT; -use mm2_err_handle::map_to_mm::MapToMmResult; -use mm2_number::BigDecimal; -use regex::Regex; -use serde_json::Value as Json; -use std::cmp::Ordering; -use std::str::FromStr; +use crate::{coin_conf, get_my_address, MyAddressReq, WithdrawError}; const MORALIS_API_ENDPOINT: &str = "api/v2"; /// query parameters for moralis request: The format of the token ID diff --git a/mm2src/coins/nft/nft_errors.rs b/mm2src/coins/nft/nft_errors.rs index 719c481dfc..cc361febf0 100644 --- a/mm2src/coins/nft/nft_errors.rs +++ b/mm2src/coins/nft/nft_errors.rs @@ -1,6 +1,3 @@ -use crate::eth::GetEthAddressError; -use crate::nft::storage::{CreateNftStorageError, NftStorageError}; -use crate::{GetMyAddressError, WithdrawError}; use common::{HttpStatusCode, ParseRfc3339Err}; use derive_more::Display; use enum_from::EnumFromStringify; @@ -9,6 +6,10 @@ use mm2_net::transport::SlurpError; use serde::{Deserialize, Serialize}; use web3::Error; +use crate::eth::GetEthAddressError; +use crate::nft::storage::{CreateNftStorageError, NftStorageError}; +use crate::{GetMyAddressError, WithdrawError}; + #[derive(Clone, Debug, Deserialize, Display, EnumFromStringify, PartialEq, Serialize, SerializeErrorType)] #[serde(tag = "error_type", content = "error_data")] pub enum GetNftInfoError { diff --git a/mm2src/coins/nft/nft_structs.rs b/mm2src/coins/nft/nft_structs.rs index 9d7a07b89a..df015e8ad3 100644 --- a/mm2src/coins/nft/nft_structs.rs +++ b/mm2src/coins/nft/nft_structs.rs @@ -1,24 +1,24 @@ -use crate::nft::eth_addr_to_hex; -use crate::{TransactionType, TxFeeDetails, WithdrawFee}; +use std::fmt; +use std::num::NonZeroUsize; +use std::str::FromStr; +use std::sync::Arc; + use common::ten; use ethereum_types::Address; use futures::lock::Mutex as AsyncMutex; use mm2_core::mm_ctx::{from_ctx, MmArc}; +#[cfg(target_arch = "wasm32")] +use mm2_db::indexed_db::{ConstructibleDb, SharedDb}; use mm2_number::BigDecimal; use rpc::v1::types::Bytes as BytesJson; use serde::Deserialize; use serde_json::Value as Json; -use std::fmt; -use std::num::NonZeroUsize; -use std::str::FromStr; -use std::sync::Arc; use url::Url; -#[cfg(target_arch = "wasm32")] -use mm2_db::indexed_db::{ConstructibleDb, SharedDb}; - +use crate::nft::eth_addr_to_hex; #[cfg(target_arch = "wasm32")] use crate::nft::storage::wasm::nft_idb::NftCacheIDB; +use crate::{TransactionType, TxFeeDetails, WithdrawFee}; #[derive(Debug, Deserialize)] pub struct NftListReq { diff --git a/mm2src/coins/nft/nft_tests.rs b/mm2src/coins/nft/nft_tests.rs index 02710e0ac4..cd90f03fbe 100644 --- a/mm2src/coins/nft/nft_tests.rs +++ b/mm2src/coins/nft/nft_tests.rs @@ -5,13 +5,14 @@ const TEST_WALLET_ADDR_EVM: &str = "0x394d86994f954ed931b86791b62fe64f4c5dac37"; #[cfg(all(test, not(target_arch = "wasm32")))] mod native_tests { + use common::block_on; + use crate::eth::eth_addr_to_hex; use crate::nft::nft_structs::{NftFromMoralis, NftTransferHistoryFromMoralis, UriMeta}; use crate::nft::nft_tests::{NFT_HISTORY_URL_TEST, NFT_LIST_URL_TEST, NFT_METADATA_URL_TEST, TEST_WALLET_ADDR_EVM}; use crate::nft::storage::db_test_helpers::*; use crate::nft::{check_and_redact_if_spam, check_moralis_ipfs_bafy, check_nft_metadata_for_spam, send_request_to_uri}; - use common::block_on; #[test] fn test_moralis_ipfs_bafy() { @@ -125,12 +126,13 @@ mod native_tests { #[cfg(target_arch = "wasm32")] mod wasm_tests { + use wasm_bindgen_test::*; + use crate::eth::eth_addr_to_hex; use crate::nft::nft_structs::{NftFromMoralis, NftTransferHistoryFromMoralis}; use crate::nft::nft_tests::{NFT_HISTORY_URL_TEST, NFT_LIST_URL_TEST, NFT_METADATA_URL_TEST, TEST_WALLET_ADDR_EVM}; use crate::nft::send_request_to_uri; use crate::nft::storage::db_test_helpers::*; - use wasm_bindgen_test::*; wasm_bindgen_test_configure!(run_in_browser); diff --git a/mm2src/coins/nft/storage/db_test_helpers.rs b/mm2src/coins/nft/storage/db_test_helpers.rs index 7961d4c1ea..f8bfec97b8 100644 --- a/mm2src/coins/nft/storage/db_test_helpers.rs +++ b/mm2src/coins/nft/storage/db_test_helpers.rs @@ -1,12 +1,14 @@ +use std::num::NonZeroUsize; +use std::str::FromStr; + +use ethereum_types::Address; +use mm2_number::BigDecimal; +use mm2_test_helpers::for_tests::mm_ctx_with_custom_db; + use crate::eth::eth_addr_to_hex; use crate::nft::nft_structs::{Chain, ContractType, Nft, NftCommon, NftTransferCommon, NftTransferHistory, NftTransferHistoryFilters, TransferMeta, TransferStatus, UriMeta}; use crate::nft::storage::{NftListStorageOps, NftStorageBuilder, NftTransferHistoryStorageOps, RemoveNftResult}; -use ethereum_types::Address; -use mm2_number::BigDecimal; -use mm2_test_helpers::for_tests::mm_ctx_with_custom_db; -use std::num::NonZeroUsize; -use std::str::FromStr; cfg_wasm32! { use wasm_bindgen_test::*; diff --git a/mm2src/coins/nft/storage/mod.rs b/mm2src/coins/nft/storage/mod.rs index 0a2e906ccc..b025daf8e9 100644 --- a/mm2src/coins/nft/storage/mod.rs +++ b/mm2src/coins/nft/storage/mod.rs @@ -1,6 +1,5 @@ -use crate::nft::nft_structs::{Chain, Nft, NftList, NftTokenAddrId, NftTransferHistory, NftTransferHistoryFilters, - NftsTransferHistoryList, TransferMeta}; -use crate::WithdrawError; +use std::num::NonZeroUsize; + use async_trait::async_trait; use derive_more::Display; use mm2_core::mm_ctx::MmArc; @@ -8,7 +7,10 @@ use mm2_err_handle::mm_error::MmResult; use mm2_err_handle::mm_error::{NotEqual, NotMmError}; use mm2_number::BigDecimal; use serde::{Deserialize, Serialize}; -use std::num::NonZeroUsize; + +use crate::nft::nft_structs::{Chain, Nft, NftList, NftTokenAddrId, NftTransferHistory, NftTransferHistoryFilters, + NftsTransferHistoryList, TransferMeta}; +use crate::WithdrawError; #[cfg(any(test, target_arch = "wasm32"))] pub(crate) mod db_test_helpers; diff --git a/mm2src/coins/nft/storage/sql_storage.rs b/mm2src/coins/nft/storage/sql_storage.rs index 9179704467..ff310940ed 100644 --- a/mm2src/coins/nft/storage/sql_storage.rs +++ b/mm2src/coins/nft/storage/sql_storage.rs @@ -1,8 +1,8 @@ -use crate::nft::eth_addr_to_hex; -use crate::nft::nft_structs::{Chain, ConvertChain, Nft, NftList, NftTokenAddrId, NftTransferHistory, - NftTransferHistoryFilters, NftsTransferHistoryList, TransferMeta}; -use crate::nft::storage::{get_offset_limit, CreateNftStorageError, NftListStorageOps, NftStorageError, - NftTransferHistoryStorageOps, RemoveNftResult}; +use std::convert::TryInto; +use std::num::NonZeroUsize; +use std::str::FromStr; +use std::sync::{Arc, Mutex}; + use async_trait::async_trait; use common::async_blocking; use db_common::sql_build::{SqlCondition, SqlQuery}; @@ -15,10 +15,12 @@ use mm2_err_handle::map_to_mm::MapToMmResult; use mm2_err_handle::mm_error::{MmError, MmResult}; use mm2_number::BigDecimal; use serde_json::{self as json}; -use std::convert::TryInto; -use std::num::NonZeroUsize; -use std::str::FromStr; -use std::sync::{Arc, Mutex}; + +use crate::nft::eth_addr_to_hex; +use crate::nft::nft_structs::{Chain, ConvertChain, Nft, NftList, NftTokenAddrId, NftTransferHistory, + NftTransferHistoryFilters, NftsTransferHistoryList, TransferMeta}; +use crate::nft::storage::{get_offset_limit, CreateNftStorageError, NftListStorageOps, NftStorageError, + NftTransferHistoryStorageOps, RemoveNftResult}; fn nft_list_table_name(chain: &Chain) -> String { chain.to_ticker() + "_nft_list" } diff --git a/mm2src/coins/nft/storage/wasm/mod.rs b/mm2src/coins/nft/storage/wasm/mod.rs index 6bbc8738c4..e7b84859ad 100644 --- a/mm2src/coins/nft/storage/wasm/mod.rs +++ b/mm2src/coins/nft/storage/wasm/mod.rs @@ -1,8 +1,9 @@ -use crate::nft::storage::NftStorageError; use mm2_db::indexed_db::{DbTransactionError, InitDbError}; use mm2_err_handle::prelude::*; use mm2_number::bigdecimal::ParseBigDecimalError; +use crate::nft::storage::NftStorageError; + pub(crate) mod nft_idb; pub(crate) mod wasm_storage; diff --git a/mm2src/coins/nft/storage/wasm/nft_idb.rs b/mm2src/coins/nft/storage/wasm/nft_idb.rs index 0d7758d61a..79ad1dbcb7 100644 --- a/mm2src/coins/nft/storage/wasm/nft_idb.rs +++ b/mm2src/coins/nft/storage/wasm/nft_idb.rs @@ -1,8 +1,9 @@ -use crate::nft::storage::wasm::wasm_storage::{LastScannedBlockTable, NftListTable, NftTransferHistoryTable}; use async_trait::async_trait; use mm2_db::indexed_db::InitDbResult; use mm2_db::indexed_db::{DbIdentifier, DbInstance, DbLocked, IndexedDb, IndexedDbBuilder}; +use crate::nft::storage::wasm::wasm_storage::{LastScannedBlockTable, NftListTable, NftTransferHistoryTable}; + const DB_NAME: &str = "nft_cache"; const DB_VERSION: u32 = 1; pub type NftCacheIDBLocked<'a> = DbLocked<'a, NftCacheIDB>; diff --git a/mm2src/coins/nft/storage/wasm/wasm_storage.rs b/mm2src/coins/nft/storage/wasm/wasm_storage.rs index 058b6cdffd..8ad8c749d9 100644 --- a/mm2src/coins/nft/storage/wasm/wasm_storage.rs +++ b/mm2src/coins/nft/storage/wasm/wasm_storage.rs @@ -1,10 +1,7 @@ -use crate::eth::eth_addr_to_hex; -use crate::nft::nft_structs::{Chain, ContractType, Nft, NftCtx, NftList, NftTransferHistory, NftsTransferHistoryList, - TransferMeta, TransferStatus}; -use crate::nft::storage::wasm::nft_idb::{NftCacheIDB, NftCacheIDBLocked}; -use crate::nft::storage::wasm::{WasmNftCacheError, WasmNftCacheResult}; -use crate::nft::storage::{get_offset_limit, CreateNftStorageError, NftListStorageOps, NftTokenAddrId, - NftTransferHistoryFilters, NftTransferHistoryStorageOps, RemoveNftResult}; +use std::collections::HashSet; +use std::num::NonZeroUsize; +use std::str::FromStr; + use async_trait::async_trait; use common::is_initial_upgrade; use mm2_core::mm_ctx::MmArc; @@ -15,9 +12,14 @@ use mm2_err_handle::prelude::MmResult; use mm2_number::BigDecimal; use num_traits::ToPrimitive; use serde_json::{self as json, Value as Json}; -use std::collections::HashSet; -use std::num::NonZeroUsize; -use std::str::FromStr; + +use crate::eth::eth_addr_to_hex; +use crate::nft::nft_structs::{Chain, ContractType, Nft, NftCtx, NftList, NftTransferHistory, NftsTransferHistoryList, + TransferMeta, TransferStatus}; +use crate::nft::storage::wasm::nft_idb::{NftCacheIDB, NftCacheIDBLocked}; +use crate::nft::storage::wasm::{WasmNftCacheError, WasmNftCacheResult}; +use crate::nft::storage::{get_offset_limit, CreateNftStorageError, NftListStorageOps, NftTokenAddrId, + NftTransferHistoryFilters, NftTransferHistoryStorageOps, RemoveNftResult}; #[derive(Clone)] pub struct IndexedDbNftStorage { diff --git a/mm2src/coins/qrc20.rs b/mm2src/coins/qrc20.rs index 36f8086e70..13ea546bd0 100644 --- a/mm2src/coins/qrc20.rs +++ b/mm2src/coins/qrc20.rs @@ -1,3 +1,36 @@ +use std::collections::{HashMap, HashSet}; +use std::convert::TryInto; +use std::ops::{Deref, Neg}; +#[cfg(not(target_arch = "wasm32"))] use std::path::PathBuf; +use std::str::FromStr; +use std::sync::Arc; + +use async_trait::async_trait; +use bitcrypto::{dhash160, sha256}; +use chain::TransactionOutput; +use common::executor::{AbortableSystem, AbortedError, Timer}; +use common::jsonrpc_client::{JsonRpcClient, JsonRpcRequest, RpcRes}; +use common::log::{error, warn}; +use common::{now_sec, now_sec_u32}; +use derive_more::Display; +use ethabi::{Function, Token}; +use ethereum_types::{H160, U256}; +use futures::compat::Future01CompatExt; +use futures::{FutureExt, TryFutureExt}; +use futures01::Future; +use keys::bytes::Bytes as ScriptBytes; +use keys::{Address as UtxoAddress, Address, KeyPair, Public}; +use mm2_core::mm_ctx::MmArc; +use mm2_err_handle::prelude::*; +use mm2_number::{BigDecimal, MmNumber}; +#[cfg(test)] use mocktopus::macros::*; +use rpc::v1::types::{Bytes as BytesJson, ToTxHash, Transaction as RpcTransaction, H160 as H160Json, H256 as H256Json}; +use script::{Builder as ScriptBuilder, Opcode, Script, TransactionInputSigner}; +use script_pubkey::generate_contract_call_script_pubkey; +use serde_json::{self as json, Value as Json}; +use serialization::{deserialize, serialize, CoinVariant}; +use utxo_signer::with_key_pair::{sign_tx, UtxoSignWithKeyPairError}; + use crate::coin_errors::{MyAddressError, ValidatePaymentError}; use crate::eth::{self, u256_to_big_decimal, wei_from_big_decimal, TryToAddress}; use crate::qrc20::rpc_clients::{LogEntry, Qrc20ElectrumOps, Qrc20NativeOps, Qrc20RpcOps, TopicFilter, TxReceipt, @@ -28,37 +61,6 @@ use crate::{BalanceError, BalanceFut, CheckIfMyPaymentSentArgs, CoinBalance, Coi ValidatePaymentInput, VerificationResult, WaitForHTLCTxSpendArgs, WatcherOps, WatcherReward, WatcherRewardError, WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawError, WithdrawFee, WithdrawFut, WithdrawRequest, WithdrawResult}; -use async_trait::async_trait; -use bitcrypto::{dhash160, sha256}; -use chain::TransactionOutput; -use common::executor::{AbortableSystem, AbortedError, Timer}; -use common::jsonrpc_client::{JsonRpcClient, JsonRpcRequest, RpcRes}; -use common::log::{error, warn}; -use common::{now_sec, now_sec_u32}; -use derive_more::Display; -use ethabi::{Function, Token}; -use ethereum_types::{H160, U256}; -use futures::compat::Future01CompatExt; -use futures::{FutureExt, TryFutureExt}; -use futures01::Future; -use keys::bytes::Bytes as ScriptBytes; -use keys::{Address as UtxoAddress, Address, KeyPair, Public}; -use mm2_core::mm_ctx::MmArc; -use mm2_err_handle::prelude::*; -use mm2_number::{BigDecimal, MmNumber}; -#[cfg(test)] use mocktopus::macros::*; -use rpc::v1::types::{Bytes as BytesJson, ToTxHash, Transaction as RpcTransaction, H160 as H160Json, H256 as H256Json}; -use script::{Builder as ScriptBuilder, Opcode, Script, TransactionInputSigner}; -use script_pubkey::generate_contract_call_script_pubkey; -use serde_json::{self as json, Value as Json}; -use serialization::{deserialize, serialize, CoinVariant}; -use std::collections::{HashMap, HashSet}; -use std::convert::TryInto; -use std::ops::{Deref, Neg}; -#[cfg(not(target_arch = "wasm32"))] use std::path::PathBuf; -use std::str::FromStr; -use std::sync::Arc; -use utxo_signer::with_key_pair::{sign_tx, UtxoSignWithKeyPairError}; mod history; #[cfg(test)] mod qrc20_tests; diff --git a/mm2src/coins/qrc20/history.rs b/mm2src/coins/qrc20/history.rs index b3ae9e7655..666b28397d 100644 --- a/mm2src/coins/qrc20/history.rs +++ b/mm2src/coins/qrc20/history.rs @@ -1,15 +1,17 @@ -use super::*; -use crate::utxo::{RequestTxHistoryResult, UtxoFeeDetails}; -use crate::{CoinsContext, TxFeeDetails, TxHistoryResult}; +use std::collections::HashMap; +use std::io::Cursor; + use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use common::jsonrpc_client::JsonRpcErrorType; use itertools::Itertools; use mm2_metrics::MetricsArc; use script_pubkey::{extract_contract_call_from_script, extract_gas_from_script, ExtractGasEnum}; -use std::collections::HashMap; -use std::io::Cursor; use utxo_common::{HISTORY_TOO_LARGE_ERROR, HISTORY_TOO_LARGE_ERR_CODE}; +use super::*; +use crate::utxo::{RequestTxHistoryResult, UtxoFeeDetails}; +use crate::{CoinsContext, TxFeeDetails, TxHistoryResult}; + type TxTransferMap = HashMap; type HistoryMapByHash = HashMap; type TxIds = Vec<(H256Json, u64)>; @@ -812,12 +814,13 @@ fn is_transfer_event_log(log: &LogEntry) -> bool { #[cfg(test)] mod tests { - use super::*; use common::block_on; use mm2_metrics::{MetricType, MetricsJson, MetricsOps}; use mm2_test_helpers::for_tests::find_metrics_in_json; use qrc20_tests::qrc20_coin_for_test; + use super::*; + #[test] fn test_tx_internal_id() { let tx_hash = hex::decode("39104d29d77ba83c5c6c63ab7a0f096301c443b4538dc6b30140453a40caa80a").unwrap(); diff --git a/mm2src/coins/qrc20/qrc20_tests.rs b/mm2src/coins/qrc20/qrc20_tests.rs index f5aa39ba52..ebd402f460 100644 --- a/mm2src/coins/qrc20/qrc20_tests.rs +++ b/mm2src/coins/qrc20/qrc20_tests.rs @@ -1,6 +1,6 @@ -use super::*; -use crate::utxo::rpc_clients::UnspentInfo; -use crate::{TxFeeDetails, WaitForHTLCTxSpendArgs}; +use std::convert::TryFrom; +use std::mem::discriminant; + use chain::OutPoint; use common::{block_on, wait_until_sec, DEX_FEE_ADDR_RAW_PUBKEY}; use crypto::Secp256k1Secret; @@ -9,8 +9,10 @@ use mm2_core::mm_ctx::MmCtxBuilder; use mm2_number::bigdecimal::Zero; use mocktopus::mocking::{MockResult, Mockable}; use rpc::v1::types::ToTxHash; -use std::convert::TryFrom; -use std::mem::discriminant; + +use super::*; +use crate::utxo::rpc_clients::UnspentInfo; +use crate::{TxFeeDetails, WaitForHTLCTxSpendArgs}; const EXPECTED_TX_FEE: i64 = 1000; const CONTRACT_CALL_GAS_FEE: i64 = (QRC20_GAS_LIMIT_DEFAULT * QRC20_GAS_PRICE_DEFAULT) as i64; diff --git a/mm2src/coins/qrc20/rpc_clients.rs b/mm2src/coins/qrc20/rpc_clients.rs index 4feb1848a1..669136751c 100644 --- a/mm2src/coins/qrc20/rpc_clients.rs +++ b/mm2src/coins/qrc20/rpc_clients.rs @@ -1,6 +1,7 @@ +use rpc::v1::types::H256; + use super::*; use crate::utxo::rpc_clients::{UtxoRpcError, UtxoRpcFut}; -use rpc::v1::types::H256; impl From for UtxoRpcError { fn from(e: ethabi::Error) -> Self { diff --git a/mm2src/coins/qrc20/swap.rs b/mm2src/coins/qrc20/swap.rs index a560d37057..fa4cc3205f 100644 --- a/mm2src/coins/qrc20/swap.rs +++ b/mm2src/coins/qrc20/swap.rs @@ -1,10 +1,11 @@ -use super::history::TransferHistoryBuilder; -use super::*; -use crate::eth::{decode_contract_call, PaymentState}; use bitcrypto::ripemd160; use common::now_sec; use script_pubkey::{extract_contract_addr_from_script, extract_contract_call_from_script, is_contract_call}; +use super::history::TransferHistoryBuilder; +use super::*; +use crate::eth::{decode_contract_call, PaymentState}; + /// `erc20Payment` call details consist of values obtained from [`TransactionOutput::script_pubkey`] and [`TxReceipt::logs`]. #[derive(Debug, Eq, PartialEq)] pub struct Erc20PaymentDetails { diff --git a/mm2src/coins/rpc_command/account_balance.rs b/mm2src/coins/rpc_command/account_balance.rs index 4c29383d1e..9e6f5bb0b0 100644 --- a/mm2src/coins/rpc_command/account_balance.rs +++ b/mm2src/coins/rpc_command/account_balance.rs @@ -1,13 +1,15 @@ -use crate::coin_balance::HDAddressBalance; -use crate::hd_wallet::HDWalletCoinOps; -use crate::rpc_command::hd_account_balance_rpc_error::HDAccountBalanceRpcError; -use crate::{lp_coinfind_or_err, CoinBalance, CoinWithDerivationMethod, MmCoinEnum}; +use std::fmt; + use async_trait::async_trait; use common::PagingOptionsEnum; use crypto::{Bip44Chain, RpcDerivationPath}; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; -use std::fmt; + +use crate::coin_balance::HDAddressBalance; +use crate::hd_wallet::HDWalletCoinOps; +use crate::rpc_command::hd_account_balance_rpc_error::HDAccountBalanceRpcError; +use crate::{lp_coinfind_or_err, CoinBalance, CoinWithDerivationMethod, MmCoinEnum}; #[derive(Deserialize)] pub struct HDAccountBalanceRequest { @@ -59,10 +61,11 @@ pub async fn account_balance( } pub mod common_impl { + use common::calc_total_pages; + use super::*; use crate::coin_balance::HDWalletBalanceOps; use crate::hd_wallet::{HDAccountOps, HDWalletOps}; - use common::calc_total_pages; pub async fn account_balance_rpc( coin: &Coin, diff --git a/mm2src/coins/rpc_command/get_enabled_coins.rs b/mm2src/coins/rpc_command/get_enabled_coins.rs index 543f6160eb..e5a5a56947 100644 --- a/mm2src/coins/rpc_command/get_enabled_coins.rs +++ b/mm2src/coins/rpc_command/get_enabled_coins.rs @@ -1,10 +1,11 @@ -use crate::CoinsContext; use common::HttpStatusCode; use http::StatusCode; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::MmResult; use mm2_err_handle::prelude::*; +use crate::CoinsContext; + #[derive(Serialize, Display, SerializeErrorType)] #[serde(tag = "error_type", content = "error_data")] pub enum GetEnabledCoinsError { diff --git a/mm2src/coins/rpc_command/get_new_address.rs b/mm2src/coins/rpc_command/get_new_address.rs index 54263226e6..cf8979a3cd 100644 --- a/mm2src/coins/rpc_command/get_new_address.rs +++ b/mm2src/coins/rpc_command/get_new_address.rs @@ -1,8 +1,5 @@ -use crate::coin_balance::HDAddressBalance; -use crate::hd_confirm_address::{ConfirmAddressStatus, HDConfirmAddress, HDConfirmAddressError, RpcTaskConfirmAddress}; -use crate::hd_wallet::{AddressDerivingError, InvalidBip44ChainError, NewAddressDeriveConfirmError, - NewAddressDerivingError}; -use crate::{lp_coinfind_or_err, BalanceError, CoinFindError, CoinsContext, MmCoinEnum, UnexpectedDerivationMethod}; +use std::time::Duration; + use async_trait::async_trait; use common::{HttpStatusCode, SuccessResponse}; use crypto::hw_rpc_task::{HwConnectStatuses, HwRpcTaskAwaitingStatus, HwRpcTaskUserAction, HwRpcTaskUserActionRequest}; @@ -15,7 +12,12 @@ use mm2_err_handle::prelude::*; use rpc_task::rpc_common::{CancelRpcTaskError, CancelRpcTaskRequest, InitRpcTaskResponse, RpcTaskStatusError, RpcTaskStatusRequest, RpcTaskUserActionError}; use rpc_task::{RpcTask, RpcTaskError, RpcTaskHandle, RpcTaskManager, RpcTaskManagerShared, RpcTaskStatus, RpcTaskTypes}; -use std::time::Duration; + +use crate::coin_balance::HDAddressBalance; +use crate::hd_confirm_address::{ConfirmAddressStatus, HDConfirmAddress, HDConfirmAddressError, RpcTaskConfirmAddress}; +use crate::hd_wallet::{AddressDerivingError, InvalidBip44ChainError, NewAddressDeriveConfirmError, + NewAddressDerivingError}; +use crate::{lp_coinfind_or_err, BalanceError, CoinFindError, CoinsContext, MmCoinEnum, UnexpectedDerivationMethod}; pub type GetNewAddressUserAction = HwRpcTaskUserAction; pub type GetNewAddressAwaitingStatus = HwRpcTaskAwaitingStatus; @@ -377,13 +379,15 @@ pub async fn cancel_get_new_address( } pub(crate) mod common_impl { + use std::fmt; + use std::ops::DerefMut; + + use crypto::RpcDerivationPath; + use super::*; use crate::coin_balance::{HDAddressBalanceScanner, HDWalletBalanceOps}; use crate::hd_wallet::{HDAccountOps, HDWalletCoinOps, HDWalletOps}; use crate::{CoinWithDerivationMethod, HDAddress}; - use crypto::RpcDerivationPath; - use std::fmt; - use std::ops::DerefMut; /// TODO remove once GUI integrates `task::get_new_address::init`. pub async fn get_new_address_rpc_without_conf( diff --git a/mm2src/coins/rpc_command/hd_account_balance_rpc_error.rs b/mm2src/coins/rpc_command/hd_account_balance_rpc_error.rs index e929692285..df13258f70 100644 --- a/mm2src/coins/rpc_command/hd_account_balance_rpc_error.rs +++ b/mm2src/coins/rpc_command/hd_account_balance_rpc_error.rs @@ -1,11 +1,13 @@ -use crate::hd_wallet::{AddressDerivingError, InvalidBip44ChainError}; -use crate::{BalanceError, CoinFindError, UnexpectedDerivationMethod}; +use std::time::Duration; + use common::HttpStatusCode; use crypto::Bip44Chain; use derive_more::Display; use http::StatusCode; use rpc_task::RpcTaskError; -use std::time::Duration; + +use crate::hd_wallet::{AddressDerivingError, InvalidBip44ChainError}; +use crate::{BalanceError, CoinFindError, UnexpectedDerivationMethod}; #[derive(Clone, Debug, Display, Serialize, SerializeErrorType)] #[serde(tag = "error_type", content = "error_data")] diff --git a/mm2src/coins/rpc_command/init_account_balance.rs b/mm2src/coins/rpc_command/init_account_balance.rs index 3317acea67..ebb1e5f97c 100644 --- a/mm2src/coins/rpc_command/init_account_balance.rs +++ b/mm2src/coins/rpc_command/init_account_balance.rs @@ -1,6 +1,3 @@ -use crate::coin_balance::HDAccountBalance; -use crate::rpc_command::hd_account_balance_rpc_error::HDAccountBalanceRpcError; -use crate::{lp_coinfind_or_err, CoinsContext, MmCoinEnum}; use async_trait::async_trait; use common::{SerdeInfallible, SuccessResponse}; use mm2_core::mm_ctx::MmArc; @@ -9,6 +6,10 @@ use rpc_task::rpc_common::{CancelRpcTaskError, CancelRpcTaskRequest, InitRpcTask RpcTaskStatusRequest}; use rpc_task::{RpcTask, RpcTaskHandle, RpcTaskManager, RpcTaskManagerShared, RpcTaskStatus, RpcTaskTypes}; +use crate::coin_balance::HDAccountBalance; +use crate::rpc_command::hd_account_balance_rpc_error::HDAccountBalanceRpcError; +use crate::{lp_coinfind_or_err, CoinsContext, MmCoinEnum}; + pub type AccountBalanceUserAction = SerdeInfallible; pub type AccountBalanceAwaitingStatus = SerdeInfallible; pub type AccountBalanceTaskManager = RpcTaskManager; @@ -115,12 +116,14 @@ pub async fn cancel_account_balance( } pub mod common_impl { + use std::fmt; + + use crypto::RpcDerivationPath; + use super::*; use crate::coin_balance::HDWalletBalanceOps; use crate::hd_wallet::{HDAccountOps, HDWalletCoinOps, HDWalletOps}; use crate::{CoinBalance, CoinWithDerivationMethod}; - use crypto::RpcDerivationPath; - use std::fmt; pub async fn init_account_balance_rpc( coin: &Coin, diff --git a/mm2src/coins/rpc_command/init_create_account.rs b/mm2src/coins/rpc_command/init_create_account.rs index 82f99587b6..950e83e336 100644 --- a/mm2src/coins/rpc_command/init_create_account.rs +++ b/mm2src/coins/rpc_command/init_create_account.rs @@ -1,8 +1,6 @@ -use crate::coin_balance::HDAccountBalance; -use crate::hd_pubkey::{HDExtractPubkeyError, HDXPubExtractor, RpcTaskXPubExtractor}; -use crate::hd_wallet::NewAccountCreatingError; -use crate::{lp_coinfind_or_err, BalanceError, CoinBalance, CoinFindError, CoinWithDerivationMethod, CoinsContext, - MmCoinEnum, UnexpectedDerivationMethod}; +use std::sync::Arc; +use std::time::Duration; + use async_trait::async_trait; use common::{true_f, HttpStatusCode, SuccessResponse}; use crypto::hw_rpc_task::{HwConnectStatuses, HwRpcTaskAwaitingStatus, HwRpcTaskUserAction, HwRpcTaskUserActionRequest}; @@ -16,8 +14,12 @@ use parking_lot::Mutex as PaMutex; use rpc_task::rpc_common::{CancelRpcTaskError, CancelRpcTaskRequest, InitRpcTaskResponse, RpcTaskStatusError, RpcTaskStatusRequest, RpcTaskUserActionError}; use rpc_task::{RpcTask, RpcTaskError, RpcTaskHandle, RpcTaskManager, RpcTaskManagerShared, RpcTaskStatus, RpcTaskTypes}; -use std::sync::Arc; -use std::time::Duration; + +use crate::coin_balance::HDAccountBalance; +use crate::hd_pubkey::{HDExtractPubkeyError, HDXPubExtractor, RpcTaskXPubExtractor}; +use crate::hd_wallet::NewAccountCreatingError; +use crate::{lp_coinfind_or_err, BalanceError, CoinBalance, CoinFindError, CoinWithDerivationMethod, CoinsContext, + MmCoinEnum, UnexpectedDerivationMethod}; pub type CreateAccountUserAction = HwRpcTaskUserAction; pub type CreateAccountAwaitingStatus = HwRpcTaskAwaitingStatus; diff --git a/mm2src/coins/rpc_command/init_scan_for_new_addresses.rs b/mm2src/coins/rpc_command/init_scan_for_new_addresses.rs index e90d44eecc..c6f9671893 100644 --- a/mm2src/coins/rpc_command/init_scan_for_new_addresses.rs +++ b/mm2src/coins/rpc_command/init_scan_for_new_addresses.rs @@ -1,6 +1,3 @@ -use crate::coin_balance::HDAddressBalance; -use crate::rpc_command::hd_account_balance_rpc_error::HDAccountBalanceRpcError; -use crate::{lp_coinfind_or_err, CoinsContext, MmCoinEnum}; use async_trait::async_trait; use common::{SerdeInfallible, SuccessResponse}; use crypto::RpcDerivationPath; @@ -10,6 +7,10 @@ use rpc_task::rpc_common::{CancelRpcTaskError, CancelRpcTaskRequest, InitRpcTask RpcTaskStatusRequest}; use rpc_task::{RpcTask, RpcTaskHandle, RpcTaskManager, RpcTaskManagerShared, RpcTaskStatus, RpcTaskTypes}; +use crate::coin_balance::HDAddressBalance; +use crate::rpc_command::hd_account_balance_rpc_error::HDAccountBalanceRpcError; +use crate::{lp_coinfind_or_err, CoinsContext, MmCoinEnum}; + pub type ScanAddressesUserAction = SerdeInfallible; pub type ScanAddressesAwaitingStatus = SerdeInfallible; pub type ScanAddressesTaskManager = RpcTaskManager; @@ -127,12 +128,13 @@ pub async fn cancel_scan_for_new_addresses( } pub mod common_impl { + use std::fmt; + use std::ops::DerefMut; + use super::*; use crate::coin_balance::HDWalletBalanceOps; use crate::hd_wallet::{HDAccountOps, HDWalletCoinOps, HDWalletOps}; use crate::CoinWithDerivationMethod; - use std::fmt; - use std::ops::DerefMut; pub async fn scan_for_new_addresses_rpc( coin: &Coin, diff --git a/mm2src/coins/rpc_command/init_withdraw.rs b/mm2src/coins/rpc_command/init_withdraw.rs index c9ba606250..65feb9dd03 100644 --- a/mm2src/coins/rpc_command/init_withdraw.rs +++ b/mm2src/coins/rpc_command/init_withdraw.rs @@ -1,5 +1,3 @@ -use crate::{lp_coinfind_or_err, CoinsContext, MmCoinEnum, WithdrawError}; -use crate::{TransactionDetails, WithdrawRequest}; use async_trait::async_trait; use common::SuccessResponse; use crypto::hw_rpc_task::{HwRpcTaskAwaitingStatus, HwRpcTaskUserAction, HwRpcTaskUserActionRequest}; @@ -9,6 +7,9 @@ use rpc_task::rpc_common::{CancelRpcTaskError, CancelRpcTaskRequest, InitRpcTask RpcTaskStatusRequest, RpcTaskUserActionError}; use rpc_task::{RpcTask, RpcTaskHandle, RpcTaskManager, RpcTaskManagerShared, RpcTaskStatusAlias, RpcTaskTypes}; +use crate::{lp_coinfind_or_err, CoinsContext, MmCoinEnum, WithdrawError}; +use crate::{TransactionDetails, WithdrawRequest}; + pub type WithdrawAwaitingStatus = HwRpcTaskAwaitingStatus; pub type WithdrawUserAction = HwRpcTaskUserAction; pub type WithdrawStatusError = RpcTaskStatusError; diff --git a/mm2src/coins/rpc_command/lightning/close_channel.rs b/mm2src/coins/rpc_command/lightning/close_channel.rs index 716b7db969..7bedf8dc63 100644 --- a/mm2src/coins/rpc_command/lightning/close_channel.rs +++ b/mm2src/coins/rpc_command/lightning/close_channel.rs @@ -1,10 +1,11 @@ -use crate::{lp_coinfind_or_err, CoinFindError, MmCoinEnum}; use common::{async_blocking, HttpStatusCode}; use http::StatusCode; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; use uuid::Uuid; +use crate::{lp_coinfind_or_err, CoinFindError, MmCoinEnum}; + type CloseChannelResult = Result>; #[derive(Debug, Deserialize, Display, Serialize, SerializeErrorType)] diff --git a/mm2src/coins/rpc_command/lightning/connect_to_node.rs b/mm2src/coins/rpc_command/lightning/connect_to_node.rs index 79ba0f1889..21e700791e 100644 --- a/mm2src/coins/rpc_command/lightning/connect_to_node.rs +++ b/mm2src/coins/rpc_command/lightning/connect_to_node.rs @@ -1,13 +1,15 @@ +use std::collections::hash_map::Entry; + +use common::HttpStatusCode; +use http::StatusCode; +use mm2_core::mm_ctx::MmArc; +use mm2_err_handle::prelude::*; + use crate::lightning::ln_errors::EnableLightningError; use crate::lightning::ln_p2p::{connect_to_ln_node, ConnectToNodeRes, ConnectionError}; use crate::lightning::ln_serialization::NodeAddress; use crate::lightning::ln_storage::LightningStorage; use crate::{lp_coinfind_or_err, CoinFindError, MmCoinEnum}; -use common::HttpStatusCode; -use http::StatusCode; -use mm2_core::mm_ctx::MmArc; -use mm2_err_handle::prelude::*; -use std::collections::hash_map::Entry; type ConnectToNodeResult = Result>; diff --git a/mm2src/coins/rpc_command/lightning/generate_invoice.rs b/mm2src/coins/rpc_command/lightning/generate_invoice.rs index 83d0fc41f6..da487bf2bc 100644 --- a/mm2src/coins/rpc_command/lightning/generate_invoice.rs +++ b/mm2src/coins/rpc_command/lightning/generate_invoice.rs @@ -1,7 +1,3 @@ -use crate::lightning::ln_db::{LightningDB, PaymentInfo, PaymentType}; -use crate::lightning::ln_p2p::connect_to_ln_node; -use crate::lightning::DEFAULT_INVOICE_EXPIRY; -use crate::{lp_coinfind_or_err, CoinFindError, H256Json, MmCoinEnum}; use bitcoin_hashes::Hash; use common::log::LogOnError; use common::{async_blocking, HttpStatusCode}; @@ -13,6 +9,11 @@ use lightning_invoice::{Invoice, SignOrCreationError}; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; +use crate::lightning::ln_db::{LightningDB, PaymentInfo, PaymentType}; +use crate::lightning::ln_p2p::connect_to_ln_node; +use crate::lightning::DEFAULT_INVOICE_EXPIRY; +use crate::{lp_coinfind_or_err, CoinFindError, H256Json, MmCoinEnum}; + type GenerateInvoiceResult = Result>; #[derive(Debug, Deserialize, Display, Serialize, SerializeErrorType)] diff --git a/mm2src/coins/rpc_command/lightning/get_channel_details.rs b/mm2src/coins/rpc_command/lightning/get_channel_details.rs index c96cf06e57..3bf3746a75 100644 --- a/mm2src/coins/rpc_command/lightning/get_channel_details.rs +++ b/mm2src/coins/rpc_command/lightning/get_channel_details.rs @@ -1,6 +1,3 @@ -use crate::lightning::ln_db::{DBChannelDetails, LightningDB}; -use crate::lightning::ln_serialization::ChannelDetailsForRPC; -use crate::{lp_coinfind_or_err, CoinFindError, MmCoinEnum}; use common::HttpStatusCode; use db_common::sqlite::rusqlite::Error as SqlError; use http::StatusCode; @@ -8,6 +5,10 @@ use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; use uuid::Uuid; +use crate::lightning::ln_db::{DBChannelDetails, LightningDB}; +use crate::lightning::ln_serialization::ChannelDetailsForRPC; +use crate::{lp_coinfind_or_err, CoinFindError, MmCoinEnum}; + type GetChannelDetailsResult = Result>; #[derive(Debug, Deserialize, Display, Serialize, SerializeErrorType)] diff --git a/mm2src/coins/rpc_command/lightning/get_claimable_balances.rs b/mm2src/coins/rpc_command/lightning/get_claimable_balances.rs index 5d1b84dad1..279f518e0e 100644 --- a/mm2src/coins/rpc_command/lightning/get_claimable_balances.rs +++ b/mm2src/coins/rpc_command/lightning/get_claimable_balances.rs @@ -1,10 +1,11 @@ -use crate::lightning::ln_serialization::ClaimableBalance; -use crate::{lp_coinfind_or_err, CoinFindError, MmCoinEnum}; use common::{async_blocking, HttpStatusCode}; use http::StatusCode; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; +use crate::lightning::ln_serialization::ClaimableBalance; +use crate::{lp_coinfind_or_err, CoinFindError, MmCoinEnum}; + type ClaimableBalancesResult = Result>; #[derive(Debug, Deserialize, Display, Serialize, SerializeErrorType)] diff --git a/mm2src/coins/rpc_command/lightning/get_payment_details.rs b/mm2src/coins/rpc_command/lightning/get_payment_details.rs index 0e7a4868c2..06fcb7474c 100644 --- a/mm2src/coins/rpc_command/lightning/get_payment_details.rs +++ b/mm2src/coins/rpc_command/lightning/get_payment_details.rs @@ -1,6 +1,3 @@ -use crate::lightning::ln_db::LightningDB; -use crate::lightning::ln_serialization::PaymentInfoForRPC; -use crate::{lp_coinfind_or_err, CoinFindError, H256Json, MmCoinEnum}; use common::HttpStatusCode; use db_common::sqlite::rusqlite::Error as SqlError; use http::StatusCode; @@ -8,6 +5,10 @@ use lightning::ln::PaymentHash; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; +use crate::lightning::ln_db::LightningDB; +use crate::lightning::ln_serialization::PaymentInfoForRPC; +use crate::{lp_coinfind_or_err, CoinFindError, H256Json, MmCoinEnum}; + type GetPaymentDetailsResult = Result>; #[derive(Debug, Deserialize, Display, Serialize, SerializeErrorType)] diff --git a/mm2src/coins/rpc_command/lightning/list_channels.rs b/mm2src/coins/rpc_command/lightning/list_channels.rs index d3eb582633..957d2a249d 100644 --- a/mm2src/coins/rpc_command/lightning/list_channels.rs +++ b/mm2src/coins/rpc_command/lightning/list_channels.rs @@ -1,7 +1,3 @@ -use crate::lightning::ln_db::{ClosedChannelsFilter, DBChannelDetails, LightningDB}; -use crate::lightning::ln_serialization::ChannelDetailsForRPC; -use crate::lightning::OpenChannelsFilter; -use crate::{lp_coinfind_or_err, CoinFindError, MmCoinEnum}; use common::{calc_total_pages, ten, HttpStatusCode, PagingOptionsEnum}; use db_common::sqlite::rusqlite::Error as SqlError; use http::StatusCode; @@ -9,6 +5,11 @@ use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; use uuid::Uuid; +use crate::lightning::ln_db::{ClosedChannelsFilter, DBChannelDetails, LightningDB}; +use crate::lightning::ln_serialization::ChannelDetailsForRPC; +use crate::lightning::OpenChannelsFilter; +use crate::{lp_coinfind_or_err, CoinFindError, MmCoinEnum}; + type ListChannelsResult = Result>; #[derive(Debug, Deserialize, Display, Serialize, SerializeErrorType)] diff --git a/mm2src/coins/rpc_command/lightning/list_payments_by_filter.rs b/mm2src/coins/rpc_command/lightning/list_payments_by_filter.rs index 0a6d0d3308..65088c2efb 100644 --- a/mm2src/coins/rpc_command/lightning/list_payments_by_filter.rs +++ b/mm2src/coins/rpc_command/lightning/list_payments_by_filter.rs @@ -1,6 +1,3 @@ -use crate::lightning::ln_db::LightningDB; -use crate::lightning::ln_serialization::{PaymentInfoForRPC, PaymentsFilterForRPC}; -use crate::{lp_coinfind_or_err, CoinFindError, H256Json, MmCoinEnum}; use common::{calc_total_pages, ten, HttpStatusCode, PagingOptionsEnum}; use db_common::sqlite::rusqlite::Error as SqlError; use http::StatusCode; @@ -8,6 +5,10 @@ use lightning::ln::PaymentHash; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; +use crate::lightning::ln_db::LightningDB; +use crate::lightning::ln_serialization::{PaymentInfoForRPC, PaymentsFilterForRPC}; +use crate::{lp_coinfind_or_err, CoinFindError, H256Json, MmCoinEnum}; + type ListPaymentsResult = Result>; #[derive(Debug, Deserialize, Display, Serialize, SerializeErrorType)] diff --git a/mm2src/coins/rpc_command/lightning/open_channel.rs b/mm2src/coins/rpc_command/lightning/open_channel.rs index f79ec0b433..2d10029901 100644 --- a/mm2src/coins/rpc_command/lightning/open_channel.rs +++ b/mm2src/coins/rpc_command/lightning/open_channel.rs @@ -1,12 +1,3 @@ -use crate::lightning::ln_conf::{ChannelOptions, OurChannelsConfigs}; -use crate::lightning::ln_db::{DBChannelDetails, LightningDB}; -use crate::lightning::ln_p2p::{connect_to_ln_node, ConnectionError}; -use crate::lightning::ln_serialization::NodeAddress; -use crate::lightning::ln_storage::LightningStorage; -use crate::utxo::utxo_common::UtxoTxBuilder; -use crate::utxo::{sat_from_big_decimal, FeePolicy, GetUtxoListOps, UtxoTxGenerationOps}; -use crate::{lp_coinfind_or_err, BalanceError, CoinFindError, GenerateTxError, MmCoinEnum, NumConversError, - UnexpectedDerivationMethod, UtxoRpcError}; use chain::TransactionOutput; use common::log::error; use common::{async_blocking, new_uuid, HttpStatusCode}; @@ -20,6 +11,16 @@ use mm2_number::BigDecimal; use script::Builder; use uuid::Uuid; +use crate::lightning::ln_conf::{ChannelOptions, OurChannelsConfigs}; +use crate::lightning::ln_db::{DBChannelDetails, LightningDB}; +use crate::lightning::ln_p2p::{connect_to_ln_node, ConnectionError}; +use crate::lightning::ln_serialization::NodeAddress; +use crate::lightning::ln_storage::LightningStorage; +use crate::utxo::utxo_common::UtxoTxBuilder; +use crate::utxo::{sat_from_big_decimal, FeePolicy, GetUtxoListOps, UtxoTxGenerationOps}; +use crate::{lp_coinfind_or_err, BalanceError, CoinFindError, GenerateTxError, MmCoinEnum, NumConversError, + UnexpectedDerivationMethod, UtxoRpcError}; + type OpenChannelResult = Result>; #[derive(Debug, Deserialize, Display, Serialize, SerializeErrorType)] diff --git a/mm2src/coins/rpc_command/lightning/send_payment.rs b/mm2src/coins/rpc_command/lightning/send_payment.rs index 3efde180d4..052329217e 100644 --- a/mm2src/coins/rpc_command/lightning/send_payment.rs +++ b/mm2src/coins/rpc_command/lightning/send_payment.rs @@ -1,7 +1,3 @@ -use crate::lightning::ln_p2p::connect_to_ln_node; -use crate::lightning::ln_serialization::PublicKeyForRPC; -use crate::lightning::ln_utils::PaymentError; -use crate::{lp_coinfind_or_err, CoinFindError, H256Json, MmCoinEnum}; use common::log::LogOnError; use common::HttpStatusCode; use db_common::sqlite::rusqlite::Error as SqlError; @@ -10,6 +6,11 @@ use lightning_invoice::Invoice; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; +use crate::lightning::ln_p2p::connect_to_ln_node; +use crate::lightning::ln_serialization::PublicKeyForRPC; +use crate::lightning::ln_utils::PaymentError; +use crate::{lp_coinfind_or_err, CoinFindError, H256Json, MmCoinEnum}; + type SendPaymentResult = Result>; #[derive(Debug, Deserialize, Display, Serialize, SerializeErrorType)] diff --git a/mm2src/coins/rpc_command/lightning/trusted_nodes.rs b/mm2src/coins/rpc_command/lightning/trusted_nodes.rs index 6f0f2fd36e..338a74ede0 100644 --- a/mm2src/coins/rpc_command/lightning/trusted_nodes.rs +++ b/mm2src/coins/rpc_command/lightning/trusted_nodes.rs @@ -1,11 +1,12 @@ -use crate::lightning::ln_serialization::PublicKeyForRPC; -use crate::lightning::ln_storage::LightningStorage; -use crate::{lp_coinfind_or_err, CoinFindError, MmCoinEnum}; use common::HttpStatusCode; use http::StatusCode; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; +use crate::lightning::ln_serialization::PublicKeyForRPC; +use crate::lightning::ln_storage::LightningStorage; +use crate::{lp_coinfind_or_err, CoinFindError, MmCoinEnum}; + type TrustedNodeResult = Result>; #[derive(Debug, Deserialize, Display, Serialize, SerializeErrorType)] diff --git a/mm2src/coins/rpc_command/lightning/update_channel.rs b/mm2src/coins/rpc_command/lightning/update_channel.rs index ad7768831f..2557e8c2da 100644 --- a/mm2src/coins/rpc_command/lightning/update_channel.rs +++ b/mm2src/coins/rpc_command/lightning/update_channel.rs @@ -1,11 +1,12 @@ -use crate::lightning::ln_conf::ChannelOptions; -use crate::{lp_coinfind_or_err, CoinFindError, MmCoinEnum}; use common::{async_blocking, HttpStatusCode}; use http::StatusCode; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; use uuid::Uuid; +use crate::lightning::ln_conf::ChannelOptions; +use crate::{lp_coinfind_or_err, CoinFindError, MmCoinEnum}; + type UpdateChannelResult = Result>; #[derive(Debug, Deserialize, Display, Serialize, SerializeErrorType)] diff --git a/mm2src/coins/solana.rs b/mm2src/coins/solana.rs index 5f7bb9e44d..fa50eb53c7 100644 --- a/mm2src/coins/solana.rs +++ b/mm2src/coins/solana.rs @@ -1,19 +1,8 @@ -use super::{CoinBalance, HistorySyncState, MarketCoinOps, MmCoin, SwapOps, TradeFee, TransactionEnum, WatcherOps}; -use crate::coin_errors::MyAddressError; -use crate::solana::solana_common::{lamports_to_sol, PrepareTransferData, SufficientBalanceError}; -use crate::solana::spl::SplTokenInfo; -use crate::{BalanceError, BalanceFut, CheckIfMyPaymentSentArgs, CoinFutSpawner, ConfirmPaymentInput, FeeApproxStage, - FoundSwapTxSpend, MakerSwapTakerCoin, MmCoinEnum, NegotiateSwapContractAddrErr, PaymentInstructionArgs, - PaymentInstructions, PaymentInstructionsErr, PrivKeyBuildPolicy, PrivKeyPolicyNotAllowed, - RawTransactionFut, RawTransactionRequest, RefundError, RefundPaymentArgs, RefundResult, - SearchForSwapTxSpendInput, SendMakerPaymentSpendPreimageInput, SendPaymentArgs, SignatureResult, - SpendPaymentArgs, TakerSwapMakerCoin, TradePreimageFut, TradePreimageResult, TradePreimageValue, - TransactionDetails, TransactionFut, TransactionResult, TransactionType, TxMarshalingErr, - UnexpectedDerivationMethod, ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr, - ValidateOtherPubKeyErr, ValidatePaymentError, ValidatePaymentFut, ValidatePaymentInput, - VerificationResult, WaitForHTLCTxSpendArgs, WatcherReward, WatcherRewardError, - WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, - WithdrawError, WithdrawFut, WithdrawRequest, WithdrawResult}; +use std::collections::HashMap; +use std::str::FromStr; +use std::sync::Mutex; +use std::{convert::TryFrom, fmt::Debug, ops::Deref, sync::Arc}; + use async_trait::async_trait; use base58::ToBase58; use bincode::{deserialize, serialize}; @@ -38,10 +27,23 @@ use solana_sdk::pubkey::ParsePubkeyError; use solana_sdk::transaction::Transaction; use solana_sdk::{pubkey::Pubkey, signature::{Keypair, Signer}}; -use std::collections::HashMap; -use std::str::FromStr; -use std::sync::Mutex; -use std::{convert::TryFrom, fmt::Debug, ops::Deref, sync::Arc}; + +use super::{CoinBalance, HistorySyncState, MarketCoinOps, MmCoin, SwapOps, TradeFee, TransactionEnum, WatcherOps}; +use crate::coin_errors::MyAddressError; +use crate::solana::solana_common::{lamports_to_sol, PrepareTransferData, SufficientBalanceError}; +use crate::solana::spl::SplTokenInfo; +use crate::{BalanceError, BalanceFut, CheckIfMyPaymentSentArgs, CoinFutSpawner, ConfirmPaymentInput, FeeApproxStage, + FoundSwapTxSpend, MakerSwapTakerCoin, MmCoinEnum, NegotiateSwapContractAddrErr, PaymentInstructionArgs, + PaymentInstructions, PaymentInstructionsErr, PrivKeyBuildPolicy, PrivKeyPolicyNotAllowed, + RawTransactionFut, RawTransactionRequest, RefundError, RefundPaymentArgs, RefundResult, + SearchForSwapTxSpendInput, SendMakerPaymentSpendPreimageInput, SendPaymentArgs, SignatureResult, + SpendPaymentArgs, TakerSwapMakerCoin, TradePreimageFut, TradePreimageResult, TradePreimageValue, + TransactionDetails, TransactionFut, TransactionResult, TransactionType, TxMarshalingErr, + UnexpectedDerivationMethod, ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr, + ValidateOtherPubKeyErr, ValidatePaymentError, ValidatePaymentFut, ValidatePaymentInput, + VerificationResult, WaitForHTLCTxSpendArgs, WatcherReward, WatcherRewardError, + WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, + WithdrawError, WithdrawFut, WithdrawRequest, WithdrawResult}; pub mod solana_common; mod solana_decode_tx_helpers; diff --git a/mm2src/coins/solana/solana_common.rs b/mm2src/coins/solana/solana_common.rs index 3f74c1caff..efc173fdab 100644 --- a/mm2src/coins/solana/solana_common.rs +++ b/mm2src/coins/solana/solana_common.rs @@ -1,6 +1,5 @@ -use crate::solana::SolanaCommonOps; -use crate::{BalanceError, MarketCoinOps, NumConversError, SignatureError, SignatureResult, SolanaCoin, - UnexpectedDerivationMethod, VerificationError, VerificationResult, WithdrawError}; +use std::str::FromStr; + use base58::FromBase58; use derive_more::Display; use futures::compat::Future01CompatExt; @@ -8,7 +7,10 @@ use mm2_err_handle::prelude::*; use mm2_number::bigdecimal::{BigDecimal, ToPrimitive}; use solana_sdk::native_token::LAMPORTS_PER_SOL; use solana_sdk::signature::{Signature, Signer}; -use std::str::FromStr; + +use crate::solana::SolanaCommonOps; +use crate::{BalanceError, MarketCoinOps, NumConversError, SignatureError, SignatureResult, SolanaCoin, + UnexpectedDerivationMethod, VerificationError, VerificationResult, WithdrawError}; #[derive(Debug, Display)] pub enum SufficientBalanceError { diff --git a/mm2src/coins/solana/solana_common_tests.rs b/mm2src/coins/solana/solana_common_tests.rs index 32b030b425..e45ea533ad 100644 --- a/mm2src/coins/solana/solana_common_tests.rs +++ b/mm2src/coins/solana/solana_common_tests.rs @@ -1,12 +1,14 @@ -use super::*; -use crate::solana::spl::{SplToken, SplTokenFields}; +use std::str::FromStr; + use bip39::Language; use crypto::privkey::key_pair_from_seed; use ed25519_dalek_bip32::{DerivationPath, ExtendedSecretKey}; use mm2_core::mm_ctx::MmCtxBuilder; use solana_client::rpc_client::RpcClient; use solana_sdk::commitment_config::{CommitmentConfig, CommitmentLevel}; -use std::str::FromStr; + +use super::*; +use crate::solana::spl::{SplToken, SplTokenFields}; pub enum SolanaNet { //Mainnet, diff --git a/mm2src/coins/solana/solana_decode_tx_helpers.rs b/mm2src/coins/solana/solana_decode_tx_helpers.rs index 2ac0876809..51639a3d96 100644 --- a/mm2src/coins/solana/solana_decode_tx_helpers.rs +++ b/mm2src/coins/solana/solana_decode_tx_helpers.rs @@ -1,9 +1,11 @@ extern crate serde_derive; -use crate::{NumConversResult, SolanaCoin, SolanaFeeDetails, TransactionDetails, TransactionType}; +use std::convert::TryFrom; + use mm2_number::BigDecimal; use solana_sdk::native_token::lamports_to_sol; -use std::convert::TryFrom; + +use crate::{NumConversResult, SolanaCoin, SolanaFeeDetails, TransactionDetails, TransactionType}; #[derive(Debug, Serialize, Deserialize)] pub struct SolanaConfirmedTransaction { diff --git a/mm2src/coins/solana/solana_tests.rs b/mm2src/coins/solana/solana_tests.rs index 05939b68c5..aedb57b9ea 100644 --- a/mm2src/coins/solana/solana_tests.rs +++ b/mm2src/coins/solana/solana_tests.rs @@ -1,15 +1,17 @@ -use super::*; -use crate::solana::solana_common_tests::{generate_key_pair_from_iguana_seed, generate_key_pair_from_seed, - solana_coin_for_test, SolanaNet}; -use crate::solana::solana_decode_tx_helpers::SolanaConfirmedTransaction; -use crate::MarketCoinOps; +use std::ops::Neg; +use std::str::FromStr; + use base58::ToBase58; use common::{block_on, Future01CompatExt}; use solana_client::rpc_request::TokenAccountsFilter; use solana_sdk::signature::{Signature, Signer}; use solana_transaction_status::UiTransactionEncoding; -use std::ops::Neg; -use std::str::FromStr; + +use super::*; +use crate::solana::solana_common_tests::{generate_key_pair_from_iguana_seed, generate_key_pair_from_seed, + solana_coin_for_test, SolanaNet}; +use crate::solana::solana_decode_tx_helpers::SolanaConfirmedTransaction; +use crate::MarketCoinOps; #[test] #[cfg(not(target_arch = "wasm32"))] diff --git a/mm2src/coins/solana/spl.rs b/mm2src/coins/solana/spl.rs index 134d8204ba..f4b05430eb 100644 --- a/mm2src/coins/solana/spl.rs +++ b/mm2src/coins/solana/spl.rs @@ -1,18 +1,8 @@ -use super::{CoinBalance, HistorySyncState, MarketCoinOps, MmCoin, SwapOps, TradeFee, TransactionEnum, WatcherOps}; -use crate::coin_errors::MyAddressError; -use crate::solana::solana_common::{ui_amount_to_amount, PrepareTransferData, SufficientBalanceError}; -use crate::solana::{solana_common, AccountError, SolanaCommonOps, SolanaFeeDetails}; -use crate::{BalanceFut, CheckIfMyPaymentSentArgs, CoinFutSpawner, ConfirmPaymentInput, FeeApproxStage, - FoundSwapTxSpend, MakerSwapTakerCoin, MmCoinEnum, NegotiateSwapContractAddrErr, PaymentInstructionArgs, - PaymentInstructions, PaymentInstructionsErr, RawTransactionFut, RawTransactionRequest, RefundError, - RefundPaymentArgs, RefundResult, SearchForSwapTxSpendInput, SendMakerPaymentSpendPreimageInput, - SendPaymentArgs, SignatureResult, SolanaCoin, SpendPaymentArgs, TakerSwapMakerCoin, TradePreimageFut, - TradePreimageResult, TradePreimageValue, TransactionDetails, TransactionFut, TransactionResult, - TransactionType, TxMarshalingErr, UnexpectedDerivationMethod, ValidateAddressResult, ValidateFeeArgs, - ValidateInstructionsErr, ValidateOtherPubKeyErr, ValidatePaymentError, ValidatePaymentFut, - ValidatePaymentInput, VerificationResult, WaitForHTLCTxSpendArgs, WatcherReward, WatcherRewardError, - WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, - WithdrawError, WithdrawFut, WithdrawRequest, WithdrawResult}; +use std::{convert::TryFrom, + fmt::{Debug, Formatter, Result as FmtResult}, + str::FromStr, + sync::Arc}; + use async_trait::async_trait; use bincode::serialize; use common::executor::{abortable_queue::AbortableQueue, AbortableSystem, AbortedError}; @@ -30,10 +20,22 @@ use solana_sdk::message::Message; use solana_sdk::transaction::Transaction; use solana_sdk::{pubkey::Pubkey, signature::Signer}; use spl_associated_token_account::{create_associated_token_account, get_associated_token_address}; -use std::{convert::TryFrom, - fmt::{Debug, Formatter, Result as FmtResult}, - str::FromStr, - sync::Arc}; + +use super::{CoinBalance, HistorySyncState, MarketCoinOps, MmCoin, SwapOps, TradeFee, TransactionEnum, WatcherOps}; +use crate::coin_errors::MyAddressError; +use crate::solana::solana_common::{ui_amount_to_amount, PrepareTransferData, SufficientBalanceError}; +use crate::solana::{solana_common, AccountError, SolanaCommonOps, SolanaFeeDetails}; +use crate::{BalanceFut, CheckIfMyPaymentSentArgs, CoinFutSpawner, ConfirmPaymentInput, FeeApproxStage, + FoundSwapTxSpend, MakerSwapTakerCoin, MmCoinEnum, NegotiateSwapContractAddrErr, PaymentInstructionArgs, + PaymentInstructions, PaymentInstructionsErr, RawTransactionFut, RawTransactionRequest, RefundError, + RefundPaymentArgs, RefundResult, SearchForSwapTxSpendInput, SendMakerPaymentSpendPreimageInput, + SendPaymentArgs, SignatureResult, SolanaCoin, SpendPaymentArgs, TakerSwapMakerCoin, TradePreimageFut, + TradePreimageResult, TradePreimageValue, TransactionDetails, TransactionFut, TransactionResult, + TransactionType, TxMarshalingErr, UnexpectedDerivationMethod, ValidateAddressResult, ValidateFeeArgs, + ValidateInstructionsErr, ValidateOtherPubKeyErr, ValidatePaymentError, ValidatePaymentFut, + ValidatePaymentInput, VerificationResult, WaitForHTLCTxSpendArgs, WatcherReward, WatcherRewardError, + WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, + WithdrawError, WithdrawFut, WithdrawRequest, WithdrawResult}; #[derive(Debug)] pub enum SplTokenCreationError { diff --git a/mm2src/coins/solana/spl_tests.rs b/mm2src/coins/solana/spl_tests.rs index c405f99b05..3d90a200a2 100644 --- a/mm2src/coins/solana/spl_tests.rs +++ b/mm2src/coins/solana/spl_tests.rs @@ -1,9 +1,11 @@ +use std::ops::Neg; +use std::str::FromStr; + +use common::{block_on, Future01CompatExt}; + use super::*; use crate::{solana::solana_common_tests::solana_coin_for_test, solana::solana_common_tests::{spl_coin_for_test, SolanaNet}}; -use common::{block_on, Future01CompatExt}; -use std::ops::Neg; -use std::str::FromStr; #[test] #[cfg(not(target_arch = "wasm32"))] diff --git a/mm2src/coins/tendermint/ibc/transfer_v1.rs b/mm2src/coins/tendermint/ibc/transfer_v1.rs index 34f693aaaa..1703a9146c 100644 --- a/mm2src/coins/tendermint/ibc/transfer_v1.rs +++ b/mm2src/coins/tendermint/ibc/transfer_v1.rs @@ -1,9 +1,11 @@ -use super::{ibc_proto::IBCTransferV1Proto, IBC_OUT_SOURCE_PORT, IBC_OUT_TIMEOUT_IN_NANOS}; -use crate::tendermint::type_urls::IBC_TRANSFER_TYPE_URL; +use std::convert::TryFrom; + use common::number_type_casting::SafeTypeCastingNumbers; use cosmrs::{tx::{Msg, MsgProto}, AccountId, Coin, ErrorReport}; -use std::convert::TryFrom; + +use super::{ibc_proto::IBCTransferV1Proto, IBC_OUT_SOURCE_PORT, IBC_OUT_TIMEOUT_IN_NANOS}; +use crate::tendermint::type_urls::IBC_TRANSFER_TYPE_URL; #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) struct MsgTransfer { diff --git a/mm2src/coins/tendermint/iris/htlc.rs b/mm2src/coins/tendermint/iris/htlc.rs index 4e7b679481..bf6cc4aa4f 100644 --- a/mm2src/coins/tendermint/iris/htlc.rs +++ b/mm2src/coins/tendermint/iris/htlc.rs @@ -20,12 +20,13 @@ // If the sender address doesn't have enough nyan tokens to complete unit tests, // check this page https://www.irisnet.org/docs/get-started/testnet.html#faucet -use super::htlc_proto::{ClaimHtlcProtoRep, CreateHtlcProtoRep}; +use std::convert::TryFrom; -use crate::tendermint::type_urls::{CLAIM_HTLC_TYPE_URL, CREATE_HTLC_TYPE_URL}; use cosmrs::{tx::{Msg, MsgProto}, AccountId, Coin, ErrorReport}; -use std::convert::TryFrom; + +use super::htlc_proto::{ClaimHtlcProtoRep, CreateHtlcProtoRep}; +use crate::tendermint::type_urls::{CLAIM_HTLC_TYPE_URL, CREATE_HTLC_TYPE_URL}; // https://github.com/irisnet/irismod/blob/043e058cd6e17f4f96d32f17bfd20b67debfab0b/proto/htlc/htlc.proto#L36 pub const HTLC_STATE_OPEN: i32 = 0; diff --git a/mm2src/coins/tendermint/rpc/tendermint_native_rpc.rs b/mm2src/coins/tendermint/rpc/tendermint_native_rpc.rs index dde181b3e3..d4ada636e1 100644 --- a/mm2src/coins/tendermint/rpc/tendermint_native_rpc.rs +++ b/mm2src/coins/tendermint/rpc/tendermint_native_rpc.rs @@ -1,14 +1,15 @@ -use async_trait::async_trait; use core::convert::{TryFrom, TryInto}; use core::str::FromStr; +use std::fmt; +use std::time::Duration; + +use async_trait::async_trait; pub use cosmrs::tendermint::abci::Path as AbciPath; use cosmrs::tendermint::abci::{self, Transaction}; use cosmrs::tendermint::block::Height; use cosmrs::tendermint::evidence::Evidence; use cosmrs::tendermint::Genesis; use serde::{de::DeserializeOwned, Serialize}; -use std::fmt; -use std::time::Duration; use tendermint_config::net; use tendermint_rpc::endpoint::validators::DEFAULT_VALIDATORS_PER_PAGE; use tendermint_rpc::endpoint::*; @@ -381,13 +382,14 @@ impl TryFrom for hyper::Uri { } mod sealed { + use std::io::Read; + use common::log::debug; use hyper::body::Buf; use hyper::client::connect::Connect; use hyper::client::HttpConnector; use hyper::{header, Uri}; use hyper_rustls::{HttpsConnector, HttpsConnectorBuilder}; - use std::io::Read; use tendermint_rpc::{Error, Response, SimpleRequest}; fn https_connector() -> HttpsConnector { diff --git a/mm2src/coins/tendermint/rpc/tendermint_wasm_rpc.rs b/mm2src/coins/tendermint/rpc/tendermint_wasm_rpc.rs index 036815a25f..9a8a00f5d5 100644 --- a/mm2src/coins/tendermint/rpc/tendermint_wasm_rpc.rs +++ b/mm2src/coins/tendermint/rpc/tendermint_wasm_rpc.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use common::APPLICATION_JSON; pub use cosmrs::tendermint::abci::Path as AbciPath; use cosmrs::tendermint::abci::Transaction; @@ -8,7 +10,6 @@ use http::uri::InvalidUri; use http::{StatusCode, Uri}; use mm2_net::transport::SlurpError; use mm2_net::wasm_http::FetchRequest; -use std::str::FromStr; use tendermint_rpc::endpoint::{abci_info, broadcast}; pub use tendermint_rpc::endpoint::{abci_query::{AbciQuery, Request as AbciRequest}, health::Request as HealthRequest, @@ -110,9 +111,10 @@ impl HttpClient { } mod tests { - use super::*; use wasm_bindgen_test::*; + use super::*; + wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] diff --git a/mm2src/coins/tendermint/tendermint_coin.rs b/mm2src/coins/tendermint/tendermint_coin.rs index 1920c38709..fc557964de 100644 --- a/mm2src/coins/tendermint/tendermint_coin.rs +++ b/mm2src/coins/tendermint/tendermint_coin.rs @@ -1,34 +1,10 @@ -use super::ibc::transfer_v1::MsgTransfer; -use super::ibc::IBC_GAS_LIMIT_DEFAULT; -use super::iris::ethermint_account::EthermintAccount; -use super::iris::htlc::{IrisHtlc, MsgClaimHtlc, MsgCreateHtlc, HTLC_STATE_COMPLETED, HTLC_STATE_OPEN, - HTLC_STATE_REFUNDED}; -use super::iris::htlc_proto::{CreateHtlcProtoRep, QueryHtlcRequestProto, QueryHtlcResponseProto}; -use super::rpc::*; -use crate::coin_errors::{MyAddressError, ValidatePaymentError}; -use crate::rpc_command::tendermint::{IBCChainRegistriesResponse, IBCChainRegistriesResult, IBCChainsRequestError, - IBCTransferChannel, IBCTransferChannelTag, IBCTransferChannelsRequest, - IBCTransferChannelsRequestError, IBCTransferChannelsResponse, - IBCTransferChannelsResult, IBCWithdrawRequest, CHAIN_REGISTRY_BRANCH, - CHAIN_REGISTRY_IBC_DIR_NAME, CHAIN_REGISTRY_REPO_NAME, CHAIN_REGISTRY_REPO_OWNER}; -use crate::tendermint::ibc::IBC_OUT_SOURCE_PORT; -use crate::utxo::sat_from_big_decimal; -use crate::utxo::utxo_common::big_decimal_from_sat; -use crate::{big_decimal_from_sat_unsigned, BalanceError, BalanceFut, BigDecimal, CheckIfMyPaymentSentArgs, - CoinBalance, CoinFutSpawner, ConfirmPaymentInput, FeeApproxStage, FoundSwapTxSpend, HistorySyncState, - MakerSwapTakerCoin, MarketCoinOps, MmCoin, MmCoinEnum, NegotiateSwapContractAddrErr, - PaymentInstructionArgs, PaymentInstructions, PaymentInstructionsErr, PrivKeyBuildPolicy, PrivKeyPolicy, - PrivKeyPolicyNotAllowed, RawTransactionError, RawTransactionFut, RawTransactionRequest, RawTransactionRes, - RefundError, RefundPaymentArgs, RefundResult, RpcCommonOps, SearchForSwapTxSpendInput, - SendMakerPaymentSpendPreimageInput, SendPaymentArgs, SignatureError, SignatureResult, SpendPaymentArgs, - SwapOps, TakerSwapMakerCoin, TradeFee, TradePreimageError, TradePreimageFut, TradePreimageResult, - TradePreimageValue, TransactionDetails, TransactionEnum, TransactionErr, TransactionFut, - TransactionResult, TransactionType, TxFeeDetails, TxMarshalingErr, UnexpectedDerivationMethod, - ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr, ValidateOtherPubKeyErr, - ValidatePaymentFut, ValidatePaymentInput, VerificationError, VerificationResult, WaitForHTLCTxSpendArgs, - WatcherOps, WatcherReward, WatcherRewardError, WatcherSearchForSwapTxSpendInput, - WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawError, WithdrawFee, WithdrawFrom, - WithdrawFut, WithdrawRequest}; +use std::collections::HashMap; +use std::convert::TryFrom; +use std::ops::Deref; +use std::str::FromStr; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + use async_std::prelude::FutureExt as AsyncStdFutureExt; use async_trait::async_trait; use bitcrypto::{dhash160, sha256}; @@ -69,14 +45,40 @@ use primitives::hash::H256; use prost::{DecodeError, Message}; use rpc::v1::types::Bytes as BytesJson; use serde_json::{self as json, Value as Json}; -use std::collections::HashMap; -use std::convert::TryFrom; -use std::ops::Deref; -use std::str::FromStr; -use std::sync::{Arc, Mutex}; -use std::time::Duration; use uuid::Uuid; +use super::ibc::transfer_v1::MsgTransfer; +use super::ibc::IBC_GAS_LIMIT_DEFAULT; +use super::iris::ethermint_account::EthermintAccount; +use super::iris::htlc::{IrisHtlc, MsgClaimHtlc, MsgCreateHtlc, HTLC_STATE_COMPLETED, HTLC_STATE_OPEN, + HTLC_STATE_REFUNDED}; +use super::iris::htlc_proto::{CreateHtlcProtoRep, QueryHtlcRequestProto, QueryHtlcResponseProto}; +use super::rpc::*; +use crate::coin_errors::{MyAddressError, ValidatePaymentError}; +use crate::rpc_command::tendermint::{IBCChainRegistriesResponse, IBCChainRegistriesResult, IBCChainsRequestError, + IBCTransferChannel, IBCTransferChannelTag, IBCTransferChannelsRequest, + IBCTransferChannelsRequestError, IBCTransferChannelsResponse, + IBCTransferChannelsResult, IBCWithdrawRequest, CHAIN_REGISTRY_BRANCH, + CHAIN_REGISTRY_IBC_DIR_NAME, CHAIN_REGISTRY_REPO_NAME, CHAIN_REGISTRY_REPO_OWNER}; +use crate::tendermint::ibc::IBC_OUT_SOURCE_PORT; +use crate::utxo::sat_from_big_decimal; +use crate::utxo::utxo_common::big_decimal_from_sat; +use crate::{big_decimal_from_sat_unsigned, BalanceError, BalanceFut, BigDecimal, CheckIfMyPaymentSentArgs, + CoinBalance, CoinFutSpawner, ConfirmPaymentInput, FeeApproxStage, FoundSwapTxSpend, HistorySyncState, + MakerSwapTakerCoin, MarketCoinOps, MmCoin, MmCoinEnum, NegotiateSwapContractAddrErr, + PaymentInstructionArgs, PaymentInstructions, PaymentInstructionsErr, PrivKeyBuildPolicy, PrivKeyPolicy, + PrivKeyPolicyNotAllowed, RawTransactionError, RawTransactionFut, RawTransactionRequest, RawTransactionRes, + RefundError, RefundPaymentArgs, RefundResult, RpcCommonOps, SearchForSwapTxSpendInput, + SendMakerPaymentSpendPreimageInput, SendPaymentArgs, SignatureError, SignatureResult, SpendPaymentArgs, + SwapOps, TakerSwapMakerCoin, TradeFee, TradePreimageError, TradePreimageFut, TradePreimageResult, + TradePreimageValue, TransactionDetails, TransactionEnum, TransactionErr, TransactionFut, + TransactionResult, TransactionType, TxFeeDetails, TxMarshalingErr, UnexpectedDerivationMethod, + ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr, ValidateOtherPubKeyErr, + ValidatePaymentFut, ValidatePaymentInput, VerificationError, VerificationResult, WaitForHTLCTxSpendArgs, + WatcherOps, WatcherReward, WatcherRewardError, WatcherSearchForSwapTxSpendInput, + WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawError, WithdrawFee, WithdrawFrom, + WithdrawFut, WithdrawRequest}; + // ABCI Request Paths const ABCI_GET_LATEST_BLOCK_PATH: &str = "/cosmos.base.tendermint.v1beta1.Service/GetLatestBlock"; const ABCI_GET_BLOCK_BY_HEIGHT_PATH: &str = "/cosmos.base.tendermint.v1beta1.Service/GetBlockByHeight"; @@ -2809,12 +2811,13 @@ pub fn tendermint_priv_key_policy( #[cfg(test)] pub mod tendermint_coin_tests { - use super::*; + use std::mem::discriminant; use common::{block_on, wait_until_ms, DEX_FEE_ADDR_RAW_PUBKEY}; use cosmrs::proto::cosmos::tx::v1beta1::{GetTxRequest, GetTxResponse, GetTxsEventResponse}; use crypto::privkey::key_pair_from_seed; - use std::mem::discriminant; + + use super::*; pub const IRIS_TESTNET_HTLC_PAIR1_SEED: &str = "iris test seed"; // pub const IRIS_TESTNET_HTLC_PAIR1_PUB_KEY: &str = &[ diff --git a/mm2src/coins/tendermint/tendermint_token.rs b/mm2src/coins/tendermint/tendermint_token.rs index d753a0e61d..d91a55b42b 100644 --- a/mm2src/coins/tendermint/tendermint_token.rs +++ b/mm2src/coins/tendermint/tendermint_token.rs @@ -1,5 +1,27 @@ //! Module containing implementation for Tendermint Tokens. They include native assets + IBC +use std::ops::Deref; +use std::str::FromStr; +use std::sync::Arc; + +use async_trait::async_trait; +use bitcrypto::sha256; +use common::executor::abortable_queue::AbortableQueue; +use common::executor::{AbortableSystem, AbortedError}; +use common::log::warn; +use common::Future01CompatExt; +use cosmrs::{bank::MsgSend, + tx::{Fee, Msg}, + AccountId, Coin, Denom}; +use futures::{FutureExt, TryFutureExt}; +use futures01::Future; +use keys::KeyPair; +use mm2_core::mm_ctx::MmArc; +use mm2_err_handle::prelude::*; +use mm2_number::MmNumber; +use rpc::v1::types::Bytes as BytesJson; +use serde_json::Value as Json; + use super::ibc::transfer_v1::MsgTransfer; use super::ibc::IBC_GAS_LIMIT_DEFAULT; use super::{TendermintCoin, TendermintFeeDetails, GAS_LIMIT_DEFAULT, MIN_TX_SATOSHIS, TIMEOUT_HEIGHT_DELTA, @@ -21,26 +43,6 @@ use crate::{big_decimal_from_sat_unsigned, utxo::sat_from_big_decimal, BalanceFu WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawError, WithdrawFrom, WithdrawFut, WithdrawRequest}; use crate::{MmCoinEnum, PaymentInstructionArgs, WatcherReward, WatcherRewardError}; -use async_trait::async_trait; -use bitcrypto::sha256; -use common::executor::abortable_queue::AbortableQueue; -use common::executor::{AbortableSystem, AbortedError}; -use common::log::warn; -use common::Future01CompatExt; -use cosmrs::{bank::MsgSend, - tx::{Fee, Msg}, - AccountId, Coin, Denom}; -use futures::{FutureExt, TryFutureExt}; -use futures01::Future; -use keys::KeyPair; -use mm2_core::mm_ctx::MmArc; -use mm2_err_handle::prelude::*; -use mm2_number::MmNumber; -use rpc::v1::types::Bytes as BytesJson; -use serde_json::Value as Json; -use std::ops::Deref; -use std::str::FromStr; -use std::sync::Arc; pub struct TendermintTokenImpl { pub ticker: String, diff --git a/mm2src/coins/tendermint/tendermint_tx_history_v2.rs b/mm2src/coins/tendermint/tendermint_tx_history_v2.rs index adead7550e..bfecaef0d0 100644 --- a/mm2src/coins/tendermint/tendermint_tx_history_v2.rs +++ b/mm2src/coins/tendermint/tendermint_tx_history_v2.rs @@ -1,10 +1,6 @@ -use super::{rpc::*, AllBalancesResult, TendermintCoin, TendermintCommons, TendermintToken}; +use std::cmp; +use std::convert::Infallible; -use crate::my_tx_history_v2::{CoinWithTxHistoryV2, MyTxHistoryErrorV2, MyTxHistoryTarget, TxHistoryStorage}; -use crate::tendermint::{CustomTendermintMsgType, TendermintFeeDetails}; -use crate::tx_history_storage::{GetTxHistoryFilters, WalletId}; -use crate::utxo::utxo_common::big_decimal_from_sat_unsigned; -use crate::{HistorySyncState, MarketCoinOps, MmCoin, TransactionDetails, TransactionType, TxFeeDetails}; use async_trait::async_trait; use bitcrypto::sha256; use common::executor::Timer; @@ -19,8 +15,13 @@ use mm2_state_machine::prelude::*; use mm2_state_machine::state_machine::StateMachineTrait; use primitives::hash::H256; use rpc::v1::types::Bytes as BytesJson; -use std::cmp; -use std::convert::Infallible; + +use super::{rpc::*, AllBalancesResult, TendermintCoin, TendermintCommons, TendermintToken}; +use crate::my_tx_history_v2::{CoinWithTxHistoryV2, MyTxHistoryErrorV2, MyTxHistoryTarget, TxHistoryStorage}; +use crate::tendermint::{CustomTendermintMsgType, TendermintFeeDetails}; +use crate::tx_history_storage::{GetTxHistoryFilters, WalletId}; +use crate::utxo::utxo_common::big_decimal_from_sat_unsigned; +use crate::{HistorySyncState, MarketCoinOps, MmCoin, TransactionDetails, TransactionType, TxFeeDetails}; macro_rules! try_or_return_stopped_as_err { ($exp:expr, $reason: expr, $fmt:literal) => { diff --git a/mm2src/coins/test_coin.rs b/mm2src/coins/test_coin.rs index 24408cf506..d666bf73e9 100644 --- a/mm2src/coins/test_coin.rs +++ b/mm2src/coins/test_coin.rs @@ -1,5 +1,19 @@ #![allow(clippy::all)] +use std::ops::Deref; +use std::sync::Arc; + +use async_trait::async_trait; +use common::executor::AbortedError; +use futures01::Future; +use keys::KeyPair; +use mm2_core::mm_ctx::MmArc; +use mm2_err_handle::prelude::*; +use mm2_number::{BigDecimal, MmNumber}; +use mocktopus::macros::*; +use rpc::v1::types::Bytes as BytesJson; +use serde_json::Value as Json; + use super::{CoinBalance, HistorySyncState, MarketCoinOps, MmCoin, RawTransactionFut, RawTransactionRequest, SwapOps, TradeFee, TransactionEnum, TransactionFut}; use crate::{coin_errors::MyAddressError, BalanceFut, CanRefundHtlc, CheckIfMyPaymentSentArgs, CoinFutSpawner, @@ -15,18 +29,6 @@ use crate::{coin_errors::MyAddressError, BalanceFut, CanRefundHtlc, CheckIfMyPay VerificationResult, WaitForHTLCTxSpendArgs, WatcherOps, WatcherReward, WatcherRewardError, WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawFut, WithdrawRequest}; -use async_trait::async_trait; -use common::executor::AbortedError; -use futures01::Future; -use keys::KeyPair; -use mm2_core::mm_ctx::MmArc; -use mm2_err_handle::prelude::*; -use mm2_number::{BigDecimal, MmNumber}; -use mocktopus::macros::*; -use rpc::v1::types::Bytes as BytesJson; -use serde_json::Value as Json; -use std::ops::Deref; -use std::sync::Arc; /// Dummy coin struct used in tests which functions are unimplemented but then mocked /// in specific test to emulate the required behaviour diff --git a/mm2src/coins/tx_history_storage/mod.rs b/mm2src/coins/tx_history_storage/mod.rs index 1f0ca4f8d8..d5692e00b0 100644 --- a/mm2src/coins/tx_history_storage/mod.rs +++ b/mm2src/coins/tx_history_storage/mod.rs @@ -1,5 +1,6 @@ -use crate::my_tx_history_v2::TxHistoryStorage; -use crate::TransactionType; +use std::collections::HashSet; +use std::iter::FromIterator; + use derive_more::Display; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; @@ -7,8 +8,9 @@ use num_traits::Zero; use primitives::hash::H160; use serde::de::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use std::collections::HashSet; -use std::iter::FromIterator; + +use crate::my_tx_history_v2::TxHistoryStorage; +use crate::TransactionType; #[cfg(target_arch = "wasm32")] pub mod wasm; diff --git a/mm2src/coins/tx_history_storage/sql_tx_history_storage_v2.rs b/mm2src/coins/tx_history_storage/sql_tx_history_storage_v2.rs index 49993e4c6a..fd2850d5f2 100644 --- a/mm2src/coins/tx_history_storage/sql_tx_history_storage_v2.rs +++ b/mm2src/coins/tx_history_storage/sql_tx_history_storage_v2.rs @@ -1,7 +1,6 @@ -use crate::my_tx_history_v2::{GetHistoryResult, RemoveTxResult, TxHistoryStorage, TxHistoryStorageError}; -use crate::tx_history_storage::{token_id_from_tx_type, ConfirmationStatus, CreateTxHistoryStorageError, - FilteringAddresses, GetTxHistoryFilters, WalletId}; -use crate::TransactionDetails; +use std::convert::TryInto; +use std::sync::{Arc, Mutex}; + use async_trait::async_trait; use common::{async_blocking, PagingOptionsEnum}; use db_common::sql_build::*; @@ -12,8 +11,11 @@ use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; use rpc::v1::types::Bytes as BytesJson; use serde_json::{self as json}; -use std::convert::TryInto; -use std::sync::{Arc, Mutex}; + +use crate::my_tx_history_v2::{GetHistoryResult, RemoveTxResult, TxHistoryStorage, TxHistoryStorageError}; +use crate::tx_history_storage::{token_id_from_tx_type, ConfirmationStatus, CreateTxHistoryStorageError, + FilteringAddresses, GetTxHistoryFilters, WalletId}; +use crate::TransactionDetails; fn tx_history_table(wallet_id: &WalletId) -> String { wallet_id.to_sql_table_name() + "_tx_history" } diff --git a/mm2src/coins/tx_history_storage/tx_history_v2_tests.rs b/mm2src/coins/tx_history_storage/tx_history_v2_tests.rs index d160b68fa3..210940672f 100644 --- a/mm2src/coins/tx_history_storage/tx_history_v2_tests.rs +++ b/mm2src/coins/tx_history_storage/tx_history_v2_tests.rs @@ -1,16 +1,18 @@ //! Consider using very dirty [Rust script](https://pastebin.ubuntu.com/p/9r2mDmGGHT/) //! to print all transactions from `../for_tests/tBCH_tx_history_fixtures.json` ordered. -use crate::my_tx_history_v2::{GetHistoryResult, TxHistoryStorage}; -use crate::tx_history_storage::{FilteringAddresses, GetTxHistoryFilters, TxHistoryStorageBuilder, WalletId}; -use crate::{BytesJson, TransactionDetails}; -use common::PagingOptionsEnum; -use mm2_test_helpers::for_tests::mm_ctx_with_custom_db; -use serde_json as json; use std::collections::HashMap; use std::iter::FromIterator; use std::num::NonZeroUsize; +use common::PagingOptionsEnum; +use mm2_test_helpers::for_tests::mm_ctx_with_custom_db; +use serde_json as json; + +use crate::my_tx_history_v2::{GetHistoryResult, TxHistoryStorage}; +use crate::tx_history_storage::{FilteringAddresses, GetTxHistoryFilters, TxHistoryStorageBuilder, WalletId}; +use crate::{BytesJson, TransactionDetails}; + const BCH_TX_HISTORY_STR: &str = include_str!("../for_tests/tBCH_tx_history_fixtures.json"); lazy_static! { @@ -580,11 +582,12 @@ async fn test_get_history_for_addresses_impl() { #[cfg(all(test, not(target_arch = "wasm32")))] mod native_tests { + use common::block_on; + use mm2_test_helpers::for_tests::mm_ctx_with_custom_db; + use super::wallet_id_for_test; use crate::my_tx_history_v2::TxHistoryStorage; use crate::tx_history_storage::sql_tx_history_storage_v2::SqliteTxHistoryStorage; - use common::block_on; - use mm2_test_helpers::for_tests::mm_ctx_with_custom_db; #[test] fn test_init_collection() { @@ -647,11 +650,12 @@ mod native_tests { #[cfg(target_arch = "wasm32")] mod wasm_tests { + use mm2_test_helpers::for_tests::mm_ctx_with_custom_db; + use wasm_bindgen_test::*; + use super::wallet_id_for_test; use crate::my_tx_history_v2::TxHistoryStorage; use crate::tx_history_storage::wasm::tx_history_storage_v2::IndexedDbTxHistoryStorage; - use mm2_test_helpers::for_tests::mm_ctx_with_custom_db; - use wasm_bindgen_test::*; wasm_bindgen_test_configure!(run_in_browser); diff --git a/mm2src/coins/tx_history_storage/wasm/mod.rs b/mm2src/coins/tx_history_storage/wasm/mod.rs index a3ba6cb193..2c97f87a48 100644 --- a/mm2src/coins/tx_history_storage/wasm/mod.rs +++ b/mm2src/coins/tx_history_storage/wasm/mod.rs @@ -1,7 +1,8 @@ -use crate::my_tx_history_v2::TxHistoryStorageError; use mm2_db::indexed_db::{DbTransactionError, InitDbError}; use mm2_err_handle::prelude::*; +use crate::my_tx_history_v2::TxHistoryStorageError; + pub mod tx_history_db; pub mod tx_history_storage_v1; pub mod tx_history_storage_v2; diff --git a/mm2src/coins/tx_history_storage/wasm/tx_history_db.rs b/mm2src/coins/tx_history_storage/wasm/tx_history_db.rs index c88fd3defc..5929fa197f 100644 --- a/mm2src/coins/tx_history_storage/wasm/tx_history_db.rs +++ b/mm2src/coins/tx_history_storage/wasm/tx_history_db.rs @@ -1,8 +1,9 @@ -use crate::tx_history_storage::wasm::tx_history_storage_v1::TxHistoryTableV1; -use crate::tx_history_storage::wasm::tx_history_storage_v2::{TxCacheTableV2, TxHistoryTableV2}; use async_trait::async_trait; use mm2_db::indexed_db::{DbIdentifier, DbInstance, DbLocked, IndexedDb, IndexedDbBuilder, InitDbResult}; +use crate::tx_history_storage::wasm::tx_history_storage_v1::TxHistoryTableV1; +use crate::tx_history_storage::wasm::tx_history_storage_v2::{TxCacheTableV2, TxHistoryTableV2}; + const DB_NAME: &str = "tx_history"; const DB_VERSION: u32 = 1; diff --git a/mm2src/coins/tx_history_storage/wasm/tx_history_storage_v1.rs b/mm2src/coins/tx_history_storage/wasm/tx_history_storage_v1.rs index 90ef077cde..a13786d136 100644 --- a/mm2src/coins/tx_history_storage/wasm/tx_history_storage_v1.rs +++ b/mm2src/coins/tx_history_storage/wasm/tx_history_storage_v1.rs @@ -1,7 +1,8 @@ +use mm2_db::indexed_db::{DbIdentifier, DbInstance, DbUpgrader, OnUpgradeResult, TableSignature}; + use crate::tx_history_storage::wasm::tx_history_db::TxHistoryDb; use crate::tx_history_storage::wasm::WasmTxHistoryResult; use crate::TransactionDetails; -use mm2_db::indexed_db::{DbIdentifier, DbInstance, DbUpgrader, OnUpgradeResult, TableSignature}; pub async fn load_tx_history( db: &TxHistoryDb, @@ -86,10 +87,11 @@ impl TableSignature for TxHistoryTableV1 { } mod tests { - use super::*; use serde_json as json; use wasm_bindgen_test::*; + use super::*; + wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] diff --git a/mm2src/coins/tx_history_storage/wasm/tx_history_storage_v2.rs b/mm2src/coins/tx_history_storage/wasm/tx_history_storage_v2.rs index 1b19565bf7..bb6a7f3c9a 100644 --- a/mm2src/coins/tx_history_storage/wasm/tx_history_storage_v2.rs +++ b/mm2src/coins/tx_history_storage/wasm/tx_history_storage_v2.rs @@ -1,9 +1,3 @@ -use crate::my_tx_history_v2::{GetHistoryResult, RemoveTxResult, TxHistoryStorage}; -use crate::tx_history_storage::wasm::tx_history_db::{TxHistoryDb, TxHistoryDbLocked}; -use crate::tx_history_storage::wasm::{WasmTxHistoryError, WasmTxHistoryResult}; -use crate::tx_history_storage::{token_id_from_tx_type, ConfirmationStatus, CreateTxHistoryStorageError, - FilteringAddresses, GetTxHistoryFilters, WalletId}; -use crate::{compare_transaction_details, CoinsContext, TransactionDetails}; use async_trait::async_trait; use common::PagingOptionsEnum; use itertools::Itertools; @@ -13,6 +7,13 @@ use mm2_err_handle::prelude::*; use rpc::v1::types::Bytes as BytesJson; use serde_json::{self as json, Value as Json}; +use crate::my_tx_history_v2::{GetHistoryResult, RemoveTxResult, TxHistoryStorage}; +use crate::tx_history_storage::wasm::tx_history_db::{TxHistoryDb, TxHistoryDbLocked}; +use crate::tx_history_storage::wasm::{WasmTxHistoryError, WasmTxHistoryResult}; +use crate::tx_history_storage::{token_id_from_tx_type, ConfirmationStatus, CreateTxHistoryStorageError, + FilteringAddresses, GetTxHistoryFilters, WalletId}; +use crate::{compare_transaction_details, CoinsContext, TransactionDetails}; + impl WalletId { /// If [`WalletId::hd_wallet_rmd160`] is not specified, /// we need to exclude transactions of each HD wallet by specifying an empty `hd_wallet_rmd160`. diff --git a/mm2src/coins/utxo.rs b/mm2src/coins/utxo.rs index ab1fee5bde..ab3ea9e3ef 100644 --- a/mm2src/coins/utxo.rs +++ b/mm2src/coins/utxo.rs @@ -39,6 +39,18 @@ pub mod utxo_standard; pub mod utxo_tx_history_v2; pub mod utxo_withdraw; +use std::array::TryFromSliceError; +use std::collections::{HashMap, HashSet}; +use std::convert::TryInto; +use std::hash::Hash; +use std::num::{NonZeroU64, TryFromIntError}; +use std::ops::Deref; +#[cfg(not(target_arch = "wasm32"))] +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::sync::atomic::{AtomicBool, AtomicU64}; +use std::sync::{Arc, Mutex, Weak}; + use async_trait::async_trait; #[cfg(not(target_arch = "wasm32"))] use bitcoin::network::constants::Network as BitcoinNetwork; @@ -79,17 +91,6 @@ use serialization::{serialize, serialize_with_flags, Error as SerError, SERIALIZ use spv_validation::conf::SPVConf; use spv_validation::helpers_validation::SPVError; use spv_validation::storage::BlockHeaderStorageError; -use std::array::TryFromSliceError; -use std::collections::{HashMap, HashSet}; -use std::convert::TryInto; -use std::hash::Hash; -use std::num::{NonZeroU64, TryFromIntError}; -use std::ops::Deref; -#[cfg(not(target_arch = "wasm32"))] -use std::path::{Path, PathBuf}; -use std::str::FromStr; -use std::sync::atomic::{AtomicBool, AtomicU64}; -use std::sync::{Arc, Mutex, Weak}; use utxo_builder::UtxoConfBuilder; use utxo_common::{big_decimal_from_sat, UtxoTxBuilder}; use utxo_signer::with_key_pair::sign_tx; @@ -142,10 +143,11 @@ pub type UtxoHDAddress = HDAddress; #[cfg(windows)] #[cfg(not(target_arch = "wasm32"))] fn get_special_folder_path() -> PathBuf { - use libc::c_char; use std::ffi::CStr; use std::mem::zeroed; use std::ptr::null_mut; + + use libc::c_char; use winapi::shared::minwindef::MAX_PATH; use winapi::um::shlobj::SHGetSpecialFolderPathA; use winapi::um::shlobj::CSIDL_APPDATA; diff --git a/mm2src/coins/utxo/bch.rs b/mm2src/coins/utxo/bch.rs index 393f25cd54..7e30935f75 100644 --- a/mm2src/coins/utxo/bch.rs +++ b/mm2src/coins/utxo/bch.rs @@ -1,3 +1,18 @@ +use std::sync::MutexGuard; + +use common::executor::{AbortableSystem, AbortedError}; +use common::log::warn; +use derive_more::Display; +use futures::{FutureExt, TryFutureExt}; +use itertools::Either as EitherIter; +use keys::hash::H256; +use keys::CashAddress; +pub use keys::NetworkPrefix as CashAddrPrefix; +use mm2_metrics::MetricsArc; +use mm2_number::MmNumber; +use serde_json::{self as json, Value as Json}; +use serialization::{deserialize, CoinVariant}; + use super::*; use crate::coin_errors::MyAddressError; use crate::my_tx_history_v2::{CoinWithTxHistoryV2, MyTxHistoryErrorV2, MyTxHistoryTarget, TxDetailsBuilder, @@ -20,19 +35,6 @@ use crate::{BlockHeightAndTime, CanRefundHtlc, CheckIfMyPaymentSentArgs, CoinBal ValidatePaymentError, ValidatePaymentFut, ValidatePaymentInput, VerificationResult, WaitForHTLCTxSpendArgs, WatcherOps, WatcherReward, WatcherRewardError, WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawFut}; -use common::executor::{AbortableSystem, AbortedError}; -use common::log::warn; -use derive_more::Display; -use futures::{FutureExt, TryFutureExt}; -use itertools::Either as EitherIter; -use keys::hash::H256; -use keys::CashAddress; -pub use keys::NetworkPrefix as CashAddrPrefix; -use mm2_metrics::MetricsArc; -use mm2_number::MmNumber; -use serde_json::{self as json, Value as Json}; -use serialization::{deserialize, CoinVariant}; -use std::sync::MutexGuard; pub type BchUnspentMap = HashMap; @@ -1463,10 +1465,11 @@ pub fn bch_coin_for_test() -> BchCoin { #[cfg(test)] mod bch_tests { + use common::block_on; + use super::*; use crate::my_tx_history_v2::for_tests::init_storage_for; use crate::{TransactionType, TxFeeDetails}; - use common::block_on; #[test] fn test_get_slp_genesis_params() { diff --git a/mm2src/coins/utxo/bchd_grpc.rs b/mm2src/coins/utxo/bchd_grpc.rs index 6017f3b9c0..14319bdf06 100644 --- a/mm2src/coins/utxo/bchd_grpc.rs +++ b/mm2src/coins/utxo/bchd_grpc.rs @@ -1,7 +1,3 @@ -/// https://bchd.cash/ -/// https://bchd.fountainhead.cash/ -use super::bchd_pb::*; -use crate::{coin_errors::ValidatePaymentError, utxo::slp::SlpUnspent}; use chain::OutPoint; use derive_more::Display; use futures::future::join_all; @@ -11,6 +7,11 @@ use keys::hash::H256; use mm2_err_handle::prelude::*; use mm2_net::grpc_web::{post_grpc_web, PostGrpcWebErr}; +/// https://bchd.cash/ +/// https://bchd.fountainhead.cash/ +use super::bchd_pb::*; +use crate::{coin_errors::ValidatePaymentError, utxo::slp::SlpUnspent}; + #[derive(Debug, Display)] #[display(fmt = "Error {:?} on request to the url {}", err, to_url)] pub struct GrpcWebMultiUrlReqErr { @@ -241,11 +242,12 @@ pub async fn check_slp_transaction( #[cfg(test)] mod bchd_grpc_tests { - use super::*; - use crate::utxo::rpc_clients::UnspentInfo; use common::block_on; use mm2_test_helpers::for_tests::BCHD_TESTNET_URLS; + use super::*; + use crate::utxo::rpc_clients::UnspentInfo; + #[test] #[ignore] fn test_validate_slp_utxos_valid() { diff --git a/mm2src/coins/utxo/qtum.rs b/mm2src/coins/utxo/qtum.rs index 2f4c57ac6e..362de4ba14 100644 --- a/mm2src/coins/utxo/qtum.rs +++ b/mm2src/coins/utxo/qtum.rs @@ -1,3 +1,14 @@ +use common::executor::{AbortableSystem, AbortedError}; +use crypto::Bip44Chain; +use ethereum_types::H160; +use futures::{FutureExt, TryFutureExt}; +use keys::AddressHashEnum; +use mm2_metrics::MetricsArc; +use mm2_number::MmNumber; +use serde::Serialize; +use serialization::CoinVariant; +use utxo_signer::UtxoSignerOps; + use super::*; use crate::coin_balance::{self, EnableCoinBalanceError, EnabledCoinBalanceParams, HDAccountBalance, HDAddressBalance, HDWalletBalance, HDWalletBalanceOps}; @@ -35,16 +46,6 @@ use crate::{eth, CanRefundHtlc, CheckIfMyPaymentSentArgs, CoinBalance, CoinWithD VerificationResult, WaitForHTLCTxSpendArgs, WatcherOps, WatcherReward, WatcherRewardError, WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawFut, WithdrawSenderAddress}; -use common::executor::{AbortableSystem, AbortedError}; -use crypto::Bip44Chain; -use ethereum_types::H160; -use futures::{FutureExt, TryFutureExt}; -use keys::AddressHashEnum; -use mm2_metrics::MetricsArc; -use mm2_number::MmNumber; -use serde::Serialize; -use serialization::CoinVariant; -use utxo_signer::UtxoSignerOps; #[derive(Debug, Display)] pub enum Qrc20AddressError { diff --git a/mm2src/coins/utxo/qtum_delegation.rs b/mm2src/coins/utxo/qtum_delegation.rs index 231d230c51..67cb570815 100644 --- a/mm2src/coins/utxo/qtum_delegation.rs +++ b/mm2src/coins/utxo/qtum_delegation.rs @@ -1,14 +1,6 @@ -use crate::qrc20::rpc_clients::Qrc20ElectrumOps; -use crate::qrc20::script_pubkey::generate_contract_call_script_pubkey; -use crate::qrc20::{contract_addr_into_rpc_format, ContractCallOutput, GenerateQrc20TxResult, Qrc20AbiError, - Qrc20FeeDetails, OUTPUT_QTUM_AMOUNT, QRC20_DUST, QRC20_GAS_LIMIT_DEFAULT, QRC20_GAS_PRICE_DEFAULT}; -use crate::utxo::qtum::{QtumBasedCoin, QtumCoin, QtumDelegationOps, QtumDelegationRequest, QtumStakingInfosDetails}; -use crate::utxo::rpc_clients::UtxoRpcClientEnum; -use crate::utxo::utxo_common::{big_decimal_from_sat_unsigned, UtxoTxBuilder}; -use crate::utxo::{qtum, utxo_common, Address, GetUtxoListOps, UtxoCommonOps}; -use crate::utxo::{PrivKeyPolicyNotAllowed, UTXO_LOCK}; -use crate::{DelegationError, DelegationFut, DelegationResult, MarketCoinOps, StakingInfos, StakingInfosError, - StakingInfosFut, StakingInfosResult, TransactionDetails, TransactionType}; +use std::convert::TryInto; +use std::str::FromStr; + use bitcrypto::dhash256; use common::now_sec; use derive_more::Display; @@ -22,10 +14,20 @@ use mm2_number::bigdecimal::{BigDecimal, Zero}; use rpc::v1::types::ToTxHash; use script::Builder as ScriptBuilder; use serialization::serialize; -use std::convert::TryInto; -use std::str::FromStr; use utxo_signer::with_key_pair::sign_tx; +use crate::qrc20::rpc_clients::Qrc20ElectrumOps; +use crate::qrc20::script_pubkey::generate_contract_call_script_pubkey; +use crate::qrc20::{contract_addr_into_rpc_format, ContractCallOutput, GenerateQrc20TxResult, Qrc20AbiError, + Qrc20FeeDetails, OUTPUT_QTUM_AMOUNT, QRC20_DUST, QRC20_GAS_LIMIT_DEFAULT, QRC20_GAS_PRICE_DEFAULT}; +use crate::utxo::qtum::{QtumBasedCoin, QtumCoin, QtumDelegationOps, QtumDelegationRequest, QtumStakingInfosDetails}; +use crate::utxo::rpc_clients::UtxoRpcClientEnum; +use crate::utxo::utxo_common::{big_decimal_from_sat_unsigned, UtxoTxBuilder}; +use crate::utxo::{qtum, utxo_common, Address, GetUtxoListOps, UtxoCommonOps}; +use crate::utxo::{PrivKeyPolicyNotAllowed, UTXO_LOCK}; +use crate::{DelegationError, DelegationFut, DelegationResult, MarketCoinOps, StakingInfos, StakingInfosError, + StakingInfosFut, StakingInfosResult, TransactionDetails, TransactionType}; + pub const QTUM_DELEGATION_STANDARD_FEE: u64 = 10; pub const QTUM_LOWER_BOUND_DELEGATION_AMOUNT: f64 = 100.0; pub const QRC20_GAS_LIMIT_DELEGATION: u64 = 2_250_000; diff --git a/mm2src/coins/utxo/rpc_clients.rs b/mm2src/coins/utxo/rpc_clients.rs index c4cb848dde..1e2cf79eba 100644 --- a/mm2src/coins/utxo/rpc_clients.rs +++ b/mm2src/coins/utxo/rpc_clients.rs @@ -1,10 +1,18 @@ #![cfg_attr(target_arch = "wasm32", allow(unused_macros))] #![cfg_attr(target_arch = "wasm32", allow(dead_code))] -use crate::utxo::utxo_block_header_storage::BlockHeaderStorage; -use crate::utxo::{output_script, sat_from_big_decimal, GetBlockHeaderError, GetConfirmedTxError, GetTxError, - GetTxHeightError}; -use crate::{big_decimal_from_sat_unsigned, NumConversError, RpcTransportEventHandler, RpcTransportEventHandlerShared}; +use std::collections::hash_map::Entry; +use std::collections::HashMap; +use std::convert::TryInto; +use std::fmt; +use std::io; +use std::net::{SocketAddr, ToSocketAddrs}; +use std::num::NonZeroU64; +use std::ops::Deref; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; +use std::sync::Arc; +use std::time::Duration; + use async_trait::async_trait; use chain::{BlockHeader, BlockHeaderBits, BlockHeaderNonce, OutPoint, Transaction as UtxoTx}; use common::custom_futures::{select_ok_sequential, timeout::FutureTimerExt}; @@ -40,17 +48,11 @@ use serialization::{deserialize, serialize, serialize_with_flags, CoinVariant, C use sha2::{Digest, Sha256}; use spv_validation::helpers_validation::SPVError; use spv_validation::storage::BlockHeaderStorageOps; -use std::collections::hash_map::Entry; -use std::collections::HashMap; -use std::convert::TryInto; -use std::fmt; -use std::io; -use std::net::{SocketAddr, ToSocketAddrs}; -use std::num::NonZeroU64; -use std::ops::Deref; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; -use std::sync::Arc; -use std::time::Duration; + +use crate::utxo::utxo_block_header_storage::BlockHeaderStorage; +use crate::utxo::{output_script, sat_from_big_decimal, GetBlockHeaderError, GetConfirmedTxError, GetTxError, + GetTxHeightError}; +use crate::{big_decimal_from_sat_unsigned, NumConversError, RpcTransportEventHandler, RpcTransportEventHandlerShared}; cfg_native! { use futures::future::Either; diff --git a/mm2src/coins/utxo/slp.rs b/mm2src/coins/utxo/slp.rs index 07379fcbbf..d32a4372f7 100644 --- a/mm2src/coins/utxo/slp.rs +++ b/mm2src/coins/utxo/slp.rs @@ -3,29 +3,10 @@ //! Tracking issue: https://github.com/KomodoPlatform/atomicDEX-API/issues/701 //! More info about the protocol and implementation guides can be found at https://slp.dev/ -use crate::coin_errors::{MyAddressError, ValidatePaymentError, ValidatePaymentFut}; -use crate::my_tx_history_v2::{CoinWithTxHistoryV2, MyTxHistoryErrorV2, MyTxHistoryTarget}; -use crate::tx_history_storage::{GetTxHistoryFilters, WalletId}; -use crate::utxo::bch::BchCoin; -use crate::utxo::bchd_grpc::{check_slp_transaction, validate_slp_utxos, ValidateSlpUtxosErr}; -use crate::utxo::rpc_clients::{UnspentInfo, UtxoRpcClientEnum, UtxoRpcError, UtxoRpcResult}; -use crate::utxo::utxo_common::{self, big_decimal_from_sat_unsigned, payment_script, UtxoTxBuilder}; -use crate::utxo::{generate_and_send_tx, sat_from_big_decimal, ActualTxFee, AdditionalTxData, BroadcastTxErr, - FeePolicy, GenerateTxError, RecentlySpentOutPointsGuard, UtxoCoinConf, UtxoCoinFields, - UtxoCommonOps, UtxoTx, UtxoTxBroadcastOps, UtxoTxGenerationOps}; -use crate::{BalanceFut, CheckIfMyPaymentSentArgs, CoinBalance, CoinFutSpawner, ConfirmPaymentInput, FeeApproxStage, - FoundSwapTxSpend, HistorySyncState, MakerSwapTakerCoin, MarketCoinOps, MmCoin, MmCoinEnum, - NegotiateSwapContractAddrErr, NumConversError, PaymentInstructionArgs, PaymentInstructions, - PaymentInstructionsErr, PrivKeyPolicyNotAllowed, RawTransactionFut, RawTransactionRequest, RefundError, - RefundPaymentArgs, RefundResult, SearchForSwapTxSpendInput, SendMakerPaymentSpendPreimageInput, - SendPaymentArgs, SignatureResult, SpendPaymentArgs, SwapOps, TakerSwapMakerCoin, TradeFee, - TradePreimageError, TradePreimageFut, TradePreimageResult, TradePreimageValue, TransactionDetails, - TransactionEnum, TransactionErr, TransactionFut, TransactionResult, TxFeeDetails, TxMarshalingErr, - UnexpectedDerivationMethod, ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr, - ValidateOtherPubKeyErr, ValidatePaymentInput, VerificationError, VerificationResult, - WaitForHTLCTxSpendArgs, WatcherOps, WatcherReward, WatcherRewardError, WatcherSearchForSwapTxSpendInput, - WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawError, WithdrawFee, WithdrawFut, - WithdrawRequest}; +use std::convert::TryInto; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; +use std::sync::Arc; + use async_trait::async_trait; use bitcrypto::dhash160; use chain::constants::SEQUENCE_FINAL; @@ -51,11 +32,32 @@ use script::{Builder as ScriptBuilder, Opcode, Script, TransactionInputSigner}; use serde_json::Value as Json; use serialization::{deserialize, serialize, Deserializable, Error as SerError, Reader}; use serialization_derive::Deserializable; -use std::convert::TryInto; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; -use std::sync::Arc; use utxo_signer::with_key_pair::{p2pkh_spend, p2sh_spend, sign_tx, UtxoSignWithKeyPairError}; +use crate::coin_errors::{MyAddressError, ValidatePaymentError, ValidatePaymentFut}; +use crate::my_tx_history_v2::{CoinWithTxHistoryV2, MyTxHistoryErrorV2, MyTxHistoryTarget}; +use crate::tx_history_storage::{GetTxHistoryFilters, WalletId}; +use crate::utxo::bch::BchCoin; +use crate::utxo::bchd_grpc::{check_slp_transaction, validate_slp_utxos, ValidateSlpUtxosErr}; +use crate::utxo::rpc_clients::{UnspentInfo, UtxoRpcClientEnum, UtxoRpcError, UtxoRpcResult}; +use crate::utxo::utxo_common::{self, big_decimal_from_sat_unsigned, payment_script, UtxoTxBuilder}; +use crate::utxo::{generate_and_send_tx, sat_from_big_decimal, ActualTxFee, AdditionalTxData, BroadcastTxErr, + FeePolicy, GenerateTxError, RecentlySpentOutPointsGuard, UtxoCoinConf, UtxoCoinFields, + UtxoCommonOps, UtxoTx, UtxoTxBroadcastOps, UtxoTxGenerationOps}; +use crate::{BalanceFut, CheckIfMyPaymentSentArgs, CoinBalance, CoinFutSpawner, ConfirmPaymentInput, FeeApproxStage, + FoundSwapTxSpend, HistorySyncState, MakerSwapTakerCoin, MarketCoinOps, MmCoin, MmCoinEnum, + NegotiateSwapContractAddrErr, NumConversError, PaymentInstructionArgs, PaymentInstructions, + PaymentInstructionsErr, PrivKeyPolicyNotAllowed, RawTransactionFut, RawTransactionRequest, RefundError, + RefundPaymentArgs, RefundResult, SearchForSwapTxSpendInput, SendMakerPaymentSpendPreimageInput, + SendPaymentArgs, SignatureResult, SpendPaymentArgs, SwapOps, TakerSwapMakerCoin, TradeFee, + TradePreimageError, TradePreimageFut, TradePreimageResult, TradePreimageValue, TransactionDetails, + TransactionEnum, TransactionErr, TransactionFut, TransactionResult, TxFeeDetails, TxMarshalingErr, + UnexpectedDerivationMethod, ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr, + ValidateOtherPubKeyErr, ValidatePaymentInput, VerificationError, VerificationResult, + WaitForHTLCTxSpendArgs, WatcherOps, WatcherReward, WatcherRewardError, WatcherSearchForSwapTxSpendInput, + WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawError, WithdrawFee, WithdrawFut, + WithdrawRequest}; + const SLP_SWAP_VOUT: usize = 1; const SLP_FEE_VOUT: usize = 1; const SLP_HTLC_SPEND_SIZE: u64 = 555; @@ -1918,12 +1920,14 @@ pub fn slp_addr_from_pubkey_str(pubkey: &str, prefix: &str) -> Result, @@ -47,9 +47,10 @@ impl BlockHeaderStorage { #[cfg(all(test, not(target_arch = "wasm32")))] pub(crate) fn new_from_ctx(ctx: MmArc, ticker: String) -> Result { - use db_common::sqlite::rusqlite::Connection; use std::sync::{Arc, Mutex}; + use db_common::sqlite::rusqlite::Connection; + let conn = Arc::new(Mutex::new(Connection::open_in_memory().unwrap())); let conn = ctx.sqlite_connection.clone_or(conn); @@ -114,10 +115,11 @@ impl BlockHeaderStorageOps for BlockHeaderStorage { #[cfg(any(test, target_arch = "wasm32"))] mod block_headers_storage_tests { - use super::*; use chain::BlockHeaderBits; use mm2_test_helpers::for_tests::mm_ctx_with_custom_db; + use super::*; + cfg_wasm32! { use wasm_bindgen_test::*; use spv_validation::work::MAX_BITS_BTC; @@ -279,11 +281,12 @@ mod block_headers_storage_tests { #[cfg(all(test, not(target_arch = "wasm32")))] mod native_tests { - use super::*; - use crate::utxo::utxo_block_header_storage::block_headers_storage_tests::*; use common::block_on; use mm2_test_helpers::for_tests::mm_ctx_with_custom_db; + use super::*; + use crate::utxo::utxo_block_header_storage::block_headers_storage_tests::*; + #[test] fn test_init_collection() { let for_coin = "init_collection"; @@ -325,12 +328,13 @@ mod native_tests { #[cfg(target_arch = "wasm32")] mod wasm_test { - use super::*; - use crate::utxo::utxo_block_header_storage::block_headers_storage_tests::*; use common::log::wasm_log::register_wasm_log; use mm2_test_helpers::for_tests::mm_ctx_with_custom_db; use wasm_bindgen_test::*; + use super::*; + use crate::utxo::utxo_block_header_storage::block_headers_storage_tests::*; + wasm_bindgen_test_configure!(run_in_browser); const FOR_COIN: &str = "tBTC"; diff --git a/mm2src/coins/utxo/utxo_block_header_storage/sql_block_header_storage.rs b/mm2src/coins/utxo/utxo_block_header_storage/sql_block_header_storage.rs index 183c3abea1..2c80553de5 100644 --- a/mm2src/coins/utxo/utxo_block_header_storage/sql_block_header_storage.rs +++ b/mm2src/coins/utxo/utxo_block_header_storage/sql_block_header_storage.rs @@ -1,3 +1,8 @@ +use std::collections::HashMap; +use std::convert::TryInto; +use std::num::TryFromIntError; +use std::sync::{Arc, Mutex}; + use async_trait::async_trait; use chain::BlockHeader; use common::async_blocking; @@ -9,10 +14,6 @@ use db_common::{sqlite::rusqlite::Error as SqlError, use primitives::hash::H256; use serialization::Reader; use spv_validation::storage::{BlockHeaderStorageError, BlockHeaderStorageOps}; -use std::collections::HashMap; -use std::convert::TryInto; -use std::num::TryFromIntError; -use std::sync::{Arc, Mutex}; pub(crate) fn block_headers_cache_table(ticker: &str) -> String { ticker.to_owned() + "_block_headers_cache" } diff --git a/mm2src/coins/utxo/utxo_block_header_storage/wasm/indexeddb_block_header_storage.rs b/mm2src/coins/utxo/utxo_block_header_storage/wasm/indexeddb_block_header_storage.rs index 13abdd4ed5..2fc299fe85 100644 --- a/mm2src/coins/utxo/utxo_block_header_storage/wasm/indexeddb_block_header_storage.rs +++ b/mm2src/coins/utxo/utxo_block_header_storage/wasm/indexeddb_block_header_storage.rs @@ -1,4 +1,4 @@ -use super::BlockHeaderStorageTable; +use std::collections::HashMap; use async_trait::async_trait; use chain::BlockHeader; @@ -10,7 +10,8 @@ use num_traits::ToPrimitive; use primitives::hash::H256; use serialization::Reader; use spv_validation::storage::{BlockHeaderStorageError, BlockHeaderStorageOps}; -use std::collections::HashMap; + +use super::BlockHeaderStorageTable; const DB_NAME: &str = "block_headers_cache"; const DB_VERSION: u32 = 1; diff --git a/mm2src/coins/utxo/utxo_builder/mod.rs b/mm2src/coins/utxo/utxo_builder/mod.rs index 205c36ee71..610624064d 100644 --- a/mm2src/coins/utxo/utxo_builder/mod.rs +++ b/mm2src/coins/utxo/utxo_builder/mod.rs @@ -2,11 +2,10 @@ mod utxo_arc_builder; mod utxo_coin_builder; mod utxo_conf_builder; +#[cfg(test)] +pub(crate) use utxo_arc_builder::{block_header_utxo_loop, BlockHeaderUtxoLoopExtraArgs}; pub use utxo_arc_builder::{MergeUtxoArcOps, UtxoArcBuilder}; pub use utxo_coin_builder::{UtxoCoinBuildError, UtxoCoinBuildResult, UtxoCoinBuilder, UtxoCoinBuilderCommonOps, UtxoFieldsWithGlobalHDBuilder, UtxoFieldsWithHardwareWalletBuilder, UtxoFieldsWithIguanaSecretBuilder, DAY_IN_SECONDS}; pub use utxo_conf_builder::{UtxoConfBuilder, UtxoConfError, UtxoConfResult}; - -#[cfg(test)] -pub(crate) use utxo_arc_builder::{block_header_utxo_loop, BlockHeaderUtxoLoopExtraArgs}; diff --git a/mm2src/coins/utxo/utxo_builder/utxo_arc_builder.rs b/mm2src/coins/utxo/utxo_builder/utxo_arc_builder.rs index b97c1aa94e..5536d0d378 100644 --- a/mm2src/coins/utxo/utxo_builder/utxo_arc_builder.rs +++ b/mm2src/coins/utxo/utxo_builder/utxo_arc_builder.rs @@ -1,11 +1,7 @@ -use crate::utxo::rpc_clients::{ElectrumClient, ElectrumClientImpl, UtxoJsonRpcClientInfo, UtxoRpcClientEnum}; -use crate::utxo::utxo_block_header_storage::BlockHeaderStorage; -use crate::utxo::utxo_builder::{UtxoCoinBuildError, UtxoCoinBuilder, UtxoCoinBuilderCommonOps, - UtxoFieldsWithGlobalHDBuilder, UtxoFieldsWithHardwareWalletBuilder, - UtxoFieldsWithIguanaSecretBuilder}; -use crate::utxo::{generate_and_send_tx, FeePolicy, GetUtxoListOps, UtxoArc, UtxoCommonOps, UtxoSyncStatusLoopHandle, - UtxoWeak}; -use crate::{DerivationMethod, PrivKeyBuildPolicy, UtxoActivationParams}; +use std::collections::HashMap; +use std::num::NonZeroU64; +use std::sync::{Arc, Weak}; + use async_trait::async_trait; use chain::{BlockHeader, TransactionOutput}; use common::executor::{AbortSettings, SpawnAbortable, Timer}; @@ -21,9 +17,15 @@ use serialization::Reader; use spv_validation::conf::SPVConf; use spv_validation::helpers_validation::{validate_headers, SPVError}; use spv_validation::storage::{BlockHeaderStorageError, BlockHeaderStorageOps}; -use std::collections::HashMap; -use std::num::NonZeroU64; -use std::sync::{Arc, Weak}; + +use crate::utxo::rpc_clients::{ElectrumClient, ElectrumClientImpl, UtxoJsonRpcClientInfo, UtxoRpcClientEnum}; +use crate::utxo::utxo_block_header_storage::BlockHeaderStorage; +use crate::utxo::utxo_builder::{UtxoCoinBuildError, UtxoCoinBuilder, UtxoCoinBuilderCommonOps, + UtxoFieldsWithGlobalHDBuilder, UtxoFieldsWithHardwareWalletBuilder, + UtxoFieldsWithIguanaSecretBuilder}; +use crate::utxo::{generate_and_send_tx, FeePolicy, GetUtxoListOps, UtxoArc, UtxoCommonOps, UtxoSyncStatusLoopHandle, + UtxoWeak}; +use crate::{DerivationMethod, PrivKeyBuildPolicy, UtxoActivationParams}; const CHUNK_SIZE_REDUCER_VALUE: u64 = 100; const TRY_TO_RETRIEVE_HEADERS_ATTEMPTS: u8 = 10; diff --git a/mm2src/coins/utxo/utxo_builder/utxo_coin_builder.rs b/mm2src/coins/utxo/utxo_builder/utxo_coin_builder.rs index 16f778d5ff..fa18e5f6cb 100644 --- a/mm2src/coins/utxo/utxo_builder/utxo_coin_builder.rs +++ b/mm2src/coins/utxo/utxo_builder/utxo_coin_builder.rs @@ -1,15 +1,5 @@ -use crate::hd_wallet::{HDAccountsMap, HDAccountsMutex}; -use crate::hd_wallet_storage::{HDWalletCoinStorage, HDWalletStorageError}; -use crate::utxo::rpc_clients::{ElectrumClient, ElectrumClientImpl, ElectrumRpcRequest, EstimateFeeMethod, - UtxoRpcClientEnum}; -use crate::utxo::tx_cache::{UtxoVerboseCacheOps, UtxoVerboseCacheShared}; -use crate::utxo::utxo_block_header_storage::BlockHeaderStorage; -use crate::utxo::utxo_builder::utxo_conf_builder::{UtxoConfBuilder, UtxoConfError}; -use crate::utxo::{output_script, utxo_common, ElectrumBuilderArgs, ElectrumProtoVerifier, ElectrumProtoVerifierEvent, - RecentlySpentOutPoints, TxFee, UtxoCoinConf, UtxoCoinFields, UtxoHDAccount, UtxoHDWallet, - UtxoRpcMode, UtxoSyncStatus, UtxoSyncStatusLoopHandle, DEFAULT_GAP_LIMIT, UTXO_DUST_AMOUNT}; -use crate::{BlockchainNetwork, CoinTransportMetrics, DerivationMethod, HistorySyncState, IguanaPrivKey, - PrivKeyBuildPolicy, PrivKeyPolicy, PrivKeyPolicyNotAllowed, RpcClientType, UtxoActivationParams}; +use std::sync::{Arc, Mutex, Weak}; + use async_trait::async_trait; use chain::TxHashAlgo; use common::custom_futures::repeatable::{Ready, Retry}; @@ -35,7 +25,19 @@ use serde_json::{self as json, Value as Json}; use spv_validation::conf::SPVConf; use spv_validation::helpers_validation::SPVError; use spv_validation::storage::{BlockHeaderStorageError, BlockHeaderStorageOps}; -use std::sync::{Arc, Mutex, Weak}; + +use crate::hd_wallet::{HDAccountsMap, HDAccountsMutex}; +use crate::hd_wallet_storage::{HDWalletCoinStorage, HDWalletStorageError}; +use crate::utxo::rpc_clients::{ElectrumClient, ElectrumClientImpl, ElectrumRpcRequest, EstimateFeeMethod, + UtxoRpcClientEnum}; +use crate::utxo::tx_cache::{UtxoVerboseCacheOps, UtxoVerboseCacheShared}; +use crate::utxo::utxo_block_header_storage::BlockHeaderStorage; +use crate::utxo::utxo_builder::utxo_conf_builder::{UtxoConfBuilder, UtxoConfError}; +use crate::utxo::{output_script, utxo_common, ElectrumBuilderArgs, ElectrumProtoVerifier, ElectrumProtoVerifierEvent, + RecentlySpentOutPoints, TxFee, UtxoCoinConf, UtxoCoinFields, UtxoHDAccount, UtxoHDWallet, + UtxoRpcMode, UtxoSyncStatus, UtxoSyncStatusLoopHandle, DEFAULT_GAP_LIMIT, UTXO_DUST_AMOUNT}; +use crate::{BlockchainNetwork, CoinTransportMetrics, DerivationMethod, HistorySyncState, IguanaPrivKey, + PrivKeyBuildPolicy, PrivKeyPolicy, PrivKeyPolicyNotAllowed, RpcClientType, UtxoActivationParams}; cfg_native! { use crate::utxo::coin_daemon_data_dir; diff --git a/mm2src/coins/utxo/utxo_builder/utxo_conf_builder.rs b/mm2src/coins/utxo/utxo_builder/utxo_conf_builder.rs index a950b67cb4..71a1d8732d 100644 --- a/mm2src/coins/utxo/utxo_builder/utxo_conf_builder.rs +++ b/mm2src/coins/utxo/utxo_builder/utxo_conf_builder.rs @@ -1,7 +1,6 @@ -use crate::utxo::rpc_clients::EstimateFeeMode; -use crate::utxo::{parse_hex_encoded_u32, UtxoCoinConf, DEFAULT_DYNAMIC_FEE_VOLATILITY_PERCENT, KMD_MTP_BLOCK_COUNT, - MATURE_CONFIRMATIONS_DEFAULT}; -use crate::UtxoActivationParams; +use std::num::NonZeroU64; +use std::sync::atomic::AtomicBool; + use bitcrypto::ChecksumType; use crypto::{Bip32Error, StandardHDPathToCoin}; use derive_more::Display; @@ -11,8 +10,11 @@ use mm2_err_handle::prelude::*; use script::SignatureVersion; use serde_json::{self as json, Value as Json}; use spv_validation::conf::SPVConf; -use std::num::NonZeroU64; -use std::sync::atomic::AtomicBool; + +use crate::utxo::rpc_clients::EstimateFeeMode; +use crate::utxo::{parse_hex_encoded_u32, UtxoCoinConf, DEFAULT_DYNAMIC_FEE_VOLATILITY_PERCENT, KMD_MTP_BLOCK_COUNT, + MATURE_CONFIRMATIONS_DEFAULT}; +use crate::UtxoActivationParams; pub type UtxoConfResult = Result>; diff --git a/mm2src/coins/utxo/utxo_common.rs b/mm2src/coins/utxo/utxo_common.rs index 4f5970afc2..728cf906a0 100644 --- a/mm2src/coins/utxo/utxo_common.rs +++ b/mm2src/coins/utxo/utxo_common.rs @@ -1,36 +1,12 @@ -use super::*; -use crate::coin_balance::{AddressBalanceStatus, HDAddressBalance, HDWalletBalanceOps}; -use crate::coin_errors::{MyAddressError, ValidatePaymentError}; -use crate::eth::EthCoinType; -use crate::hd_confirm_address::HDConfirmAddress; -use crate::hd_pubkey::{ExtractExtendedPubkey, HDExtractPubkeyError, HDXPubExtractor}; -use crate::hd_wallet::{AccountUpdatingError, AddressDerivingResult, HDAccountMut, HDAccountsMap, - NewAccountCreatingError, NewAddressDeriveConfirmError, NewAddressDerivingError}; -use crate::hd_wallet_storage::{HDWalletCoinWithStorageOps, HDWalletStorageResult}; -use crate::lp_price::get_base_price_in_rel; -use crate::rpc_command::init_withdraw::WithdrawTaskHandle; -use crate::utxo::rpc_clients::{electrum_script_hash, BlockHashOrHeight, UnspentInfo, UnspentMap, UtxoRpcClientEnum, - UtxoRpcClientOps, UtxoRpcResult}; -use crate::utxo::spv::SimplePaymentVerification; -use crate::utxo::tx_cache::TxCacheResult; -use crate::utxo::utxo_withdraw::{InitUtxoWithdraw, StandardUtxoWithdraw, UtxoWithdraw}; -use crate::watcher_common::validate_watcher_reward; -use crate::{CanRefundHtlc, CoinBalance, CoinWithDerivationMethod, ConfirmPaymentInput, GenTakerPaymentSpendArgs, - GenTakerPaymentSpendResult, GetWithdrawSenderAddress, HDAccountAddressId, RawTransactionError, - RawTransactionRequest, RawTransactionRes, RefundPaymentArgs, RewardTarget, SearchForSwapTxSpendInput, - SendCombinedTakerPaymentArgs, SendMakerPaymentSpendPreimageInput, SendPaymentArgs, SignatureError, - SignatureResult, SpendPaymentArgs, SwapOps, TradePreimageValue, TransactionFut, TransactionResult, - TxFeeDetails, TxGenError, TxMarshalingErr, TxPreimageWithSig, ValidateAddressResult, - ValidateOtherPubKeyErr, ValidatePaymentFut, ValidatePaymentInput, ValidateTakerPaymentArgs, - ValidateTakerPaymentError, ValidateTakerPaymentResult, ValidateTakerPaymentSpendPreimageError, - ValidateTakerPaymentSpendPreimageResult, VerificationError, VerificationResult, - WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawFrom, - WithdrawResult, WithdrawSenderAddress, EARLY_CONFIRMATION_ERR_LOG, INVALID_RECEIVER_ERR_LOG, - INVALID_REFUND_TX_ERR_LOG, INVALID_SCRIPT_ERR_LOG, INVALID_SENDER_ERR_LOG, OLD_TRANSACTION_ERR_LOG}; -use crate::{MmCoinEnum, WatcherReward, WatcherRewardError}; +use std::cmp::Ordering; +use std::collections::hash_map::{Entry, HashMap}; +use std::str::FromStr; +use std::sync::atomic::Ordering as AtomicOrdering; + pub use bitcrypto::{dhash160, sha256, ChecksumType}; use bitcrypto::{dhash256, ripemd160}; use chain::constants::SEQUENCE_FINAL; +pub use chain::Transaction as UtxoTx; use chain::{OutPoint, TransactionOutput}; use common::executor::Timer; use common::jsonrpc_client::JsonRpcErrorType; @@ -54,15 +30,40 @@ use secp256k1::{PublicKey, Signature}; use serde_json::{self as json}; use serialization::{deserialize, serialize, serialize_with_flags, CoinVariant, CompactInteger, Serializable, Stream, SERIALIZE_TRANSACTION_WITNESS}; -use std::cmp::Ordering; -use std::collections::hash_map::{Entry, HashMap}; -use std::str::FromStr; -use std::sync::atomic::Ordering as AtomicOrdering; use utxo_signer::with_key_pair::{calc_and_sign_sighash, p2sh_spend, signature_hash_to_sign, SIGHASH_ALL, SIGHASH_SINGLE}; use utxo_signer::UtxoSignerOps; -pub use chain::Transaction as UtxoTx; +use super::*; +use crate::coin_balance::{AddressBalanceStatus, HDAddressBalance, HDWalletBalanceOps}; +use crate::coin_errors::{MyAddressError, ValidatePaymentError}; +use crate::eth::EthCoinType; +use crate::hd_confirm_address::HDConfirmAddress; +use crate::hd_pubkey::{ExtractExtendedPubkey, HDExtractPubkeyError, HDXPubExtractor}; +use crate::hd_wallet::{AccountUpdatingError, AddressDerivingResult, HDAccountMut, HDAccountsMap, + NewAccountCreatingError, NewAddressDeriveConfirmError, NewAddressDerivingError}; +use crate::hd_wallet_storage::{HDWalletCoinWithStorageOps, HDWalletStorageResult}; +use crate::lp_price::get_base_price_in_rel; +use crate::rpc_command::init_withdraw::WithdrawTaskHandle; +use crate::utxo::rpc_clients::{electrum_script_hash, BlockHashOrHeight, UnspentInfo, UnspentMap, UtxoRpcClientEnum, + UtxoRpcClientOps, UtxoRpcResult}; +use crate::utxo::spv::SimplePaymentVerification; +use crate::utxo::tx_cache::TxCacheResult; +use crate::utxo::utxo_withdraw::{InitUtxoWithdraw, StandardUtxoWithdraw, UtxoWithdraw}; +use crate::watcher_common::validate_watcher_reward; +use crate::{CanRefundHtlc, CoinBalance, CoinWithDerivationMethod, ConfirmPaymentInput, GenTakerPaymentSpendArgs, + GenTakerPaymentSpendResult, GetWithdrawSenderAddress, HDAccountAddressId, RawTransactionError, + RawTransactionRequest, RawTransactionRes, RefundPaymentArgs, RewardTarget, SearchForSwapTxSpendInput, + SendCombinedTakerPaymentArgs, SendMakerPaymentSpendPreimageInput, SendPaymentArgs, SignatureError, + SignatureResult, SpendPaymentArgs, SwapOps, TradePreimageValue, TransactionFut, TransactionResult, + TxFeeDetails, TxGenError, TxMarshalingErr, TxPreimageWithSig, ValidateAddressResult, + ValidateOtherPubKeyErr, ValidatePaymentFut, ValidatePaymentInput, ValidateTakerPaymentArgs, + ValidateTakerPaymentError, ValidateTakerPaymentResult, ValidateTakerPaymentSpendPreimageError, + ValidateTakerPaymentSpendPreimageResult, VerificationError, VerificationResult, + WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawFrom, + WithdrawResult, WithdrawSenderAddress, EARLY_CONFIRMATION_ERR_LOG, INVALID_RECEIVER_ERR_LOG, + INVALID_REFUND_TX_ERR_LOG, INVALID_SCRIPT_ERR_LOG, INVALID_SENDER_ERR_LOG, OLD_TRANSACTION_ERR_LOG}; +use crate::{MmCoinEnum, WatcherReward, WatcherRewardError}; pub mod utxo_tx_history_v2_common; diff --git a/mm2src/coins/utxo/utxo_common/utxo_tx_history_v2_common.rs b/mm2src/coins/utxo/utxo_common/utxo_tx_history_v2_common.rs index 97a637a68c..54dcf4a5d9 100644 --- a/mm2src/coins/utxo/utxo_common/utxo_tx_history_v2_common.rs +++ b/mm2src/coins/utxo/utxo_common/utxo_tx_history_v2_common.rs @@ -1,3 +1,19 @@ +use std::collections::{HashMap, HashSet}; +use std::convert::{TryFrom, TryInto}; +use std::iter; +use std::num::TryFromIntError; + +use common::jsonrpc_client::JsonRpcErrorType; +use crypto::Bip44Chain; +use futures::compat::Future01CompatExt; +use itertools::Itertools; +use keys::{Address, Type as ScriptType}; +use mm2_err_handle::prelude::*; +use mm2_metrics::MetricsArc; +use mm2_number::BigDecimal; +use rpc::v1::types::{TransactionInputEnum, H256 as H256Json}; +use serialization::deserialize; + use crate::coin_balance::CoinBalanceReportOps; use crate::hd_wallet::{HDAccountOps, HDWalletCoinOps, HDWalletOps}; use crate::my_tx_history_v2::{CoinWithTxHistoryV2, DisplayAddress, MyTxHistoryErrorV2, MyTxHistoryTarget, @@ -11,20 +27,6 @@ use crate::utxo::{output_script, RequestTxHistoryResult, UtxoCoinFields, UtxoCom use crate::{big_decimal_from_sat_unsigned, compare_transactions, BalanceResult, CoinWithDerivationMethod, DerivationMethod, HDAccountAddressId, MarketCoinOps, NumConversError, TransactionDetails, TxFeeDetails, TxIdHeight, UtxoFeeDetails, UtxoTx}; -use common::jsonrpc_client::JsonRpcErrorType; -use crypto::Bip44Chain; -use futures::compat::Future01CompatExt; -use itertools::Itertools; -use keys::{Address, Type as ScriptType}; -use mm2_err_handle::prelude::*; -use mm2_metrics::MetricsArc; -use mm2_number::BigDecimal; -use rpc::v1::types::{TransactionInputEnum, H256 as H256Json}; -use serialization::deserialize; -use std::collections::{HashMap, HashSet}; -use std::convert::{TryFrom, TryInto}; -use std::iter; -use std::num::TryFromIntError; /// [`CoinWithTxHistoryV2::history_wallet_id`] implementation. pub fn history_wallet_id(coin: &UtxoCoinFields) -> WalletId { WalletId::new(coin.conf.ticker.clone()) } diff --git a/mm2src/coins/utxo/utxo_common_tests.rs b/mm2src/coins/utxo/utxo_common_tests.rs index 246cadcbdb..73b01fa5f9 100644 --- a/mm2src/coins/utxo/utxo_common_tests.rs +++ b/mm2src/coins/utxo/utxo_common_tests.rs @@ -1,3 +1,15 @@ +use std::convert::TryFrom; +use std::num::NonZeroUsize; +use std::time::Duration; + +use common::custom_futures::repeatable::{Ready, Retry}; +use common::executor::{spawn, Timer}; +use common::jsonrpc_client::JsonRpcErrorType; +use common::PagingOptionsEnum; +use crypto::privkey::key_pair_from_seed; +use itertools::Itertools; +use mm2_test_helpers::for_tests::mm_ctx_with_custom_db; + use super::*; use crate::hd_wallet::HDAccountsMap; use crate::my_tx_history_v2::{my_tx_history_v2_impl, CoinWithTxHistoryV2, MyTxHistoryDetails, MyTxHistoryRequestV2, @@ -8,16 +20,6 @@ use crate::utxo::tx_cache::dummy_tx_cache::DummyVerboseCache; use crate::utxo::tx_cache::UtxoVerboseCacheOps; use crate::utxo::utxo_tx_history_v2::{utxo_history_loop, UtxoTxHistoryOps}; use crate::{compare_transaction_details, UtxoStandardCoin}; -use common::custom_futures::repeatable::{Ready, Retry}; -use common::executor::{spawn, Timer}; -use common::jsonrpc_client::JsonRpcErrorType; -use common::PagingOptionsEnum; -use crypto::privkey::key_pair_from_seed; -use itertools::Itertools; -use mm2_test_helpers::for_tests::mm_ctx_with_custom_db; -use std::convert::TryFrom; -use std::num::NonZeroUsize; -use std::time::Duration; pub(super) const TEST_COIN_NAME: &str = "RICK"; // Made-up hrp for rick to test p2wpkh script diff --git a/mm2src/coins/utxo/utxo_standard.rs b/mm2src/coins/utxo/utxo_standard.rs index 47582f8524..fb4b89fa92 100644 --- a/mm2src/coins/utxo/utxo_standard.rs +++ b/mm2src/coins/utxo/utxo_standard.rs @@ -1,3 +1,10 @@ +use common::executor::{AbortableSystem, AbortedError}; +use crypto::Bip44Chain; +use futures::{FutureExt, TryFutureExt}; +use mm2_metrics::MetricsArc; +use mm2_number::MmNumber; +use utxo_signer::UtxoSignerOps; + use super::*; use crate::coin_balance::{self, EnableCoinBalanceError, EnabledCoinBalanceParams, HDAccountBalance, HDAddressBalance, HDWalletBalance, HDWalletBalanceOps}; @@ -34,12 +41,6 @@ use crate::{CanRefundHtlc, CheckIfMyPaymentSentArgs, CoinBalance, CoinWithDeriva ValidateTakerPaymentResult, ValidateTakerPaymentSpendPreimageResult, VerificationResult, WaitForHTLCTxSpendArgs, WatcherOps, WatcherReward, WatcherRewardError, WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawFut, WithdrawSenderAddress}; -use common::executor::{AbortableSystem, AbortedError}; -use crypto::Bip44Chain; -use futures::{FutureExt, TryFutureExt}; -use mm2_metrics::MetricsArc; -use mm2_number::MmNumber; -use utxo_signer::UtxoSignerOps; #[derive(Clone)] pub struct UtxoStandardCoin { diff --git a/mm2src/coins/utxo/utxo_tests.rs b/mm2src/coins/utxo/utxo_tests.rs index 0e1d56dddc..14ef107bb1 100644 --- a/mm2src/coins/utxo/utxo_tests.rs +++ b/mm2src/coins/utxo/utxo_tests.rs @@ -1,3 +1,27 @@ +#[cfg(not(target_arch = "wasm32"))] use std::convert::TryFrom; +use std::iter; +use std::mem::discriminant; +use std::num::NonZeroUsize; + +use chain::{BlockHeader, BlockHeaderBits, OutPoint}; +use common::executor::Timer; +use common::{block_on, wait_until_sec, OrdRange, PagingOptionsEnum, DEX_FEE_ADDR_RAW_PUBKEY}; +use crypto::{privkey::key_pair_from_seed, Bip44Chain, RpcDerivationPath, Secp256k1Secret}; +#[cfg(not(target_arch = "wasm32"))] +use db_common::sqlite::rusqlite::Connection; +use futures::channel::mpsc::channel; +use futures::future::join_all; +use futures::TryFutureExt; +use mm2_core::mm_ctx::MmCtxBuilder; +use mm2_number::bigdecimal::{BigDecimal, Signed}; +use mm2_test_helpers::for_tests::{mm_ctx_with_custom_db, DOC_ELECTRUM_ADDRS, MORTY_ELECTRUM_ADDRS, RICK_ELECTRUM_ADDRS}; +use mocktopus::mocking::*; +use rpc::v1::types::H256 as H256Json; +use serialization::{deserialize, CoinVariant}; +use spv_validation::conf::{BlockHeaderValidationParams, SPVBlockHeader}; +use spv_validation::storage::BlockHeaderStorageOps; +use spv_validation::work::DifficultyAlgorithm; + use super::*; use crate::coin_balance::HDAddressBalance; use crate::coin_errors::ValidatePaymentError; @@ -31,28 +55,6 @@ use crate::utxo::utxo_tx_history_v2::{UtxoTxDetailsParams, UtxoTxHistoryOps}; use crate::{BlockHeightAndTime, CoinBalance, ConfirmPaymentInput, IguanaPrivKey, PrivKeyBuildPolicy, SearchForSwapTxSpendInput, SpendPaymentArgs, StakingInfosDetails, SwapOps, TradePreimageValue, TxFeeDetails, TxMarshalingErr, ValidateFeeArgs, WaitForHTLCTxSpendArgs, INVALID_SENDER_ERR_LOG}; -use chain::{BlockHeader, BlockHeaderBits, OutPoint}; -use common::executor::Timer; -use common::{block_on, wait_until_sec, OrdRange, PagingOptionsEnum, DEX_FEE_ADDR_RAW_PUBKEY}; -use crypto::{privkey::key_pair_from_seed, Bip44Chain, RpcDerivationPath, Secp256k1Secret}; -#[cfg(not(target_arch = "wasm32"))] -use db_common::sqlite::rusqlite::Connection; -use futures::channel::mpsc::channel; -use futures::future::join_all; -use futures::TryFutureExt; -use mm2_core::mm_ctx::MmCtxBuilder; -use mm2_number::bigdecimal::{BigDecimal, Signed}; -use mm2_test_helpers::for_tests::{mm_ctx_with_custom_db, DOC_ELECTRUM_ADDRS, MORTY_ELECTRUM_ADDRS, RICK_ELECTRUM_ADDRS}; -use mocktopus::mocking::*; -use rpc::v1::types::H256 as H256Json; -use serialization::{deserialize, CoinVariant}; -use spv_validation::conf::{BlockHeaderValidationParams, SPVBlockHeader}; -use spv_validation::storage::BlockHeaderStorageOps; -use spv_validation::work::DifficultyAlgorithm; -#[cfg(not(target_arch = "wasm32"))] use std::convert::TryFrom; -use std::iter; -use std::mem::discriminant; -use std::num::NonZeroUsize; #[cfg(not(target_arch = "wasm32"))] const TAKER_PAYMENT_SPEND_SEARCH_INTERVAL: f64 = 1.; @@ -2431,9 +2433,10 @@ fn test_find_output_spend_skips_conflicting_transactions() { #[test] #[cfg(not(target_arch = "wasm32"))] fn test_qtum_is_unspent_mature() { - use crate::utxo::qtum::QtumBasedCoin; use rpc::v1::types::{ScriptType, SignedTransactionOutput, TransactionOutputScript}; + use crate::utxo::qtum::QtumBasedCoin; + let mut coin_fields = utxo_coin_fields_for_test(UtxoRpcClientEnum::Native(native_client_for_test()), None, false); // Qtum's mature confirmations is 500 blocks coin_fields.conf.mature_confirmations = 500; @@ -4341,10 +4344,11 @@ fn test_utxo_validate_valid_and_invalid_pubkey() { #[test] fn test_block_header_utxo_loop() { - use crate::utxo::utxo_builder::{block_header_utxo_loop, BlockHeaderUtxoLoopExtraArgs}; use futures::future::{Either, FutureExt}; use keys::hash::H256 as H256Json; + use crate::utxo::utxo_builder::{block_header_utxo_loop, BlockHeaderUtxoLoopExtraArgs}; + static mut CURRENT_BLOCK_COUNT: u64 = 13; ElectrumClient::get_servers_with_latest_block_count.mock_safe(move |_| { @@ -4528,10 +4532,11 @@ fn rick_blocker_5() -> BlockHeader { #[test] fn test_block_header_utxo_loop_with_reorg() { - use crate::utxo::utxo_builder::{block_header_utxo_loop, BlockHeaderUtxoLoopExtraArgs}; use futures::future::{Either, FutureExt}; use keys::hash::H256 as H256Json; + use crate::utxo::utxo_builder::{block_header_utxo_loop, BlockHeaderUtxoLoopExtraArgs}; + static mut CURRENT_BLOCK_COUNT: u64 = 3; static mut IS_MISMATCH_HEADER: bool = true; let rick_headers = include_str!("../for_tests/RICK_HEADERS.json"); diff --git a/mm2src/coins/utxo/utxo_tx_history_v2.rs b/mm2src/coins/utxo/utxo_tx_history_v2.rs index 29861a23dc..e77b2fc130 100644 --- a/mm2src/coins/utxo/utxo_tx_history_v2.rs +++ b/mm2src/coins/utxo/utxo_tx_history_v2.rs @@ -1,12 +1,8 @@ -use super::RequestTxHistoryResult; -use crate::hd_wallet::AddressDerivingError; -use crate::my_tx_history_v2::{CoinWithTxHistoryV2, DisplayAddress, TxHistoryStorage, TxHistoryStorageError}; -use crate::tx_history_storage::FilteringAddresses; -use crate::utxo::bch::BchCoin; -use crate::utxo::slp::ParseSlpScriptError; -use crate::utxo::{utxo_common, AddrFromStrError, GetBlockHeaderError}; -use crate::{BalanceError, BalanceResult, BlockHeightAndTime, HistorySyncState, MarketCoinOps, NumConversError, - ParseBigDecimalError, TransactionDetails, UnexpectedDerivationMethod, UtxoRpcError, UtxoTx}; +use std::collections::{hash_map::Entry, HashMap, HashSet}; +use std::convert::Infallible; +use std::iter::FromIterator; +use std::str::FromStr; + use async_trait::async_trait; use common::executor::Timer; use common::log::{error, info}; @@ -18,10 +14,16 @@ use mm2_number::BigDecimal; use mm2_state_machine::prelude::*; use mm2_state_machine::state_machine::StateMachineTrait; use rpc::v1::types::H256 as H256Json; -use std::collections::{hash_map::Entry, HashMap, HashSet}; -use std::convert::Infallible; -use std::iter::FromIterator; -use std::str::FromStr; + +use super::RequestTxHistoryResult; +use crate::hd_wallet::AddressDerivingError; +use crate::my_tx_history_v2::{CoinWithTxHistoryV2, DisplayAddress, TxHistoryStorage, TxHistoryStorageError}; +use crate::tx_history_storage::FilteringAddresses; +use crate::utxo::bch::BchCoin; +use crate::utxo::slp::ParseSlpScriptError; +use crate::utxo::{utxo_common, AddrFromStrError, GetBlockHeaderError}; +use crate::{BalanceError, BalanceResult, BlockHeightAndTime, HistorySyncState, MarketCoinOps, NumConversError, + ParseBigDecimalError, TransactionDetails, UnexpectedDerivationMethod, UtxoRpcError, UtxoTx}; macro_rules! try_or_stop_unknown { ($exp:expr, $fmt:literal) => { diff --git a/mm2src/coins/utxo/utxo_wasm_tests.rs b/mm2src/coins/utxo/utxo_wasm_tests.rs index 65bd2fe20a..038e6af21a 100644 --- a/mm2src/coins/utxo/utxo_wasm_tests.rs +++ b/mm2src/coins/utxo/utxo_wasm_tests.rs @@ -1,12 +1,13 @@ +use mm2_core::mm_ctx::MmCtxBuilder; +use serialization::deserialize; +use wasm_bindgen_test::*; + use super::rpc_clients::{ElectrumClient, UtxoRpcClientOps}; use super::utxo_builder::{UtxoArcBuilder, UtxoCoinBuilderCommonOps}; use super::utxo_standard::UtxoStandardCoin; use super::*; use crate::utxo::utxo_common_tests; use crate::{IguanaPrivKey, PrivKeyBuildPolicy}; -use mm2_core::mm_ctx::MmCtxBuilder; -use serialization::deserialize; -use wasm_bindgen_test::*; wasm_bindgen_test_configure!(run_in_browser); diff --git a/mm2src/coins/utxo/utxo_withdraw.rs b/mm2src/coins/utxo/utxo_withdraw.rs index f51726c6c4..3290004f19 100644 --- a/mm2src/coins/utxo/utxo_withdraw.rs +++ b/mm2src/coins/utxo/utxo_withdraw.rs @@ -1,9 +1,5 @@ -use crate::rpc_command::init_withdraw::{WithdrawInProgressStatus, WithdrawTaskHandle}; -use crate::utxo::utxo_common::{big_decimal_from_sat, UtxoTxBuilder}; -use crate::utxo::{output_script, sat_from_big_decimal, ActualTxFee, Address, FeePolicy, GetUtxoListOps, PrivKeyPolicy, - UtxoAddressFormat, UtxoCoinFields, UtxoCommonOps, UtxoFeeDetails, UtxoTx, UTXO_LOCK}; -use crate::{CoinWithDerivationMethod, GetWithdrawSenderAddress, MarketCoinOps, TransactionDetails, WithdrawError, - WithdrawFee, WithdrawFrom, WithdrawRequest, WithdrawResult}; +use std::iter::once; + use async_trait::async_trait; use chain::TransactionOutput; use common::log::info; @@ -17,11 +13,17 @@ use rpc::v1::types::ToTxHash; use rpc_task::RpcTaskError; use script::{Builder, Script, SignatureVersion, TransactionInputSigner}; use serialization::{serialize, serialize_with_flags, SERIALIZE_TRANSACTION_WITNESS}; -use std::iter::once; use utxo_signer::sign_params::{OutputDestination, SendingOutputInfo, SpendingInputInfo, UtxoSignTxParamsBuilder}; use utxo_signer::{with_key_pair, UtxoSignTxError}; use utxo_signer::{SignPolicy, UtxoSignerOps}; +use crate::rpc_command::init_withdraw::{WithdrawInProgressStatus, WithdrawTaskHandle}; +use crate::utxo::utxo_common::{big_decimal_from_sat, UtxoTxBuilder}; +use crate::utxo::{output_script, sat_from_big_decimal, ActualTxFee, Address, FeePolicy, GetUtxoListOps, PrivKeyPolicy, + UtxoAddressFormat, UtxoCoinFields, UtxoCommonOps, UtxoFeeDetails, UtxoTx, UTXO_LOCK}; +use crate::{CoinWithDerivationMethod, GetWithdrawSenderAddress, MarketCoinOps, TransactionDetails, WithdrawError, + WithdrawFee, WithdrawFrom, WithdrawRequest, WithdrawResult}; + impl From for WithdrawError { fn from(sign_err: UtxoSignTxError) -> Self { match sign_err { diff --git a/mm2src/coins/utxo_signer/src/lib.rs b/mm2src/coins/utxo_signer/src/lib.rs index 9285bf8587..bae5c5b8ab 100644 --- a/mm2src/coins/utxo_signer/src/lib.rs +++ b/mm2src/coins/utxo_signer/src/lib.rs @@ -13,9 +13,10 @@ pub mod sign_params; pub mod with_key_pair; pub mod with_trezor; -use crate::with_key_pair::UtxoSignWithKeyPairError; use sign_params::UtxoSignTxParams; +use crate::with_key_pair::UtxoSignWithKeyPairError; + pub type UtxoSignTxResult = Result>; type Signature = Bytes; diff --git a/mm2src/coins/utxo_signer/src/sign_common.rs b/mm2src/coins/utxo_signer/src/sign_common.rs index 85732dd900..6e7d9c8301 100644 --- a/mm2src/coins/utxo_signer/src/sign_common.rs +++ b/mm2src/coins/utxo_signer/src/sign_common.rs @@ -1,10 +1,11 @@ -use crate::Signature; use chain::{Transaction as UtxoTx, TransactionInput}; use keys::bytes::Bytes; use keys::Public as PublicKey; use primitives::hash::{H256, H512}; use script::{Builder, Script, TransactionInputSigner, UnsignedTransactionInput}; +use crate::Signature; + pub(crate) fn complete_tx(unsigned: TransactionInputSigner, signed_inputs: Vec) -> UtxoTx { UtxoTx { inputs: signed_inputs, diff --git a/mm2src/coins/utxo_signer/src/sign_params.rs b/mm2src/coins/utxo_signer/src/sign_params.rs index dab3ad17a4..834c56d472 100644 --- a/mm2src/coins/utxo_signer/src/sign_params.rs +++ b/mm2src/coins/utxo_signer/src/sign_params.rs @@ -1,4 +1,3 @@ -use crate::{UtxoSignTxError, UtxoSignTxResult}; use chain::TransactionOutput; use crypto::trezor::utxo::TrezorOutputScriptType; use crypto::DerivationPath; @@ -6,6 +5,8 @@ use keys::Public as PublicKey; use mm2_err_handle::prelude::*; use script::{Script, SignatureVersion, TransactionInputSigner, UnsignedTransactionInput}; +use crate::{UtxoSignTxError, UtxoSignTxResult}; + impl UtxoSignTxError { fn no_param(param: &str) -> UtxoSignTxError { UtxoSignTxError::InvalidSignParam { diff --git a/mm2src/coins/utxo_signer/src/with_key_pair.rs b/mm2src/coins/utxo_signer/src/with_key_pair.rs index 38b67b3b7b..58d45d659c 100644 --- a/mm2src/coins/utxo_signer/src/with_key_pair.rs +++ b/mm2src/coins/utxo_signer/src/with_key_pair.rs @@ -1,6 +1,3 @@ -use crate::sign_common::{complete_tx, p2pk_spend_with_signature, p2pkh_spend_with_signature, - p2sh_spend_with_signature, p2wpkh_spend_with_signature}; -use crate::Signature; use chain::{Transaction as UtxoTx, TransactionInput}; use derive_more::Display; use keys::bytes::Bytes; @@ -9,6 +6,10 @@ use mm2_err_handle::prelude::*; use primitives::hash::H256; use script::{Builder, Script, SignatureVersion, TransactionInputSigner, UnsignedTransactionInput}; +use crate::sign_common::{complete_tx, p2pk_spend_with_signature, p2pkh_spend_with_signature, + p2sh_spend_with_signature, p2wpkh_spend_with_signature}; +use crate::Signature; + pub const SIGHASH_ALL: u32 = 1; pub const _SIGHASH_NONE: u32 = 2; pub const SIGHASH_SINGLE: u32 = 3; diff --git a/mm2src/coins/utxo_signer/src/with_trezor.rs b/mm2src/coins/utxo_signer/src/with_trezor.rs index 5cbe8709ae..58e9eb0622 100644 --- a/mm2src/coins/utxo_signer/src/with_trezor.rs +++ b/mm2src/coins/utxo_signer/src/with_trezor.rs @@ -1,6 +1,3 @@ -use crate::sign_common::{complete_tx, p2pkh_spend_with_signature}; -use crate::sign_params::{OutputDestination, SendingOutputInfo, SpendingInputInfo, UtxoSignTxParams}; -use crate::{TxProvider, UtxoSignTxError, UtxoSignTxResult}; use chain::{Transaction as UtxoTx, TransactionOutput}; use common::log::debug; use crypto::trezor::utxo::{PrevTx, PrevTxInput, PrevTxOutput, TrezorInputScriptType, TxOutput, TxSignResult, @@ -12,6 +9,10 @@ use rpc::v1::types::H256 as H256Json; use script::{SignatureVersion, UnsignedTransactionInput}; use serialization::deserialize; +use crate::sign_common::{complete_tx, p2pkh_spend_with_signature}; +use crate::sign_params::{OutputDestination, SendingOutputInfo, SpendingInputInfo, UtxoSignTxParams}; +use crate::{TxProvider, UtxoSignTxError, UtxoSignTxResult}; + pub struct TrezorTxSigner<'a, TxP> { pub trezor: TrezorSession<'a>, pub tx_provider: TxP, diff --git a/mm2src/coins/watcher_common.rs b/mm2src/coins/watcher_common.rs index f6c0e7068d..967a5bb91b 100644 --- a/mm2src/coins/watcher_common.rs +++ b/mm2src/coins/watcher_common.rs @@ -1,6 +1,7 @@ -use crate::ValidatePaymentError; use mm2_err_handle::prelude::MmError; +use crate::ValidatePaymentError; + pub const REWARD_GAS_AMOUNT: u64 = 70000; const REWARD_MARGIN: f64 = 0.05; diff --git a/mm2src/coins/z_coin.rs b/mm2src/coins/z_coin.rs index 047a1cf1fd..bc94af3968 100644 --- a/mm2src/coins/z_coin.rs +++ b/mm2src/coins/z_coin.rs @@ -1,31 +1,9 @@ -use crate::coin_errors::MyAddressError; -#[cfg(not(target_arch = "wasm32"))] -use crate::my_tx_history_v2::{MyTxHistoryErrorV2, MyTxHistoryRequestV2, MyTxHistoryResponseV2}; -#[cfg(not(target_arch = "wasm32"))] -use crate::rpc_command::init_withdraw::{InitWithdrawCoin, WithdrawInProgressStatus, WithdrawTaskHandle}; -use crate::utxo::rpc_clients::{ElectrumRpcRequest, UnspentInfo, UtxoRpcClientEnum, UtxoRpcError, UtxoRpcFut, - UtxoRpcResult}; -use crate::utxo::utxo_builder::UtxoCoinBuildError; -use crate::utxo::utxo_builder::{UtxoCoinBuilder, UtxoCoinBuilderCommonOps, UtxoFieldsWithGlobalHDBuilder, - UtxoFieldsWithHardwareWalletBuilder, UtxoFieldsWithIguanaSecretBuilder}; -use crate::utxo::utxo_common::{big_decimal_from_sat_unsigned, payment_script}; -use crate::utxo::{sat_from_big_decimal, utxo_common, ActualTxFee, AdditionalTxData, AddrFromStrError, Address, - BroadcastTxErr, FeePolicy, GetUtxoListOps, HistoryUtxoTx, HistoryUtxoTxMap, MatureUnspentList, - RecentlySpentOutPointsGuard, UtxoActivationParams, UtxoAddressFormat, UtxoArc, UtxoCoinFields, - UtxoCommonOps, UtxoRpcMode, UtxoTxBroadcastOps, UtxoTxGenerationOps, VerboseTransactionFrom}; -use crate::{BalanceError, BalanceFut, CheckIfMyPaymentSentArgs, CoinBalance, CoinFutSpawner, ConfirmPaymentInput, - FeeApproxStage, FoundSwapTxSpend, HistorySyncState, MakerSwapTakerCoin, MarketCoinOps, MmCoin, MmCoinEnum, - NegotiateSwapContractAddrErr, PaymentInstructionArgs, PaymentInstructions, PaymentInstructionsErr, - PrivKeyActivationPolicy, PrivKeyBuildPolicy, PrivKeyPolicyNotAllowed, RawTransactionFut, - RawTransactionRequest, RefundError, RefundPaymentArgs, RefundResult, SearchForSwapTxSpendInput, - SendMakerPaymentSpendPreimageInput, SendPaymentArgs, SignatureError, SignatureResult, SpendPaymentArgs, - SwapOps, TakerSwapMakerCoin, TradeFee, TradePreimageFut, TradePreimageResult, TradePreimageValue, - TransactionEnum, TransactionFut, TransactionResult, TxMarshalingErr, UnexpectedDerivationMethod, - ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr, ValidateOtherPubKeyErr, - ValidatePaymentError, ValidatePaymentFut, ValidatePaymentInput, VerificationError, VerificationResult, - WaitForHTLCTxSpendArgs, WatcherOps, WatcherReward, WatcherRewardError, WatcherSearchForSwapTxSpendInput, - WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawFut, WithdrawRequest}; -use crate::{Transaction, WithdrawError}; +use std::collections::{HashMap, HashSet}; +use std::convert::TryInto; +use std::iter; +use std::path::PathBuf; +use std::sync::Arc; + use async_trait::async_trait; use bitcrypto::dhash256; use chain::constants::SEQUENCE_FINAL; @@ -51,11 +29,6 @@ use rpc::v1::types::{Bytes as BytesJson, Transaction as RpcTransaction, H256 as use script::{Builder as ScriptBuilder, Opcode, Script, TransactionInputSigner}; use serde_json::Value as Json; use serialization::CoinVariant; -use std::collections::{HashMap, HashSet}; -use std::convert::TryInto; -use std::iter; -use std::path::PathBuf; -use std::sync::Arc; #[cfg(target_arch = "wasm32")] use z_coin_errors::ZCoinBalanceError; use z_rpc::{SaplingSyncConnector, SaplingSyncGuard}; @@ -72,6 +45,35 @@ use zcash_primitives::{constants::mainnet as z_mainnet_constants, sapling::Payme zip32::ExtendedFullViewingKey, zip32::ExtendedSpendingKey}; use zcash_proofs::prover::LocalTxProver; +use crate::coin_errors::MyAddressError; +#[cfg(not(target_arch = "wasm32"))] +use crate::my_tx_history_v2::{MyTxHistoryErrorV2, MyTxHistoryRequestV2, MyTxHistoryResponseV2}; +#[cfg(not(target_arch = "wasm32"))] +use crate::rpc_command::init_withdraw::{InitWithdrawCoin, WithdrawInProgressStatus, WithdrawTaskHandle}; +use crate::utxo::rpc_clients::{ElectrumRpcRequest, UnspentInfo, UtxoRpcClientEnum, UtxoRpcError, UtxoRpcFut, + UtxoRpcResult}; +use crate::utxo::utxo_builder::UtxoCoinBuildError; +use crate::utxo::utxo_builder::{UtxoCoinBuilder, UtxoCoinBuilderCommonOps, UtxoFieldsWithGlobalHDBuilder, + UtxoFieldsWithHardwareWalletBuilder, UtxoFieldsWithIguanaSecretBuilder}; +use crate::utxo::utxo_common::{big_decimal_from_sat_unsigned, payment_script}; +use crate::utxo::{sat_from_big_decimal, utxo_common, ActualTxFee, AdditionalTxData, AddrFromStrError, Address, + BroadcastTxErr, FeePolicy, GetUtxoListOps, HistoryUtxoTx, HistoryUtxoTxMap, MatureUnspentList, + RecentlySpentOutPointsGuard, UtxoActivationParams, UtxoAddressFormat, UtxoArc, UtxoCoinFields, + UtxoCommonOps, UtxoRpcMode, UtxoTxBroadcastOps, UtxoTxGenerationOps, VerboseTransactionFrom}; +use crate::{BalanceError, BalanceFut, CheckIfMyPaymentSentArgs, CoinBalance, CoinFutSpawner, ConfirmPaymentInput, + FeeApproxStage, FoundSwapTxSpend, HistorySyncState, MakerSwapTakerCoin, MarketCoinOps, MmCoin, MmCoinEnum, + NegotiateSwapContractAddrErr, PaymentInstructionArgs, PaymentInstructions, PaymentInstructionsErr, + PrivKeyActivationPolicy, PrivKeyBuildPolicy, PrivKeyPolicyNotAllowed, RawTransactionFut, + RawTransactionRequest, RefundError, RefundPaymentArgs, RefundResult, SearchForSwapTxSpendInput, + SendMakerPaymentSpendPreimageInput, SendPaymentArgs, SignatureError, SignatureResult, SpendPaymentArgs, + SwapOps, TakerSwapMakerCoin, TradeFee, TradePreimageFut, TradePreimageResult, TradePreimageValue, + TransactionEnum, TransactionFut, TransactionResult, TxMarshalingErr, UnexpectedDerivationMethod, + ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr, ValidateOtherPubKeyErr, + ValidatePaymentError, ValidatePaymentFut, ValidatePaymentInput, VerificationError, VerificationResult, + WaitForHTLCTxSpendArgs, WatcherOps, WatcherReward, WatcherRewardError, WatcherSearchForSwapTxSpendInput, + WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawFut, WithdrawRequest}; +use crate::{Transaction, WithdrawError}; + mod z_htlc; use z_htlc::{z_p2sh_spend, z_send_dex_fee, z_send_htlc}; @@ -100,9 +102,10 @@ cfg_native!( ); #[allow(unused)] mod z_coin_errors; -use crate::z_coin::storage::{BlockDbImpl, WalletDbShared}; pub use z_coin_errors::*; +use crate::z_coin::storage::{BlockDbImpl, WalletDbShared}; + pub mod storage; #[cfg(all(test, feature = "zhtlc-native-tests"))] mod z_coin_native_tests; @@ -2090,6 +2093,7 @@ fn derive_z_key_from_mm_seed() { #[test] fn test_interpret_memo_string() { use std::str::FromStr; + use zcash_primitives::memo::Memo; let actual = interpret_memo_string("68656c6c6f207a63617368").unwrap(); diff --git a/mm2src/coins/z_coin/storage/blockdb/mod.rs b/mm2src/coins/z_coin/storage/blockdb/mod.rs index cd9aceb6ef..67c6f8e903 100644 --- a/mm2src/coins/z_coin/storage/blockdb/mod.rs +++ b/mm2src/coins/z_coin/storage/blockdb/mod.rs @@ -1,7 +1,8 @@ #[cfg(target_arch = "wasm32")] pub(crate) mod block_idb; -use mm2_core::mm_ctx::MmArc; use std::path::Path; + +use mm2_core::mm_ctx::MmArc; use zcash_client_backend::data_api::BlockSource; use zcash_client_backend::proto::compact_formats::CompactBlock; use zcash_primitives::consensus::BlockHeight; diff --git a/mm2src/coins/z_coin/storage/walletdb/mod.rs b/mm2src/coins/z_coin/storage/walletdb/mod.rs index 656993cd4b..a102dd77fe 100644 --- a/mm2src/coins/z_coin/storage/walletdb/mod.rs +++ b/mm2src/coins/z_coin/storage/walletdb/mod.rs @@ -1,7 +1,8 @@ -use crate::z_coin::{ZCoinBuilder, ZcoinClientInitError}; use mm2_err_handle::prelude::*; use zcash_primitives::zip32::ExtendedSpendingKey; +use crate::z_coin::{ZCoinBuilder, ZcoinClientInitError}; + cfg_native!( use crate::z_coin::{CheckPointBlockInfo, ZcoinConsensusParams}; use crate::z_coin::z_rpc::create_wallet_db; diff --git a/mm2src/coins/z_coin/z_coin_errors.rs b/mm2src/coins/z_coin/z_coin_errors.rs index 2a78aedc3f..2c12c0e157 100644 --- a/mm2src/coins/z_coin/z_coin_errors.rs +++ b/mm2src/coins/z_coin/z_coin_errors.rs @@ -1,11 +1,3 @@ -use crate::my_tx_history_v2::MyTxHistoryErrorV2; -use crate::utxo::rpc_clients::UtxoRpcError; -use crate::utxo::utxo_builder::UtxoCoinBuildError; -use crate::z_coin::storage::WalletDbError; -use crate::NumConversError; -use crate::PrivKeyPolicyNotAllowed; -use crate::WithdrawError; - use common::jsonrpc_client::JsonRpcError; #[cfg(not(target_arch = "wasm32"))] use db_common::sqlite::rusqlite::Error as SqliteError; @@ -17,6 +9,14 @@ use rpc::v1::types::{Bytes as BytesJson, H256 as H256Json}; use zcash_client_sqlite::error::SqliteClientError; use zcash_primitives::transaction::builder::Error as ZTxBuilderError; +use crate::my_tx_history_v2::MyTxHistoryErrorV2; +use crate::utxo::rpc_clients::UtxoRpcError; +use crate::utxo::utxo_builder::UtxoCoinBuildError; +use crate::z_coin::storage::WalletDbError; +use crate::NumConversError; +use crate::PrivKeyPolicyNotAllowed; +use crate::WithdrawError; + /// Represents possible errors that might occur while interacting with Zcoin rpc. #[derive(Debug, Display)] #[non_exhaustive] diff --git a/mm2src/coins/z_coin/z_coin_native_tests.rs b/mm2src/coins/z_coin/z_coin_native_tests.rs index 12789b2090..bd9790c5a9 100644 --- a/mm2src/coins/z_coin/z_coin_native_tests.rs +++ b/mm2src/coins/z_coin/z_coin_native_tests.rs @@ -1,9 +1,10 @@ +use std::path::PathBuf; +use std::time::Duration; + use bitcrypto::dhash160; use common::{block_on, now_sec}; use mm2_core::mm_ctx::MmCtxBuilder; use mm2_test_helpers::for_tests::zombie_conf; -use std::path::PathBuf; -use std::time::Duration; use zcash_client_backend::encoding::decode_extended_spending_key; use super::{z_coin_from_conf_and_params_with_z_key, z_mainnet_constants, Future, PrivKeyBuildPolicy, diff --git a/mm2src/coins/z_coin/z_htlc.rs b/mm2src/coins/z_coin/z_htlc.rs index edde4bbc37..44df01d1ec 100644 --- a/mm2src/coins/z_coin/z_htlc.rs +++ b/mm2src/coins/z_coin/z_htlc.rs @@ -5,14 +5,6 @@ // taker payment spend - https://zombie.explorer.lordofthechains.com/tx/af6bb0f99f9a5a070a0c1f53d69e4189b0e9b68f9d66e69f201a6b6d9f93897e // maker payment spend - https://rick.explorer.dexstats.info/tx/6a2dcc866ad75cebecb780a02320073a88bcf5e57ddccbe2657494e7747d591e -use super::ZCoin; -use crate::utxo::rpc_clients::{UtxoRpcClientEnum, UtxoRpcError}; -use crate::utxo::utxo_common::payment_script; -use crate::utxo::{sat_from_big_decimal, UtxoAddressFormat}; -use crate::z_coin::SendOutputsErr; -use crate::z_coin::{ZOutput, DEX_FEE_OVK}; -use crate::NumConversError; -use crate::{PrivKeyPolicyNotAllowed, TransactionEnum}; use bitcrypto::dhash160; use derive_more::Display; use futures::compat::Future01CompatExt; @@ -28,6 +20,15 @@ use zcash_primitives::transaction::builder::Error as ZTxBuilderError; use zcash_primitives::transaction::components::{Amount, TxOut}; use zcash_primitives::transaction::Transaction as ZTransaction; +use super::ZCoin; +use crate::utxo::rpc_clients::{UtxoRpcClientEnum, UtxoRpcError}; +use crate::utxo::utxo_common::payment_script; +use crate::utxo::{sat_from_big_decimal, UtxoAddressFormat}; +use crate::z_coin::SendOutputsErr; +use crate::z_coin::{ZOutput, DEX_FEE_OVK}; +use crate::NumConversError; +use crate::{PrivKeyPolicyNotAllowed, TransactionEnum}; + cfg_native!( use common::async_blocking; use secp256k1::SecretKey; diff --git a/mm2src/coins/z_coin/z_rpc.rs b/mm2src/coins/z_coin/z_rpc.rs index 5996762444..f6da4c67ff 100644 --- a/mm2src/coins/z_coin/z_rpc.rs +++ b/mm2src/coins/z_coin/z_rpc.rs @@ -1,6 +1,5 @@ -use super::{z_coin_errors::*, BlockDbImpl, WalletDbShared, ZCoinBuilder, ZcoinConsensusParams}; -use crate::utxo::rpc_clients::NativeClient; -use crate::z_coin::SyncStartPoint; +use std::sync::Arc; + use async_trait::async_trait; use common::executor::{spawn_abortable, AbortOnDropHandle}; use futures::channel::mpsc::{Receiver as AsyncReceiver, Sender as AsyncSender}; @@ -9,11 +8,14 @@ use futures::lock::{Mutex as AsyncMutex, MutexGuard as AsyncMutexGuard}; use futures::StreamExt; use mm2_err_handle::prelude::*; use parking_lot::Mutex; -use std::sync::Arc; use zcash_primitives::consensus::BlockHeight; use zcash_primitives::transaction::TxId; use zcash_primitives::zip32::ExtendedSpendingKey; +use super::{z_coin_errors::*, BlockDbImpl, WalletDbShared, ZCoinBuilder, ZcoinConsensusParams}; +use crate::utxo::rpc_clients::NativeClient; +use crate::z_coin::SyncStartPoint; + cfg_native!( use crate::{RpcCommonOps, ZTransaction}; use crate::utxo::rpc_clients::{UtxoRpcClientOps, NO_TX_ERROR_CODE}; diff --git a/mm2src/coins_activation/src/bch_with_tokens_activation.rs b/mm2src/coins_activation/src/bch_with_tokens_activation.rs index a6d4c54df8..9a067fde15 100644 --- a/mm2src/coins_activation/src/bch_with_tokens_activation.rs +++ b/mm2src/coins_activation/src/bch_with_tokens_activation.rs @@ -1,6 +1,6 @@ -use crate::platform_coin_with_tokens::*; -use crate::prelude::*; -use crate::slp_token_activation::SlpActivationRequest; +use std::collections::{HashMap, HashSet}; +use std::str::FromStr; + use async_trait::async_trait; use coins::my_tx_history_v2::TxHistoryStorage; use coins::utxo::bch::{bch_coin_with_policy, BchActivationRequest, BchCoin, CashAddrPrefix}; @@ -20,8 +20,10 @@ use mm2_err_handle::prelude::*; use mm2_number::BigDecimal; use serde_derive::{Deserialize, Serialize}; use serde_json::Value as Json; -use std::collections::{HashMap, HashSet}; -use std::str::FromStr; + +use crate::platform_coin_with_tokens::*; +use crate::prelude::*; +use crate::slp_token_activation::SlpActivationRequest; impl From for InitTokensAsMmCoinsError { fn from(e: EnableSlpError) -> Self { diff --git a/mm2src/coins_activation/src/context.rs b/mm2src/coins_activation/src/context.rs index a86869e7ab..af81718533 100644 --- a/mm2src/coins_activation/src/context.rs +++ b/mm2src/coins_activation/src/context.rs @@ -1,11 +1,13 @@ +use std::sync::Arc; + +use mm2_core::mm_ctx::{from_ctx, MmArc}; +use rpc_task::RpcTaskManager; + #[cfg(not(target_arch = "wasm32"))] use crate::lightning_activation::LightningTaskManagerShared; use crate::utxo_activation::{QtumTaskManagerShared, UtxoStandardTaskManagerShared}; #[cfg(not(target_arch = "wasm32"))] use crate::z_coin_activation::ZcoinTaskManagerShared; -use mm2_core::mm_ctx::{from_ctx, MmArc}; -use rpc_task::RpcTaskManager; -use std::sync::Arc; pub struct CoinsActivationContext { pub(crate) init_utxo_standard_task_manager: UtxoStandardTaskManagerShared, diff --git a/mm2src/coins_activation/src/erc20_token_activation.rs b/mm2src/coins_activation/src/erc20_token_activation.rs index 9a5dff22d9..d181547a69 100644 --- a/mm2src/coins_activation/src/erc20_token_activation.rs +++ b/mm2src/coins_activation/src/erc20_token_activation.rs @@ -1,5 +1,5 @@ -use crate::{prelude::{TryFromCoinProtocol, TryPlatformCoinFromMmCoinEnum}, - token::{EnableTokenError, TokenActivationOps, TokenProtocolParams}}; +use std::collections::HashMap; + use async_trait::async_trait; use coins::{eth::{v2_activation::{Erc20Protocol, Erc20TokenActivationError, Erc20TokenActivationRequest}, valid_addr_from_str, EthCoin}, @@ -7,7 +7,9 @@ use coins::{eth::{v2_activation::{Erc20Protocol, Erc20TokenActivationError, Erc2 use common::Future01CompatExt; use mm2_err_handle::prelude::MmError; use serde::Serialize; -use std::collections::HashMap; + +use crate::{prelude::{TryFromCoinProtocol, TryPlatformCoinFromMmCoinEnum}, + token::{EnableTokenError, TokenActivationOps, TokenProtocolParams}}; #[derive(Debug, Serialize)] pub struct Erc20InitResult { diff --git a/mm2src/coins_activation/src/eth_with_token_activation.rs b/mm2src/coins_activation/src/eth_with_token_activation.rs index 0f7c8d8455..aeb3b69145 100644 --- a/mm2src/coins_activation/src/eth_with_token_activation.rs +++ b/mm2src/coins_activation/src/eth_with_token_activation.rs @@ -1,8 +1,5 @@ -use crate::{platform_coin_with_tokens::{EnablePlatformCoinWithTokensError, GetPlatformBalance, - InitTokensAsMmCoinsError, PlatformWithTokensActivationOps, RegisterTokenInfo, - TokenActivationParams, TokenActivationRequest, TokenAsMmCoinInitializer, - TokenInitializer, TokenOf}, - prelude::*}; +use std::collections::{HashMap, HashSet}; + use async_trait::async_trait; use coins::eth::EthPrivKeyBuildPolicy; use coins::{eth::v2_activation::EthPrivKeyActivationPolicy, MmCoinEnum}; @@ -20,7 +17,12 @@ use mm2_metamask::MetamaskRpcError; use mm2_number::BigDecimal; use serde::{Deserialize, Serialize}; use serde_json::Value as Json; -use std::collections::{HashMap, HashSet}; + +use crate::{platform_coin_with_tokens::{EnablePlatformCoinWithTokensError, GetPlatformBalance, + InitTokensAsMmCoinsError, PlatformWithTokensActivationOps, RegisterTokenInfo, + TokenActivationParams, TokenActivationRequest, TokenAsMmCoinInitializer, + TokenInitializer, TokenOf}, + prelude::*}; impl From for EnablePlatformCoinWithTokensError { fn from(err: EthActivationV2Error) -> Self { diff --git a/mm2src/coins_activation/src/l2/init_l2.rs b/mm2src/coins_activation/src/l2/init_l2.rs index 00cf6eb8dc..0cbbc8b052 100644 --- a/mm2src/coins_activation/src/l2/init_l2.rs +++ b/mm2src/coins_activation/src/l2/init_l2.rs @@ -1,9 +1,3 @@ -/// Contains L2 activation traits and their implementations for various coins -/// -use crate::context::CoinsActivationContext; -use crate::l2::init_l2_error::{CancelInitL2Error, InitL2StatusError, InitL2UserActionError}; -use crate::l2::InitL2Error; -use crate::prelude::*; use async_trait::async_trait; use coins::{lp_coinfind, lp_coinfind_or_err, CoinsContext, MmCoinEnum, RegisterCoinError}; use common::SuccessResponse; @@ -14,6 +8,13 @@ use rpc_task::{RpcTask, RpcTaskHandle, RpcTaskManager, RpcTaskManagerShared, Rpc use serde_derive::Deserialize; use serde_json::Value as Json; +/// Contains L2 activation traits and their implementations for various coins +/// +use crate::context::CoinsActivationContext; +use crate::l2::init_l2_error::{CancelInitL2Error, InitL2StatusError, InitL2UserActionError}; +use crate::l2::InitL2Error; +use crate::prelude::*; + pub type InitL2Response = InitRpcTaskResponse; pub type InitL2StatusRequest = RpcTaskStatusRequest; pub type InitL2UserActionRequest = RpcTaskUserActionRequest; diff --git a/mm2src/coins_activation/src/l2/init_l2_error.rs b/mm2src/coins_activation/src/l2/init_l2_error.rs index d23fd73078..d41d0c1f4c 100644 --- a/mm2src/coins_activation/src/l2/init_l2_error.rs +++ b/mm2src/coins_activation/src/l2/init_l2_error.rs @@ -1,4 +1,5 @@ -use crate::prelude::CoinConfWithProtocolError; +use std::time::Duration; + use coins::CoinProtocol; use common::{HttpStatusCode, StatusCode}; use derive_more::Display; @@ -6,7 +7,8 @@ use rpc_task::rpc_common::{CancelRpcTaskError, RpcTaskStatusError, RpcTaskUserAc use rpc_task::RpcTaskError; use ser_error_derive::SerializeErrorType; use serde_derive::Serialize; -use std::time::Duration; + +use crate::prelude::CoinConfWithProtocolError; pub type InitL2StatusError = RpcTaskStatusError; pub type InitL2UserActionError = RpcTaskUserActionError; diff --git a/mm2src/coins_activation/src/lightning_activation.rs b/mm2src/coins_activation/src/lightning_activation.rs index c5aed05804..7a685cb7f6 100644 --- a/mm2src/coins_activation/src/lightning_activation.rs +++ b/mm2src/coins_activation/src/lightning_activation.rs @@ -1,7 +1,5 @@ -use crate::context::CoinsActivationContext; -use crate::l2::{InitL2ActivationOps, InitL2Error, InitL2InitialStatus, InitL2TaskHandle, InitL2TaskManagerShared, - L2ProtocolParams}; -use crate::prelude::*; +use std::sync::Arc; + use async_trait::async_trait; use coins::coin_errors::MyAddressError; use coins::lightning::ln_conf::{LightningCoinConf, LightningProtocolConf}; @@ -32,7 +30,11 @@ use parking_lot::Mutex as PaMutex; use ser_error_derive::SerializeErrorType; use serde_derive::{Deserialize, Serialize}; use serde_json::{self as json, Value as Json}; -use std::sync::Arc; + +use crate::context::CoinsActivationContext; +use crate::l2::{InitL2ActivationOps, InitL2Error, InitL2InitialStatus, InitL2TaskHandle, InitL2TaskManagerShared, + L2ProtocolParams}; +use crate::prelude::*; const DEFAULT_LISTENING_PORT: u16 = 9735; diff --git a/mm2src/coins_activation/src/platform_coin_with_tokens.rs b/mm2src/coins_activation/src/platform_coin_with_tokens.rs index 94b9a16fc9..ea6a50a497 100644 --- a/mm2src/coins_activation/src/platform_coin_with_tokens.rs +++ b/mm2src/coins_activation/src/platform_coin_with_tokens.rs @@ -1,4 +1,3 @@ -use crate::prelude::*; use async_trait::async_trait; use coins::my_tx_history_v2::TxHistoryStorage; use coins::tx_history_storage::{CreateTxHistoryStorageError, TxHistoryStorageBuilder}; @@ -13,6 +12,8 @@ use ser_error_derive::SerializeErrorType; use serde_derive::{Deserialize, Serialize}; use serde_json::Value as Json; +use crate::prelude::*; + #[derive(Clone, Debug, Deserialize)] pub struct TokenActivationRequest { ticker: String, diff --git a/mm2src/coins_activation/src/prelude.rs b/mm2src/coins_activation/src/prelude.rs index 2126d8bc06..86e22ecbbb 100644 --- a/mm2src/coins_activation/src/prelude.rs +++ b/mm2src/coins_activation/src/prelude.rs @@ -1,3 +1,5 @@ +use std::collections::{HashMap, HashSet}; + use coins::utxo::UtxoActivationParams; #[cfg(not(target_arch = "wasm32"))] use coins::z_coin::ZcoinActivationParams; @@ -7,7 +9,6 @@ use mm2_err_handle::prelude::*; use mm2_number::BigDecimal; use serde_derive::Serialize; use serde_json::{self as json, Value as Json}; -use std::collections::{HashMap, HashSet}; pub trait CurrentBlock { fn current_block(&self) -> u64; diff --git a/mm2src/coins_activation/src/slp_token_activation.rs b/mm2src/coins_activation/src/slp_token_activation.rs index 85f017b0cc..7d32a1f6b2 100644 --- a/mm2src/coins_activation/src/slp_token_activation.rs +++ b/mm2src/coins_activation/src/slp_token_activation.rs @@ -1,5 +1,5 @@ -use crate::prelude::*; -use crate::token::{EnableTokenError, TokenActivationOps, TokenProtocolParams}; +use std::collections::HashMap; + use async_trait::async_trait; use coins::utxo::bch::BchCoin; use coins::utxo::slp::{EnableSlpError, SlpProtocolConf, SlpToken}; @@ -7,7 +7,9 @@ use coins::{CoinBalance, CoinProtocol, MarketCoinOps, MmCoin, MmCoinEnum}; use mm2_err_handle::prelude::*; use rpc::v1::types::H256 as H256Json; use serde_derive::{Deserialize, Serialize}; -use std::collections::HashMap; + +use crate::prelude::*; +use crate::token::{EnableTokenError, TokenActivationOps, TokenProtocolParams}; impl TryPlatformCoinFromMmCoinEnum for BchCoin { fn try_from_mm_coin(coin: MmCoinEnum) -> Option diff --git a/mm2src/coins_activation/src/solana_with_tokens_activation.rs b/mm2src/coins_activation/src/solana_with_tokens_activation.rs index b6bd7b123d..cd4d82f286 100644 --- a/mm2src/coins_activation/src/solana_with_tokens_activation.rs +++ b/mm2src/coins_activation/src/solana_with_tokens_activation.rs @@ -1,10 +1,5 @@ -use crate::platform_coin_with_tokens::{EnablePlatformCoinWithTokensError, GetPlatformBalance, - InitTokensAsMmCoinsError, PlatformWithTokensActivationOps, RegisterTokenInfo, - TokenActivationParams, TokenActivationRequest, TokenAsMmCoinInitializer, - TokenInitializer, TokenOf}; -use crate::prelude::*; -use crate::prelude::{CoinAddressInfo, TokenBalances, TryFromCoinProtocol, TxHistory}; -use crate::spl_token_activation::SplActivationRequest; +use std::collections::HashMap; + use async_trait::async_trait; use coins::coin_errors::MyAddressError; use coins::my_tx_history_v2::TxHistoryStorage; @@ -21,7 +16,14 @@ use mm2_err_handle::prelude::*; use mm2_number::BigDecimal; use serde_derive::{Deserialize, Serialize}; use serde_json::Value as Json; -use std::collections::HashMap; + +use crate::platform_coin_with_tokens::{EnablePlatformCoinWithTokensError, GetPlatformBalance, + InitTokensAsMmCoinsError, PlatformWithTokensActivationOps, RegisterTokenInfo, + TokenActivationParams, TokenActivationRequest, TokenAsMmCoinInitializer, + TokenInitializer, TokenOf}; +use crate::prelude::*; +use crate::prelude::{CoinAddressInfo, TokenBalances, TryFromCoinProtocol, TxHistory}; +use crate::spl_token_activation::SplActivationRequest; pub struct SplTokenInitializer { platform_coin: SolanaCoin, diff --git a/mm2src/coins_activation/src/spl_token_activation.rs b/mm2src/coins_activation/src/spl_token_activation.rs index 69782e11ac..c04fab1615 100644 --- a/mm2src/coins_activation/src/spl_token_activation.rs +++ b/mm2src/coins_activation/src/spl_token_activation.rs @@ -1,5 +1,5 @@ -use crate::prelude::{TryFromCoinProtocol, TryPlatformCoinFromMmCoinEnum}; -use crate::token::{EnableTokenError, TokenActivationOps, TokenProtocolParams}; +use std::collections::HashMap; + use async_trait::async_trait; use coins::coin_errors::MyAddressError; use coins::solana::spl::{SplProtocolConf, SplTokenCreationError}; @@ -7,7 +7,9 @@ use coins::{BalanceError, CoinBalance, CoinProtocol, MarketCoinOps, MmCoinEnum, use common::Future01CompatExt; use mm2_err_handle::prelude::*; use serde_derive::{Deserialize, Serialize}; -use std::collections::HashMap; + +use crate::prelude::{TryFromCoinProtocol, TryPlatformCoinFromMmCoinEnum}; +use crate::token::{EnableTokenError, TokenActivationOps, TokenProtocolParams}; impl TryPlatformCoinFromMmCoinEnum for SolanaCoin { fn try_from_mm_coin(coin: MmCoinEnum) -> Option diff --git a/mm2src/coins_activation/src/standalone_coin/init_standalone_coin.rs b/mm2src/coins_activation/src/standalone_coin/init_standalone_coin.rs index 46b9638a4c..692cfabfd3 100644 --- a/mm2src/coins_activation/src/standalone_coin/init_standalone_coin.rs +++ b/mm2src/coins_activation/src/standalone_coin/init_standalone_coin.rs @@ -1,8 +1,5 @@ -use crate::context::CoinsActivationContext; -use crate::prelude::*; -use crate::standalone_coin::init_standalone_coin_error::{CancelInitStandaloneCoinError, InitStandaloneCoinError, - InitStandaloneCoinStatusError, - InitStandaloneCoinUserActionError}; +use std::collections::HashMap; + use async_trait::async_trait; use coins::my_tx_history_v2::TxHistoryStorage; use coins::tx_history_storage::{CreateTxHistoryStorageError, TxHistoryStorageBuilder}; @@ -17,7 +14,12 @@ use rpc_task::rpc_common::{CancelRpcTaskRequest, InitRpcTaskResponse, RpcTaskSta use rpc_task::{RpcTask, RpcTaskManager, RpcTaskManagerShared, RpcTaskStatus, RpcTaskTypes}; use serde_derive::Deserialize; use serde_json::Value as Json; -use std::collections::HashMap; + +use crate::context::CoinsActivationContext; +use crate::prelude::*; +use crate::standalone_coin::init_standalone_coin_error::{CancelInitStandaloneCoinError, InitStandaloneCoinError, + InitStandaloneCoinStatusError, + InitStandaloneCoinUserActionError}; pub type InitStandaloneCoinResponse = InitRpcTaskResponse; pub type InitStandaloneCoinStatusRequest = RpcTaskStatusRequest; diff --git a/mm2src/coins_activation/src/standalone_coin/init_standalone_coin_error.rs b/mm2src/coins_activation/src/standalone_coin/init_standalone_coin_error.rs index 1f0b5db764..81b38facff 100644 --- a/mm2src/coins_activation/src/standalone_coin/init_standalone_coin_error.rs +++ b/mm2src/coins_activation/src/standalone_coin/init_standalone_coin_error.rs @@ -1,4 +1,5 @@ -use crate::prelude::CoinConfWithProtocolError; +use std::time::Duration; + use coins::CoinProtocol; use common::{HttpStatusCode, StatusCode}; use crypto::HwRpcError; @@ -7,7 +8,8 @@ use rpc_task::rpc_common::{CancelRpcTaskError, RpcTaskStatusError, RpcTaskUserAc use rpc_task::{RpcTaskError, TaskId}; use ser_error_derive::SerializeErrorType; use serde_derive::Serialize; -use std::time::Duration; + +use crate::prelude::CoinConfWithProtocolError; pub type InitStandaloneCoinStatusError = RpcTaskStatusError; pub type InitStandaloneCoinUserActionError = RpcTaskUserActionError; diff --git a/mm2src/coins_activation/src/tendermint_token_activation.rs b/mm2src/coins_activation/src/tendermint_token_activation.rs index 58cc6b90c1..14475cd4f3 100644 --- a/mm2src/coins_activation/src/tendermint_token_activation.rs +++ b/mm2src/coins_activation/src/tendermint_token_activation.rs @@ -1,5 +1,5 @@ -use crate::{prelude::TryPlatformCoinFromMmCoinEnum, - token::{EnableTokenError, TokenActivationOps, TokenProtocolParams}}; +use std::collections::HashMap; + use async_trait::async_trait; use coins::{tendermint::{TendermintCoin, TendermintToken, TendermintTokenActivationParams, TendermintTokenInitError, TendermintTokenProtocolInfo}, @@ -7,7 +7,9 @@ use coins::{tendermint::{TendermintCoin, TendermintToken, TendermintTokenActivat use common::Future01CompatExt; use mm2_err_handle::prelude::{MapMmError, MmError}; use serde::Serialize; -use std::collections::HashMap; + +use crate::{prelude::TryPlatformCoinFromMmCoinEnum, + token::{EnableTokenError, TokenActivationOps, TokenProtocolParams}}; impl From for EnableTokenError { fn from(err: TendermintTokenInitError) -> Self { diff --git a/mm2src/coins_activation/src/tendermint_with_assets_activation.rs b/mm2src/coins_activation/src/tendermint_with_assets_activation.rs index 006f7993d3..b172fdbb67 100644 --- a/mm2src/coins_activation/src/tendermint_with_assets_activation.rs +++ b/mm2src/coins_activation/src/tendermint_with_assets_activation.rs @@ -1,8 +1,5 @@ -use crate::platform_coin_with_tokens::{EnablePlatformCoinWithTokensError, GetPlatformBalance, - InitTokensAsMmCoinsError, PlatformWithTokensActivationOps, RegisterTokenInfo, - TokenActivationParams, TokenActivationRequest, TokenAsMmCoinInitializer, - TokenInitializer, TokenOf}; -use crate::prelude::*; +use std::collections::{HashMap, HashSet}; + use async_trait::async_trait; use coins::my_tx_history_v2::TxHistoryStorage; use coins::tendermint::tendermint_tx_history_v2::tendermint_history_loop; @@ -18,7 +15,12 @@ use mm2_err_handle::prelude::*; use mm2_number::BigDecimal; use serde::{Deserialize, Serialize}; use serde_json::Value as Json; -use std::collections::{HashMap, HashSet}; + +use crate::platform_coin_with_tokens::{EnablePlatformCoinWithTokensError, GetPlatformBalance, + InitTokensAsMmCoinsError, PlatformWithTokensActivationOps, RegisterTokenInfo, + TokenActivationParams, TokenActivationRequest, TokenAsMmCoinInitializer, + TokenInitializer, TokenOf}; +use crate::prelude::*; impl TokenOf for TendermintToken { type PlatformCoin = TendermintCoin; diff --git a/mm2src/coins_activation/src/token.rs b/mm2src/coins_activation/src/token.rs index 70751b59cc..021fd4a28b 100644 --- a/mm2src/coins_activation/src/token.rs +++ b/mm2src/coins_activation/src/token.rs @@ -1,7 +1,5 @@ // Contains token activation traits and their implementations for various coins -use crate::platform_coin_with_tokens::{self, RegisterTokenInfo}; -use crate::prelude::*; use async_trait::async_trait; use coins::utxo::rpc_clients::UtxoRpcError; use coins::{lp_coinfind, lp_coinfind_or_err, BalanceError, CoinProtocol, CoinsContext, MmCoinEnum, RegisterCoinError, @@ -13,6 +11,9 @@ use mm2_err_handle::prelude::*; use ser_error_derive::SerializeErrorType; use serde_derive::{Deserialize, Serialize}; +use crate::platform_coin_with_tokens::{self, RegisterTokenInfo}; +use crate::prelude::*; + pub trait TokenProtocolParams { fn platform_coin_ticker(&self) -> &str; } diff --git a/mm2src/coins_activation/src/utxo_activation/common_impl.rs b/mm2src/coins_activation/src/utxo_activation/common_impl.rs index f33dbd41c5..72ac15710b 100644 --- a/mm2src/coins_activation/src/utxo_activation/common_impl.rs +++ b/mm2src/coins_activation/src/utxo_activation/common_impl.rs @@ -1,8 +1,5 @@ -use crate::standalone_coin::{InitStandaloneCoinActivationOps, InitStandaloneCoinTaskHandle}; -use crate::utxo_activation::init_utxo_standard_activation_error::InitUtxoStandardError; -use crate::utxo_activation::init_utxo_standard_statuses::{UtxoStandardAwaitingStatus, UtxoStandardInProgressStatus, - UtxoStandardUserAction}; -use crate::utxo_activation::utxo_standard_activation_result::UtxoStandardActivationResult; +use std::collections::HashMap; + use coins::coin_balance::EnableCoinBalanceOps; use coins::hd_pubkey::RpcTaskXPubExtractor; use coins::my_tx_history_v2::TxHistoryStorage; @@ -17,7 +14,12 @@ use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; use mm2_metrics::MetricsArc; use mm2_number::BigDecimal; -use std::collections::HashMap; + +use crate::standalone_coin::{InitStandaloneCoinActivationOps, InitStandaloneCoinTaskHandle}; +use crate::utxo_activation::init_utxo_standard_activation_error::InitUtxoStandardError; +use crate::utxo_activation::init_utxo_standard_statuses::{UtxoStandardAwaitingStatus, UtxoStandardInProgressStatus, + UtxoStandardUserAction}; +use crate::utxo_activation::utxo_standard_activation_result::UtxoStandardActivationResult; pub(crate) async fn get_activation_result( ctx: &MmArc, diff --git a/mm2src/coins_activation/src/utxo_activation/init_qtum_activation.rs b/mm2src/coins_activation/src/utxo_activation/init_qtum_activation.rs index 74e7d12a77..3b099d1337 100644 --- a/mm2src/coins_activation/src/utxo_activation/init_qtum_activation.rs +++ b/mm2src/coins_activation/src/utxo_activation/init_qtum_activation.rs @@ -1,13 +1,5 @@ -use crate::context::CoinsActivationContext; -use crate::prelude::TryFromCoinProtocol; -use crate::standalone_coin::{InitStandaloneCoinActivationOps, InitStandaloneCoinTaskHandle, - InitStandaloneCoinTaskManagerShared}; -use crate::utxo_activation::common_impl::{get_activation_result, priv_key_build_policy, - start_history_background_fetching}; -use crate::utxo_activation::init_utxo_standard_activation_error::InitUtxoStandardError; -use crate::utxo_activation::init_utxo_standard_statuses::{UtxoStandardAwaitingStatus, UtxoStandardInProgressStatus, - UtxoStandardUserAction}; -use crate::utxo_activation::utxo_standard_activation_result::UtxoStandardActivationResult; +use std::collections::HashMap; + use async_trait::async_trait; use coins::my_tx_history_v2::TxHistoryStorage; use coins::utxo::qtum::{QtumCoin, QtumCoinBuilder}; @@ -19,7 +11,17 @@ use mm2_err_handle::prelude::*; use mm2_metrics::MetricsArc; use mm2_number::BigDecimal; use serde_json::Value as Json; -use std::collections::HashMap; + +use crate::context::CoinsActivationContext; +use crate::prelude::TryFromCoinProtocol; +use crate::standalone_coin::{InitStandaloneCoinActivationOps, InitStandaloneCoinTaskHandle, + InitStandaloneCoinTaskManagerShared}; +use crate::utxo_activation::common_impl::{get_activation_result, priv_key_build_policy, + start_history_background_fetching}; +use crate::utxo_activation::init_utxo_standard_activation_error::InitUtxoStandardError; +use crate::utxo_activation::init_utxo_standard_statuses::{UtxoStandardAwaitingStatus, UtxoStandardInProgressStatus, + UtxoStandardUserAction}; +use crate::utxo_activation::utxo_standard_activation_result::UtxoStandardActivationResult; pub type QtumTaskManagerShared = InitStandaloneCoinTaskManagerShared; pub type QtumRpcTaskHandle = InitStandaloneCoinTaskHandle; diff --git a/mm2src/coins_activation/src/utxo_activation/init_utxo_standard_activation.rs b/mm2src/coins_activation/src/utxo_activation/init_utxo_standard_activation.rs index 342d070469..218cabe6a1 100644 --- a/mm2src/coins_activation/src/utxo_activation/init_utxo_standard_activation.rs +++ b/mm2src/coins_activation/src/utxo_activation/init_utxo_standard_activation.rs @@ -1,13 +1,5 @@ -use crate::context::CoinsActivationContext; -use crate::prelude::TryFromCoinProtocol; -use crate::standalone_coin::{InitStandaloneCoinActivationOps, InitStandaloneCoinTaskHandle, - InitStandaloneCoinTaskManagerShared}; -use crate::utxo_activation::common_impl::{get_activation_result, priv_key_build_policy, - start_history_background_fetching}; -use crate::utxo_activation::init_utxo_standard_activation_error::InitUtxoStandardError; -use crate::utxo_activation::init_utxo_standard_statuses::{UtxoStandardAwaitingStatus, UtxoStandardInProgressStatus, - UtxoStandardUserAction}; -use crate::utxo_activation::utxo_standard_activation_result::UtxoStandardActivationResult; +use std::collections::HashMap; + use async_trait::async_trait; use coins::my_tx_history_v2::TxHistoryStorage; use coins::utxo::utxo_builder::{UtxoArcBuilder, UtxoCoinBuilder}; @@ -20,7 +12,17 @@ use mm2_err_handle::prelude::*; use mm2_metrics::MetricsArc; use mm2_number::BigDecimal; use serde_json::Value as Json; -use std::collections::HashMap; + +use crate::context::CoinsActivationContext; +use crate::prelude::TryFromCoinProtocol; +use crate::standalone_coin::{InitStandaloneCoinActivationOps, InitStandaloneCoinTaskHandle, + InitStandaloneCoinTaskManagerShared}; +use crate::utxo_activation::common_impl::{get_activation_result, priv_key_build_policy, + start_history_background_fetching}; +use crate::utxo_activation::init_utxo_standard_activation_error::InitUtxoStandardError; +use crate::utxo_activation::init_utxo_standard_statuses::{UtxoStandardAwaitingStatus, UtxoStandardInProgressStatus, + UtxoStandardUserAction}; +use crate::utxo_activation::utxo_standard_activation_result::UtxoStandardActivationResult; pub type UtxoStandardTaskManagerShared = InitStandaloneCoinTaskManagerShared; pub type UtxoStandardRpcTaskHandle = InitStandaloneCoinTaskHandle; diff --git a/mm2src/coins_activation/src/utxo_activation/init_utxo_standard_activation_error.rs b/mm2src/coins_activation/src/utxo_activation/init_utxo_standard_activation_error.rs index 47894c2a6f..10e5006eb3 100644 --- a/mm2src/coins_activation/src/utxo_activation/init_utxo_standard_activation_error.rs +++ b/mm2src/coins_activation/src/utxo_activation/init_utxo_standard_activation_error.rs @@ -1,4 +1,5 @@ -use crate::standalone_coin::InitStandaloneCoinError; +use std::time::Duration; + use coins::coin_balance::EnableCoinBalanceError; use coins::hd_wallet::{NewAccountCreatingError, NewAddressDerivingError}; use coins::tx_history_storage::CreateTxHistoryStorageError; @@ -9,7 +10,8 @@ use derive_more::Display; use rpc_task::RpcTaskError; use ser_error_derive::SerializeErrorType; use serde_derive::Serialize; -use std::time::Duration; + +use crate::standalone_coin::InitStandaloneCoinError; #[derive(Clone, Display, Serialize, SerializeErrorType)] #[serde(tag = "error_type", content = "error_data")] diff --git a/mm2src/coins_activation/src/utxo_activation/init_utxo_standard_statuses.rs b/mm2src/coins_activation/src/utxo_activation/init_utxo_standard_statuses.rs index 5bf863815c..14c6217be3 100644 --- a/mm2src/coins_activation/src/utxo_activation/init_utxo_standard_statuses.rs +++ b/mm2src/coins_activation/src/utxo_activation/init_utxo_standard_statuses.rs @@ -1,7 +1,8 @@ -use crate::standalone_coin::InitStandaloneCoinInitialStatus; use crypto::hw_rpc_task::{HwRpcTaskAwaitingStatus, HwRpcTaskUserAction}; use serde_derive::Serialize; +use crate::standalone_coin::InitStandaloneCoinInitialStatus; + pub type UtxoStandardAwaitingStatus = HwRpcTaskAwaitingStatus; pub type UtxoStandardUserAction = HwRpcTaskUserAction; diff --git a/mm2src/coins_activation/src/utxo_activation/utxo_standard_activation_result.rs b/mm2src/coins_activation/src/utxo_activation/utxo_standard_activation_result.rs index aa54ec3698..93249420c4 100644 --- a/mm2src/coins_activation/src/utxo_activation/utxo_standard_activation_result.rs +++ b/mm2src/coins_activation/src/utxo_activation/utxo_standard_activation_result.rs @@ -1,8 +1,10 @@ -use crate::prelude::{CurrentBlock, GetAddressesBalances}; +use std::collections::HashMap; + use coins::coin_balance::CoinBalanceReport; use mm2_number::BigDecimal; use serde_derive::Serialize; -use std::collections::HashMap; + +use crate::prelude::{CurrentBlock, GetAddressesBalances}; #[derive(Clone, Serialize)] pub struct UtxoStandardActivationResult { diff --git a/mm2src/coins_activation/src/z_coin_activation.rs b/mm2src/coins_activation/src/z_coin_activation.rs index ba1997b1a3..fec5c0647e 100644 --- a/mm2src/coins_activation/src/z_coin_activation.rs +++ b/mm2src/coins_activation/src/z_coin_activation.rs @@ -1,8 +1,6 @@ -use crate::context::CoinsActivationContext; -use crate::prelude::*; -use crate::standalone_coin::{InitStandaloneCoinActivationOps, InitStandaloneCoinError, - InitStandaloneCoinInitialStatus, InitStandaloneCoinTaskHandle, - InitStandaloneCoinTaskManagerShared}; +use std::collections::HashMap; +use std::time::Duration; + use async_trait::async_trait; use coins::coin_balance::{CoinBalanceReport, IguanaWalletBalance}; use coins::my_tx_history_v2::TxHistoryStorage; @@ -22,8 +20,12 @@ use rpc_task::RpcTaskError; use ser_error_derive::SerializeErrorType; use serde_derive::Serialize; use serde_json::Value as Json; -use std::collections::HashMap; -use std::time::Duration; + +use crate::context::CoinsActivationContext; +use crate::prelude::*; +use crate::standalone_coin::{InitStandaloneCoinActivationOps, InitStandaloneCoinError, + InitStandaloneCoinInitialStatus, InitStandaloneCoinTaskHandle, + InitStandaloneCoinTaskManagerShared}; pub type ZcoinTaskManagerShared = InitStandaloneCoinTaskManagerShared; pub type ZcoinRpcTaskHandle = InitStandaloneCoinTaskHandle; diff --git a/mm2src/common/build.rs b/mm2src/common/build.rs index 0230591b5b..99f88c6a72 100644 --- a/mm2src/common/build.rs +++ b/mm2src/common/build.rs @@ -9,12 +9,13 @@ #![allow(uncommon_codepoints)] -use gstuff::{last_modified_sec, slurp}; use std::env::var; use std::fs; use std::io::Write; use std::path::Path; +use gstuff::{last_modified_sec, slurp}; + /// Ongoing (RLS) builds might interfere with a precise time comparison. const SLIDE: f64 = 60.; diff --git a/mm2src/common/common.rs b/mm2src/common/common.rs index 058661f42c..06397b82bf 100644 --- a/mm2src/common/common.rs +++ b/mm2src/common/common.rs @@ -125,22 +125,6 @@ pub mod wio; #[cfg(target_arch = "wasm32")] pub mod wasm; -#[cfg(target_arch = "wasm32")] pub use wasm::*; - -use backtrace::SymbolName; -use chrono::format::ParseError; -use chrono::{DateTime, Utc}; -use derive_more::Display; -pub use futures::compat::Future01CompatExt; -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}; -use sha2::{Digest, Sha256}; use std::convert::TryInto; use std::fmt::Write as FmtWrite; use std::fs::File; @@ -156,10 +140,25 @@ use std::path::PathBuf; use std::ptr::read_volatile; use std::sync::atomic::Ordering; use std::time::{Duration, SystemTime, SystemTimeError}; -use uuid::Uuid; +use backtrace::SymbolName; +use chrono::format::ParseError; +use chrono::{DateTime, Utc}; +use derive_more::Display; +pub use futures::compat::Future01CompatExt; +use futures01::{future, Future}; +use http::header::CONTENT_TYPE; +use http::Response; pub use http::StatusCode; +use parking_lot::{Mutex as PaMutex, MutexGuard as PaMutexGuard}; +use rand::RngCore; +use rand::{rngs::SmallRng, SeedableRng}; pub use serde; +use serde::{de, ser}; +use serde_json::{self as json, Value as Json}; +use sha2::{Digest, Sha256}; +use uuid::Uuid; +#[cfg(target_arch = "wasm32")] pub use wasm::*; cfg_native! { pub use gstuff::{now_float, now_ms}; diff --git a/mm2src/common/crash_reports.rs b/mm2src/common/crash_reports.rs index a749824015..a320cf60d5 100644 --- a/mm2src/common/crash_reports.rs +++ b/mm2src/common/crash_reports.rs @@ -1,5 +1,4 @@ #![allow(unused_imports)] -use crate::{log, set_panic_hook, stack_trace, stack_trace_frame, writeln}; use std::env; use std::io::stderr; use std::io::Write; @@ -8,6 +7,8 @@ use std::path::Path; use std::process::abort; use std::sync::Once; +use crate::{log, set_panic_hook, stack_trace, stack_trace_frame, writeln}; + #[cfg(windows)] #[allow(dead_code)] fn exception_name(exception_code: u32) -> &'static str { diff --git a/mm2src/common/custom_futures/repeatable.rs b/mm2src/common/custom_futures/repeatable.rs index fbc1a8c9e8..6467b8d07f 100644 --- a/mm2src/common/custom_futures/repeatable.rs +++ b/mm2src/common/custom_futures/repeatable.rs @@ -20,11 +20,6 @@ //! This happens due to the fact that the `counter` variable is not shared between attempts, //! and every time the future starts with `counter = 0`. -use crate::executor::Timer; -use crate::number_type_casting::SafeTypeCastingNumbers; -use crate::{now_ms, wait_until_ms}; -use futures::FutureExt; -use log::warn; use std::fmt; use std::future::Future; use std::marker::PhantomData; @@ -32,8 +27,14 @@ use std::pin::Pin; use std::task::{Context, Poll}; use std::time::Duration; +use futures::FutureExt; +use log::warn; pub use Action::{Ready, Retry}; +use crate::executor::Timer; +use crate::number_type_casting::SafeTypeCastingNumbers; +use crate::{now_ms, wait_until_ms}; + /// Wraps the given future into `Repeatable` future. /// The future should return [`Action`] with any `T` and `E` types. #[macro_export] @@ -394,14 +395,16 @@ fn poll_timeout(timeout_fut: &mut Option, cx: &mut Context<'_>) -> Poll<( #[cfg(test)] mod tests { - use super::*; - use crate::block_on; - use futures::lock::Mutex as AsyncMutex; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use std::time::Instant; + use futures::lock::Mutex as AsyncMutex; + + use super::*; + use crate::block_on; + async fn an_operation(counter: &AsyncMutex, finish_if: usize) -> Result { let mut counter = counter.lock().await; *counter += 1; diff --git a/mm2src/common/custom_futures/timeout.rs b/mm2src/common/custom_futures/timeout.rs index 594b07ad9e..ca9b690a33 100644 --- a/mm2src/common/custom_futures/timeout.rs +++ b/mm2src/common/custom_futures/timeout.rs @@ -1,11 +1,13 @@ -use crate::executor::Timer; -use futures::task::Poll as Poll03; -use futures::Future as Future03; use std::fmt; use std::pin::Pin; use std::task::Context; use std::time::Duration; +use futures::task::Poll as Poll03; +use futures::Future as Future03; + +use crate::executor::Timer; + #[derive(Debug)] pub struct TimeoutError { pub duration: Duration, diff --git a/mm2src/common/executor/abortable_system/abortable_queue.rs b/mm2src/common/executor/abortable_system/abortable_queue.rs index 99ffc70ca3..eec1867d33 100644 --- a/mm2src/common/executor/abortable_system/abortable_queue.rs +++ b/mm2src/common/executor/abortable_system/abortable_queue.rs @@ -1,12 +1,14 @@ +use std::future::Future as Future03; +use std::sync::Arc; + +use futures::channel::oneshot; +use futures::future::{abortable, select, Either}; +use futures::FutureExt; + use crate::executor::abortable_system::{AbortableSystem, AbortedError, InnerShared, InnerWeak, SystemInner}; use crate::executor::spawner::{SpawnAbortable, SpawnFuture}; use crate::executor::{spawn, AbortSettings, Timer}; use crate::log::{error, LogOnError}; -use futures::channel::oneshot; -use futures::future::{abortable, select, Either}; -use futures::FutureExt; -use std::future::Future as Future03; -use std::sync::Arc; const CAPACITY: usize = 1024; diff --git a/mm2src/common/executor/abortable_system/graceful_shutdown.rs b/mm2src/common/executor/abortable_system/graceful_shutdown.rs index 3feee076b2..d34a15c1f6 100644 --- a/mm2src/common/executor/abortable_system/graceful_shutdown.rs +++ b/mm2src/common/executor/abortable_system/graceful_shutdown.rs @@ -1,8 +1,10 @@ -use crate::executor::abortable_system::{AbortedError, InnerShared, SystemInner}; -use crate::executor::AbortableSystem; +use std::future::Future; + use futures::channel::oneshot; use futures::FutureExt; -use std::future::Future; + +use crate::executor::abortable_system::{AbortedError, InnerShared, SystemInner}; +use crate::executor::AbortableSystem; /// This is an `AbortableSystem` that initiates listeners for graceful shutdown /// once the `GracefulShutdownRegistry` instance is dropped. diff --git a/mm2src/common/executor/abortable_system/mod.rs b/mm2src/common/executor/abortable_system/mod.rs index b5399ad6dd..885689c843 100644 --- a/mm2src/common/executor/abortable_system/mod.rs +++ b/mm2src/common/executor/abortable_system/mod.rs @@ -1,10 +1,12 @@ -use crate::executor::spawn; -use crate::log::LogOnError; -use futures::channel::oneshot; -use parking_lot::Mutex as PaMutex; use std::fmt; use std::sync::{Arc, Weak}; +use futures::channel::oneshot; +use parking_lot::Mutex as PaMutex; + +use crate::executor::spawn; +use crate::log::LogOnError; + pub mod abortable_queue; pub mod graceful_shutdown; pub mod simple_map; @@ -66,10 +68,11 @@ pub trait SystemInner: Default + Send + 'static { #[cfg(test)] mod tests { + use abortable_queue::AbortableQueue; + use super::*; use crate::block_on; use crate::executor::{SpawnFuture, Timer}; - use abortable_queue::AbortableQueue; #[test] fn test_abort_subsystem() { diff --git a/mm2src/common/executor/abortable_system/simple_map.rs b/mm2src/common/executor/abortable_system/simple_map.rs index c7cd9fc6cd..890869e88f 100644 --- a/mm2src/common/executor/abortable_system/simple_map.rs +++ b/mm2src/common/executor/abortable_system/simple_map.rs @@ -1,14 +1,16 @@ -use crate::executor::abortable_system::{AbortableSystem, AbortedError, InnerShared, SystemInner}; -use crate::executor::{spawn_abortable, AbortOnDropHandle}; -use futures::channel::oneshot; -use futures::future::Future as Future03; -use parking_lot::{Mutex as PaMutex, MutexGuard as PaMutexGuard}; use std::borrow::Borrow; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::hash::Hash; use std::sync::Arc; +use futures::channel::oneshot; +use futures::future::Future as Future03; +use parking_lot::{Mutex as PaMutex, MutexGuard as PaMutexGuard}; + +use crate::executor::abortable_system::{AbortableSystem, AbortedError, InnerShared, SystemInner}; +use crate::executor::{spawn_abortable, AbortOnDropHandle}; + /// An alias. pub trait FutureIdTrait: 'static + Eq + Hash + Send {} diff --git a/mm2src/common/executor/native_executor.rs b/mm2src/common/executor/native_executor.rs index 6876355b88..826e3fad15 100644 --- a/mm2src/common/executor/native_executor.rs +++ b/mm2src/common/executor/native_executor.rs @@ -1,9 +1,10 @@ +use std::pin::Pin; +use std::time::Duration; + use futures::task::Context; use futures::task::Poll as Poll03; use futures::Future as Future03; use futures_timer::Delay; -use std::pin::Pin; -use std::time::Duration; /// # Important /// diff --git a/mm2src/common/executor/spawner.rs b/mm2src/common/executor/spawner.rs index 169c97ce14..189926186a 100644 --- a/mm2src/common/executor/spawner.rs +++ b/mm2src/common/executor/spawner.rs @@ -1,6 +1,7 @@ -use crate::executor::AbortSettings; use futures::Future as Future03; +use crate::executor::AbortSettings; + pub trait BoxFutureSpawner { fn spawn_boxed(&self, f: Box + Send + Unpin + 'static>); } diff --git a/mm2src/common/executor/wasm_executor.rs b/mm2src/common/executor/wasm_executor.rs index 422f564623..6076f46b7a 100644 --- a/mm2src/common/executor/wasm_executor.rs +++ b/mm2src/common/executor/wasm_executor.rs @@ -1,15 +1,17 @@ -use crate::executor::AbortOnDropHandle; -use crate::now_float; -use crate::number_type_casting::SafeTypeCastingNumbers; -use futures::future::{abortable, FutureExt}; -use futures::task::{Context, Poll}; use std::future::Future; use std::pin::Pin; use std::sync::{Arc, Mutex}; use std::task::Waker; use std::time::Duration; + +use futures::future::{abortable, FutureExt}; +use futures::task::{Context, Poll}; use wasm_bindgen::prelude::*; +use crate::executor::AbortOnDropHandle; +use crate::now_float; +use crate::number_type_casting::SafeTypeCastingNumbers; + #[wasm_bindgen] extern "C" { // https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout diff --git a/mm2src/common/jsonrpc_client.rs b/mm2src/common/jsonrpc_client.rs index 94a1ca809b..11319bb671 100644 --- a/mm2src/common/jsonrpc_client.rs +++ b/mm2src/common/jsonrpc_client.rs @@ -1,9 +1,10 @@ +use std::collections::{BTreeSet, HashMap}; +use std::fmt; + use futures01::Future; use itertools::Itertools; use serde::de::DeserializeOwned; use serde_json::{self as json, Value as Json}; -use std::collections::{BTreeSet, HashMap}; -use std::fmt; /// Macro generating functions for RPC requests. /// Args must implement/derive Serialize trait. diff --git a/mm2src/common/log.rs b/mm2src/common/log.rs index a30b0b83de..52a7bbf4c2 100644 --- a/mm2src/common/log.rs +++ b/mm2src/common/log.rs @@ -1,18 +1,5 @@ //! Human-readable logging and statuses. -use super::{now_ms, writeln}; -use crate::executor::{spawn_abortable, AbortOnDropHandle, Timer}; -use crate::filename; -use chrono::format::strftime::StrftimeItems; -use chrono::format::DelayedFormat; -use chrono::{Local, TimeZone, Utc}; -use crossbeam::queue::SegQueue; -use itertools::Itertools; -#[cfg(not(target_arch = "wasm32"))] -use lightning::util::logger::{Level as LightningLevel, Logger as LightningLogger, Record as LightningRecord}; -use log::{Level, Record}; -use parking_lot::Mutex as PaMutex; -use serde_json::Value as Json; use std::cell::RefCell; use std::collections::hash_map::DefaultHasher; use std::collections::VecDeque; @@ -28,7 +15,21 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Weak}; use std::thread; +use chrono::format::strftime::StrftimeItems; +use chrono::format::DelayedFormat; +use chrono::{Local, TimeZone, Utc}; +use crossbeam::queue::SegQueue; +use itertools::Itertools; +#[cfg(not(target_arch = "wasm32"))] +use lightning::util::logger::{Level as LightningLevel, Logger as LightningLogger, Record as LightningRecord}; pub use log::{self as log_crate, debug, error, info, trace, warn, LevelFilter}; +use log::{Level, Record}; +use parking_lot::Mutex as PaMutex; +use serde_json::Value as Json; + +use super::{now_ms, writeln}; +use crate::executor::{spawn_abortable, AbortOnDropHandle, Timer}; +use crate::filename; #[cfg(target_arch = "wasm32")] #[path = "log/wasm_log.rs"] diff --git a/mm2src/common/log/native_log.rs b/mm2src/common/log/native_log.rs index 269b9fb28f..d86d5075a2 100644 --- a/mm2src/common/log/native_log.rs +++ b/mm2src/common/log/native_log.rs @@ -1,9 +1,10 @@ -use super::{format_record, LogCallback}; use std::env; use std::io::Write; use std::os::raw::c_char; use std::str::FromStr; +use super::{format_record, LogCallback}; + #[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] pub enum LogLevel { /// A level lower than all log levels. diff --git a/mm2src/common/log/wasm_log.rs b/mm2src/common/log/wasm_log.rs index 3d7f83a16b..aa71944dd8 100644 --- a/mm2src/common/log/wasm_log.rs +++ b/mm2src/common/log/wasm_log.rs @@ -1,16 +1,16 @@ -use super::{LogCallback, LOG_CALLBACK}; -use crate::executor::spawn_local; -use crate::log::format_record; use futures::channel::mpsc; use futures::stream::StreamExt; +pub use js_sys::Function as JsFunction; use log::{set_boxed_logger, set_max_level, LevelFilter, Log, Metadata, Record}; use serde_repr::*; use wasm_bindgen::prelude::*; - -pub use js_sys::Function as JsFunction; pub use wasm_bindgen::JsValue; pub use web_sys::console; +use super::{LogCallback, LOG_CALLBACK}; +use crate::executor::spawn_local; +use crate::log::format_record; + const DEFAULT_LEVEL_FILTER: LogLevel = LogLevel::Info; #[macro_export] @@ -179,10 +179,11 @@ struct CallbackMsg { } pub fn register_wasm_log() { - use crate::log::register_callback; use std::str::FromStr; use std::sync::atomic::{AtomicBool, Ordering}; + use crate::log::register_callback; + static IS_INITIALIZED: AtomicBool = AtomicBool::new(false); // Check if the logger is initialized already diff --git a/mm2src/common/seri.rs b/mm2src/common/seri.rs index a3a8ab3cc5..d83ad4be28 100644 --- a/mm2src/common/seri.rs +++ b/mm2src/common/seri.rs @@ -1,6 +1,7 @@ -use serde::de::{self, Deserializer}; use std::fmt; +use serde::de::{self, Deserializer}; + /// Deserializes an empty string into `None`. /// Does not try to trim the string, passing `" "` will produce `Some (String::from (" "))`. /// Use with `#[serde(default, deserialize_with = "de_none_if_empty")]`. diff --git a/mm2src/common/shared_ref_counter/src/enable.rs b/mm2src/common/shared_ref_counter/src/enable.rs index 205b36aab7..58dc7bbfc8 100644 --- a/mm2src/common/shared_ref_counter/src/enable.rs +++ b/mm2src/common/shared_ref_counter/src/enable.rs @@ -1,10 +1,11 @@ -#[cfg(feature = "log")] use log::{log, Level}; use std::collections::HashMap; use std::ops::Deref; use std::panic::Location; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, RwLock, Weak}; +#[cfg(feature = "log")] use log::{log, Level}; + const LOCKING_ERROR: &str = "Error locking 'SharedRc::existing_pointers'"; const UPGRADING_ERROR: &str = "Some counter fields are dropped unexpectedly though an inner pointer is still alive"; diff --git a/mm2src/common/time_cache.rs b/mm2src/common/time_cache.rs index aafa8a6aea..197e8aed8d 100644 --- a/mm2src/common/time_cache.rs +++ b/mm2src/common/time_cache.rs @@ -20,14 +20,15 @@ //! This implements a time-based LRU cache for checking gossipsub message duplicates. -use fnv::FnvHashMap; -use instant::Instant; use std::collections::hash_map::{self, Entry::{Occupied, Vacant}, Iter, Keys}; use std::collections::VecDeque; use std::time::Duration; +use fnv::FnvHashMap; +use instant::Instant; + #[derive(Debug)] pub struct ExpiringElement { /// The element that expires diff --git a/mm2src/common/wasm.rs b/mm2src/common/wasm.rs index 2342b59383..1d76b5530b 100644 --- a/mm2src/common/wasm.rs +++ b/mm2src/common/wasm.rs @@ -1,10 +1,12 @@ -use crate::filename; +use std::fmt; + use serde::de::DeserializeOwned; use serde::Serialize; use serde_wasm_bindgen::Serializer; -use std::fmt; use wasm_bindgen::prelude::*; +use crate::filename; + /// Get only the first line of the error. /// Generally, the `JsValue` error contains the stack trace of an error. /// This function cuts off the stack trace. diff --git a/mm2src/common/wio.rs b/mm2src/common/wio.rs index 7f436f8f2b..3e5dbc7a79 100644 --- a/mm2src/common/wio.rs +++ b/mm2src/common/wio.rs @@ -1,5 +1,8 @@ //! `wio` stands for "web I/O", it contains the parts which aren't directly available with WASM. +use std::fmt; +use std::sync::Mutex; + use futures::compat::Future01CompatExt; use futures::executor::ThreadPool; use futures01::sync::oneshot::{self, Receiver}; @@ -7,8 +10,6 @@ use futures01::Future; use hyper::client::HttpConnector; use hyper::Client; use hyper_rustls::{HttpsConnector, HttpsConnectorBuilder}; -use std::fmt; -use std::sync::Mutex; use tokio::runtime::Runtime; fn start_core_thread() -> Mm2Runtime { Mm2Runtime(Runtime::new().unwrap()) } diff --git a/mm2src/crypto/src/bip32_child.rs b/mm2src/crypto/src/bip32_child.rs index 17b5064f97..c6e4584f35 100644 --- a/mm2src/crypto/src/bip32_child.rs +++ b/mm2src/crypto/src/bip32_child.rs @@ -1,10 +1,12 @@ -use crate::RpcDerivationPath; -use hw_common::primitives::{Bip32Error, ChildNumber, DerivationPath}; -use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::convert::TryFrom; use std::fmt; use std::str::FromStr; +use hw_common::primitives::{Bip32Error, ChildNumber, DerivationPath}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +use crate::RpcDerivationPath; + pub type HardenedValue = AnyValue; pub type NonHardenedValue = AnyValue; diff --git a/mm2src/crypto/src/crypto_ctx.rs b/mm2src/crypto/src/crypto_ctx.rs index 4f91448af4..dfc7d20ac0 100644 --- a/mm2src/crypto/src/crypto_ctx.rs +++ b/mm2src/crypto/src/crypto_ctx.rs @@ -1,11 +1,6 @@ -use crate::global_hd_ctx::{GlobalHDAccountArc, GlobalHDAccountCtx}; -use crate::hw_client::{HwDeviceInfo, HwProcessingError, HwPubkey, TrezorConnectProcessor}; -use crate::hw_ctx::{HardwareWalletArc, HardwareWalletCtx}; -use crate::hw_error::HwError; -#[cfg(target_arch = "wasm32")] -use crate::metamask_ctx::{MetamaskArc, MetamaskCtx, MetamaskError}; -use crate::privkey::{key_pair_from_seed, PrivKeyError}; -use crate::shared_db_id::{shared_db_id_from_seed, SharedDbIdError}; +use std::ops::Deref; +use std::sync::Arc; + use arrayref::array_ref; use common::bits256; use common::log::info; @@ -16,8 +11,15 @@ use mm2_err_handle::common_errors::InternalError; use mm2_err_handle::prelude::*; use parking_lot::RwLock; use primitives::hash::H160; -use std::ops::Deref; -use std::sync::Arc; + +use crate::global_hd_ctx::{GlobalHDAccountArc, GlobalHDAccountCtx}; +use crate::hw_client::{HwDeviceInfo, HwProcessingError, HwPubkey, TrezorConnectProcessor}; +use crate::hw_ctx::{HardwareWalletArc, HardwareWalletCtx}; +use crate::hw_error::HwError; +#[cfg(target_arch = "wasm32")] +use crate::metamask_ctx::{MetamaskArc, MetamaskCtx, MetamaskError}; +use crate::privkey::{key_pair_from_seed, PrivKeyError}; +use crate::shared_db_id::{shared_db_id_from_seed, SharedDbIdError}; pub type CryptoInitResult = Result>; diff --git a/mm2src/crypto/src/global_hd_ctx.rs b/mm2src/crypto/src/global_hd_ctx.rs index 79326e9889..29a8efa7fd 100644 --- a/mm2src/crypto/src/global_hd_ctx.rs +++ b/mm2src/crypto/src/global_hd_ctx.rs @@ -1,13 +1,15 @@ -use crate::privkey::{bip39_seed_from_passphrase, key_pair_from_secret, PrivKeyError}; -use crate::standard_hd_path::StandardHDCoinAddress; -use crate::{mm2_internal_der_path, Bip32DerPathOps, Bip32Error, CryptoInitError, CryptoInitResult, - StandardHDPathToCoin}; +use std::ops::Deref; +use std::sync::Arc; + use bip32::{ChildNumber, ExtendedPrivateKey}; use common::drop_mutability; use keys::{KeyPair, Secret as Secp256k1Secret}; use mm2_err_handle::prelude::*; -use std::ops::Deref; -use std::sync::Arc; + +use crate::privkey::{bip39_seed_from_passphrase, key_pair_from_secret, PrivKeyError}; +use crate::standard_hd_path::StandardHDCoinAddress; +use crate::{mm2_internal_der_path, Bip32DerPathOps, Bip32Error, CryptoInitError, CryptoInitResult, + StandardHDPathToCoin}; const HARDENED: bool = true; const NON_HARDENED: bool = false; diff --git a/mm2src/crypto/src/hw_client.rs b/mm2src/crypto/src/hw_client.rs index cec4f104c1..30c6cb69e9 100644 --- a/mm2src/crypto/src/hw_client.rs +++ b/mm2src/crypto/src/hw_client.rs @@ -1,6 +1,5 @@ -use crate::hw_error::HwError; -#[cfg(not(target_arch = "wasm32"))] -use crate::hw_error::HwResult; +use std::time::Duration; + use async_trait::async_trait; #[cfg(not(target_os = "ios"))] use common::custom_futures::timeout::FutureTimerExt; @@ -8,11 +7,14 @@ use derive_more::Display; use futures::FutureExt; use mm2_err_handle::prelude::*; use rpc::v1::types::H160 as H160Json; -use std::time::Duration; use trezor::client::TrezorClient; use trezor::device_info::TrezorDeviceInfo; use trezor::{TrezorError, TrezorProcessingError, TrezorRequestProcessor}; +use crate::hw_error::HwError; +#[cfg(not(target_arch = "wasm32"))] +use crate::hw_error::HwResult; + pub type HwPubkey = H160Json; #[derive(Display)] diff --git a/mm2src/crypto/src/hw_ctx.rs b/mm2src/crypto/src/hw_ctx.rs index f5dc984407..34335e154e 100644 --- a/mm2src/crypto/src/hw_ctx.rs +++ b/mm2src/crypto/src/hw_ctx.rs @@ -1,21 +1,23 @@ -use crate::hw_client::{HwClient, HwConnectionStatus, HwDeviceInfo, HwProcessingError, HwPubkey, TrezorConnectProcessor}; -use crate::hw_error::HwError; -use crate::trezor::TrezorSession; -use crate::{mm2_internal_der_path, HwWalletType}; +use std::fmt; +use std::ops::Deref; +use std::str::FromStr; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + use bitcrypto::dhash160; use common::log::warn; use hw_common::primitives::{EcdsaCurve, Secp256k1ExtendedPublicKey}; use keys::Public as PublicKey; use mm2_err_handle::prelude::*; use primitives::hash::{H160, H264}; -use std::fmt; -use std::ops::Deref; -use std::str::FromStr; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; use trezor::utxo::IGNORE_XPUB_MAGIC; use trezor::{ProcessTrezorResponse, TrezorRequestProcessor}; +use crate::hw_client::{HwClient, HwConnectionStatus, HwDeviceInfo, HwProcessingError, HwPubkey, TrezorConnectProcessor}; +use crate::hw_error::HwError; +use crate::trezor::TrezorSession; +use crate::{mm2_internal_der_path, HwWalletType}; + const MM2_INTERNAL_ECDSA_CURVE: EcdsaCurve = EcdsaCurve::Secp256k1; const MM2_TREZOR_INTERNAL_COIN: &str = "Komodo"; const SHOW_PUBKEY_ON_DISPLAY: bool = false; diff --git a/mm2src/crypto/src/hw_error.rs b/mm2src/crypto/src/hw_error.rs index 1efd4b243f..2fbd7c8c6c 100644 --- a/mm2src/crypto/src/hw_error.rs +++ b/mm2src/crypto/src/hw_error.rs @@ -1,8 +1,9 @@ +use std::time::Duration; + use derive_more::Display; use hw_common::primitives::Bip32Error; use mm2_err_handle::prelude::*; use serde::Serialize; -use std::time::Duration; use trezor::{OperationFailure, TrezorError, TrezorUserInteraction}; pub type HwResult = Result>; diff --git a/mm2src/crypto/src/hw_rpc_task.rs b/mm2src/crypto/src/hw_rpc_task.rs index 41a0516ab6..2c00fd47a1 100644 --- a/mm2src/crypto/src/hw_rpc_task.rs +++ b/mm2src/crypto/src/hw_rpc_task.rs @@ -1,16 +1,18 @@ -use crate::hw_client::{HwProcessingError, TrezorConnectProcessor}; -use crate::trezor::TrezorPinMatrix3x3Response; +use std::convert::TryFrom; +use std::time::Duration; + use async_trait::async_trait; use mm2_err_handle::prelude::*; use rpc_task::rpc_common::RpcTaskUserActionRequest; use serde::Serialize; -use std::convert::TryFrom; -use std::time::Duration; use trezor::trezor_rpc_task::{RpcTask, RpcTaskError, RpcTaskHandle, TrezorRequestStatuses, TrezorRpcTaskProcessor, TryIntoUserAction}; use trezor::user_interaction::TrezorPassphraseResponse; use trezor::{TrezorProcessingError, TrezorRequestProcessor}; +use crate::hw_client::{HwProcessingError, TrezorConnectProcessor}; +use crate::trezor::TrezorPinMatrix3x3Response; + const CONNECT_DEFAULT_TIMEOUT: Duration = Duration::from_secs(300); pub type HwRpcTaskUserActionRequest = RpcTaskUserActionRequest; diff --git a/mm2src/crypto/src/lib.rs b/mm2src/crypto/src/lib.rs index da9ff99a29..e663d9f4dc 100644 --- a/mm2src/crypto/src/lib.rs +++ b/mm2src/crypto/src/lib.rs @@ -16,7 +16,11 @@ mod xpub; // Uncomment this to finish MetaMask login. #[cfg(target_arch = "wasm32")] mod metamask_login; +use std::str::FromStr; + pub use bip32_child::{Bip32Child, Bip32DerPathError, Bip32DerPathOps, Bip44Tail}; +#[cfg(target_arch = "wasm32")] +pub use crypto_ctx::MetamaskCtxInitError; pub use crypto_ctx::{CryptoCtx, CryptoCtxError, CryptoInitError, CryptoInitResult, HwCtxInitError, KeyPairPolicy}; pub use global_hd_ctx::{derive_secp256k1_secret, GlobalHDAccountArc}; pub use hw_client::{HwClient, HwConnectionStatus, HwDeviceInfo, HwProcessingError, HwPubkey, HwWalletType, @@ -26,20 +30,15 @@ pub use hw_common::primitives::{Bip32Error, ChildNumber, DerivationPath, EcdsaCu pub use hw_ctx::{HardwareWalletArc, HardwareWalletCtx}; pub use hw_error::{from_hw_error, HwError, HwResult, HwRpcError, WithHwRpcError}; pub use keys::Secret as Secp256k1Secret; -pub use standard_hd_path::{Bip44Chain, StandardHDCoinAddress, StandardHDPath, StandardHDPathError, - StandardHDPathToAccount, StandardHDPathToCoin, UnknownChainError}; -pub use trezor; -pub use xpub::{XPubConverter, XpubError}; - -#[cfg(target_arch = "wasm32")] -pub use crypto_ctx::MetamaskCtxInitError; #[cfg(target_arch = "wasm32")] pub use metamask_ctx::{MetamaskArc, MetamaskError, MetamaskResult, MetamaskWeak}; #[cfg(target_arch = "wasm32")] pub use mm2_metamask as metamask; - use serde::de::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use std::str::FromStr; +pub use standard_hd_path::{Bip44Chain, StandardHDCoinAddress, StandardHDPath, StandardHDPathError, + StandardHDPathToAccount, StandardHDPathToCoin, UnknownChainError}; +pub use trezor; +pub use xpub::{XPubConverter, XpubError}; /// The derivation path generally consists of: /// `m/purpose'/coin_type'/account'/change/address_index`. diff --git a/mm2src/crypto/src/metamask_ctx.rs b/mm2src/crypto/src/metamask_ctx.rs index a36b957e79..1b012418cf 100644 --- a/mm2src/crypto/src/metamask_ctx.rs +++ b/mm2src/crypto/src/metamask_ctx.rs @@ -1,15 +1,16 @@ -use crate::metamask_login::{adex_eip712_request, AtomicDEXDomain, AtomicDEXLoginRequest}; +use std::ops::Deref; +use std::str::FromStr; +use std::sync::{Arc, Weak}; + use mm2_err_handle::prelude::*; use mm2_eth::address::{address_from_pubkey_uncompressed, Address}; use mm2_eth::recovery::{recover_pubkey, Signature}; use mm2_metamask::{Eip1193Provider, MetamaskSession}; -use std::ops::Deref; -use std::str::FromStr; -use std::sync::{Arc, Weak}; +pub use mm2_metamask::{MetamaskError, MetamaskResult}; use web3::types::H520; use web3::Web3; -pub use mm2_metamask::{MetamaskError, MetamaskResult}; +use crate::metamask_login::{adex_eip712_request, AtomicDEXDomain, AtomicDEXLoginRequest}; #[derive(Clone)] pub struct MetamaskArc(Arc); diff --git a/mm2src/crypto/src/metamask_login.rs b/mm2src/crypto/src/metamask_login.rs index aa156af294..bf9d090e11 100644 --- a/mm2src/crypto/src/metamask_login.rs +++ b/mm2src/crypto/src/metamask_login.rs @@ -56,12 +56,14 @@ fn adex_login_types() -> [ObjectType; 2] { } mod tests { - use super::*; - use mm2_metamask::hash_typed_data; use std::str::FromStr; + + use mm2_metamask::hash_typed_data; use wasm_bindgen_test::*; use web3::types::H256; + use super::*; + wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] diff --git a/mm2src/crypto/src/shared_db_id.rs b/mm2src/crypto/src/shared_db_id.rs index 1aff809ca9..d75c493f2f 100644 --- a/mm2src/crypto/src/shared_db_id.rs +++ b/mm2src/crypto/src/shared_db_id.rs @@ -1,10 +1,11 @@ -use crate::privkey::private_from_seed_hash; use derive_more::Display; use enum_from::EnumFromStringify; use keys::{Error as KeysError, KeyPair}; use mm2_err_handle::prelude::*; use primitives::hash::H160; +use crate::privkey::private_from_seed_hash; + /// This magic string is used to change the input mnemonic passphrase the way /// so `sha256(mnemonic + SHARED_DB_MAGIC_SALT)` const SHARED_DB_MAGIC_SALT: &str = "uVa*6pcnpc9ki+VBX.6_L."; diff --git a/mm2src/crypto/src/standard_hd_path.rs b/mm2src/crypto/src/standard_hd_path.rs index f7d29f2e8b..43099471c7 100644 --- a/mm2src/crypto/src/standard_hd_path.rs +++ b/mm2src/crypto/src/standard_hd_path.rs @@ -1,10 +1,12 @@ -use crate::bip32_child::{Bip32Child, Bip32ChildValue, Bip32DerPathError, Bip44Tail, HardenedValue, NonHardenedValue}; +use std::convert::TryFrom; + use bip32::ChildNumber; use derive_more::Display; use enum_primitive_derive::Primitive; use hw_common::primitives::Bip32Error; use num_traits::FromPrimitive; -use std::convert::TryFrom; + +use crate::bip32_child::{Bip32Child, Bip32ChildValue, Bip32DerPathError, Bip44Tail, HardenedValue, NonHardenedValue}; /// Standard HD Path for [BIP-44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki), /// [BIP-49](https://github.com/bitcoin/bips/blob/master/bip-0049.mediawiki), @@ -243,10 +245,12 @@ impl Bip32ChildValue for Bip32PurposeValue { #[cfg(test)] mod tests { + use std::str::FromStr; + + use bip32::DerivationPath; + use super::*; use crate::bip32_child::Bip32DerPathOps; - use bip32::DerivationPath; - use std::str::FromStr; #[test] fn test_from_str() { diff --git a/mm2src/crypto/src/xpub.rs b/mm2src/crypto/src/xpub.rs index 3d97168975..c1ecf1862d 100644 --- a/mm2src/crypto/src/xpub.rs +++ b/mm2src/crypto/src/xpub.rs @@ -65,9 +65,10 @@ fn has_xpub_prefix(bytes: &[u8]) -> MmResult { #[cfg(test)] mod tests { - use super::*; use std::mem; + use super::*; + #[test] fn test_xpub_check() { XPubConverter::is_standard_xpub("xpub6FZD3nMbn98RuBforZLU7N4zArVkmM2m9UwjLX4vtdmmgq8YXPyHeAhCUxFS8wuqoQ9GwSuoSyGdHNv58ZyT5a3wXwYAq83PRyWHgoaA85M").unwrap(); diff --git a/mm2src/db_common/src/sql_condition.rs b/mm2src/db_common/src/sql_condition.rs index af645df6c3..3c25286e1c 100644 --- a/mm2src/db_common/src/sql_condition.rs +++ b/mm2src/db_common/src/sql_condition.rs @@ -1,8 +1,9 @@ -use crate::sql_value::{FromQuoted, SqlValue, SqlValueOptional, SqlValueToString, SqlValuesToStrings}; -use crate::sqlite::{OwnedSqlParam, SqlParamsBuilder, ToValidSqlIdent}; use rusqlite::Result as SqlResult; use sql_builder::SqlBuilder; +use crate::sql_value::{FromQuoted, SqlValue, SqlValueOptional, SqlValueToString, SqlValuesToStrings}; +use crate::sqlite::{OwnedSqlParam, SqlParamsBuilder, ToValidSqlIdent}; + /// An SQL condition builder. pub trait SqlCondition: Sized { fn sql_builder(&mut self) -> &mut SqlBuilder; diff --git a/mm2src/db_common/src/sql_constraint.rs b/mm2src/db_common/src/sql_constraint.rs index fa1592eba6..7b6acc6468 100644 --- a/mm2src/db_common/src/sql_constraint.rs +++ b/mm2src/db_common/src/sql_constraint.rs @@ -1,10 +1,11 @@ -use crate::sqlite::StringError; -use common::write_safe::fmt::WriteJoin; -use rusqlite::{Error as SqlError, Result as SqlResult}; use std::collections::BTreeMap; use std::fmt; +use common::write_safe::fmt::WriteJoin; pub use foreign_key::ForeignKey; +use rusqlite::{Error as SqlError, Result as SqlResult}; + +use crate::sqlite::StringError; macro_rules! named_constraint { ($constraint_ident:ident, $constraint_str:literal) => { @@ -77,9 +78,10 @@ named_constraint!(Unique, "UNIQUE"); named_constraint!(PrimaryKey, "PRIMARY KEY"); pub mod foreign_key { - use super::*; use std::fmt; + use super::*; + #[macro_export] macro_rules! foreign_columns { ($($referenced_col:expr => $parent_col:expr),+ $(,)?) => { diff --git a/mm2src/db_common/src/sql_create.rs b/mm2src/db_common/src/sql_create.rs index 771232dfd8..583f24382e 100644 --- a/mm2src/db_common/src/sql_create.rs +++ b/mm2src/db_common/src/sql_create.rs @@ -1,10 +1,12 @@ -use crate::sql_constraint::SqlConstraint; -use crate::sql_value::{FromQuoted, SqlValue}; -use crate::sqlite::StringError; +use std::fmt; + use common::{write_safe, write_safe::fmt::{WriteSafe, WriteSafeJoin}}; use rusqlite::{Connection, Error as SqlError, Result as SqlResult}; -use std::fmt; + +use crate::sql_constraint::SqlConstraint; +use crate::sql_value::{FromQuoted, SqlValue}; +use crate::sqlite::StringError; pub enum SqlType { Varchar(usize), diff --git a/mm2src/db_common/src/sql_delete.rs b/mm2src/db_common/src/sql_delete.rs index eac48b9e77..6ad153234b 100644 --- a/mm2src/db_common/src/sql_delete.rs +++ b/mm2src/db_common/src/sql_delete.rs @@ -1,9 +1,10 @@ -use crate::sql_condition::SqlCondition; -use crate::sqlite::{validate_table_name, OwnedSqlParams, SqlParamsBuilder}; use common::log::debug; use rusqlite::{params_from_iter, Connection, Error as SqlError, Result as SqlResult}; use sql_builder::SqlBuilder; +use crate::sql_condition::SqlCondition; +use crate::sqlite::{validate_table_name, OwnedSqlParams, SqlParamsBuilder}; + /// A `DELETE` SQL request builder. pub struct SqlDelete<'a> { conn: &'a Connection, diff --git a/mm2src/db_common/src/sql_insert.rs b/mm2src/db_common/src/sql_insert.rs index bf6d77a5ca..1a7acb2932 100644 --- a/mm2src/db_common/src/sql_insert.rs +++ b/mm2src/db_common/src/sql_insert.rs @@ -1,10 +1,12 @@ -use crate::sql_value::{FromQuoted, SqlValueOptional, SqlValueToString}; -use crate::sqlite::{OwnedSqlParam, OwnedSqlParams, SqlParamsBuilder, ToValidSqlIdent}; +use std::fmt; + use common::write_safe; use common::write_safe::fmt::{WriteSafe, WriteSafeJoin}; use log::debug; use rusqlite::{params_from_iter, Connection, Result as SqlResult}; -use std::fmt; + +use crate::sql_value::{FromQuoted, SqlValueOptional, SqlValueToString}; +use crate::sqlite::{OwnedSqlParam, OwnedSqlParams, SqlParamsBuilder, ToValidSqlIdent}; enum InsertMode { OrReplace, diff --git a/mm2src/db_common/src/sql_query.rs b/mm2src/db_common/src/sql_query.rs index 170939c18a..1a5605af7c 100644 --- a/mm2src/db_common/src/sql_query.rs +++ b/mm2src/db_common/src/sql_query.rs @@ -1,10 +1,11 @@ +use log::debug; +use rusqlite::{params_from_iter, Connection, Error as SqlError, Result as SqlResult, Row}; +use sql_builder::SqlBuilder; + use crate::sql_condition::SqlCondition; use crate::sql_value::{SqlValue, SqlValueToString}; use crate::sqlite::{query_single_row, validate_ident, validate_table_name, OwnedSqlParam, OwnedSqlParams, SqlParamsBuilder, StringError, ToValidSqlIdent, ToValidSqlTable}; -use log::debug; -use rusqlite::{params_from_iter, Connection, Error as SqlError, Result as SqlResult, Row}; -use sql_builder::SqlBuilder; /// A `SELECT` SQL query builder. #[derive(Clone)] diff --git a/mm2src/db_common/src/sql_update.rs b/mm2src/db_common/src/sql_update.rs index 2d4dbca6f6..e4c23adc23 100644 --- a/mm2src/db_common/src/sql_update.rs +++ b/mm2src/db_common/src/sql_update.rs @@ -1,10 +1,11 @@ -use crate::sql_condition::SqlCondition; -use crate::sql_value::{FromQuoted, SqlValueOptional, SqlValueToString}; -use crate::sqlite::{validate_table_name, OwnedSqlParam, OwnedSqlParams, SqlParamsBuilder, ToValidSqlIdent}; use common::log::debug; use rusqlite::{params_from_iter, Connection, Error as SqlError, Result as SqlResult}; use sql_builder::SqlBuilder; +use crate::sql_condition::SqlCondition; +use crate::sql_value::{FromQuoted, SqlValueOptional, SqlValueToString}; +use crate::sqlite::{validate_table_name, OwnedSqlParam, OwnedSqlParams, SqlParamsBuilder, ToValidSqlIdent}; + /// An `UPDATE` SQL request builder. pub struct SqlUpdate<'a> { conn: &'a Connection, diff --git a/mm2src/db_common/src/sqlite.rs b/mm2src/db_common/src/sqlite.rs index 5da327c0fd..9c4702b0ff 100644 --- a/mm2src/db_common/src/sqlite.rs +++ b/mm2src/db_common/src/sqlite.rs @@ -1,15 +1,15 @@ #![allow(deprecated)] // TODO: remove this once rusqlite is >= 0.29 -pub use rusqlite; -pub use sql_builder; +use std::error::Error as StdError; +use std::fmt; +use std::sync::{Arc, Mutex, Weak}; use log::debug; +pub use rusqlite; use rusqlite::types::{FromSql, Type as SqlType, Value}; use rusqlite::{Connection, Error as SqlError, Result as SqlResult, Row, ToSql}; +pub use sql_builder; use sql_builder::SqlBuilder; -use std::error::Error as StdError; -use std::fmt; -use std::sync::{Arc, Mutex, Weak}; use uuid::Uuid; pub const CHECK_TABLE_EXISTS_SQL: &str = "SELECT name FROM sqlite_master WHERE type='table' AND name=?1;"; diff --git a/mm2src/derives/enum_from/src/from_inner.rs b/mm2src/derives/enum_from/src/from_inner.rs index 8fb76172db..6ad258c7ed 100644 --- a/mm2src/derives/enum_from/src/from_inner.rs +++ b/mm2src/derives/enum_from/src/from_inner.rs @@ -1,8 +1,9 @@ -use crate::{CompileError, IdentCtx, MacroAttr, UnnamedInnerField}; use proc_macro2::TokenStream as TokenStream2; use quote::quote; use syn::Variant; +use crate::{CompileError, IdentCtx, MacroAttr, UnnamedInnerField}; + /// Implement `From` trait for the given enumeration `variant`. pub(crate) fn impl_from_inner(ctx: &IdentCtx<'_>, variant: &Variant) -> Result, CompileError> { let attr_count = variant diff --git a/mm2src/derives/enum_from/src/from_stringify.rs b/mm2src/derives/enum_from/src/from_stringify.rs index 464cb216ad..b2f3850e24 100644 --- a/mm2src/derives/enum_from/src/from_stringify.rs +++ b/mm2src/derives/enum_from/src/from_stringify.rs @@ -1,4 +1,3 @@ -use crate::{get_attr_meta, CompileError, IdentCtx, MacroAttr}; use proc_macro2::{Ident, TokenStream}; use quote::__private::ext::RepToTokensExt; use quote::quote; @@ -6,6 +5,8 @@ use syn::NestedMeta::Lit; use syn::__private::TokenStream2; use syn::{ExprPath, NestedMeta, Variant}; +use crate::{get_attr_meta, CompileError, IdentCtx, MacroAttr}; + impl CompileError { /// This error constructor is involved to be used on `EnumFromStringify` macro. fn expected_literal_inner() -> CompileError { diff --git a/mm2src/derives/enum_from/src/from_trait.rs b/mm2src/derives/enum_from/src/from_trait.rs index 4179324cb9..695b5a8984 100644 --- a/mm2src/derives/enum_from/src/from_trait.rs +++ b/mm2src/derives/enum_from/src/from_trait.rs @@ -1,10 +1,11 @@ -use crate::{get_attr_meta, CompileError, IdentCtx, MacroAttr, UnnamedInnerField}; use itertools::Itertools; use proc_macro2::{Ident, TokenStream as TokenStream2}; use quote::quote; use syn::Meta::Path; use syn::{NestedMeta, Variant}; +use crate::{get_attr_meta, CompileError, IdentCtx, MacroAttr, UnnamedInnerField}; + impl CompileError { /// This error constructor is involved to be used on `EnumFromTrait` macro. pub(crate) fn expected_trait_method_path() -> CompileError { diff --git a/mm2src/derives/enum_from/src/lib.rs b/mm2src/derives/enum_from/src/lib.rs index 83aef6f6f0..142ecc783b 100644 --- a/mm2src/derives/enum_from/src/lib.rs +++ b/mm2src/derives/enum_from/src/lib.rs @@ -1,7 +1,8 @@ +use std::fmt; + use proc_macro::{self, TokenStream}; use proc_macro2::{Ident, Span, TokenStream as TokenStream2}; use quote::quote; -use std::fmt; use syn::Meta::List; use syn::{parse_macro_input, Data, DeriveInput, Error, Field, Fields, ImplGenerics, Type, TypeGenerics, WhereClause}; use syn::{Attribute, NestedMeta, Variant}; diff --git a/mm2src/derives/ser_error_derive/src/lib.rs b/mm2src/derives/ser_error_derive/src/lib.rs index 79608cc630..bb4d3e35f4 100644 --- a/mm2src/derives/ser_error_derive/src/lib.rs +++ b/mm2src/derives/ser_error_derive/src/lib.rs @@ -1,13 +1,12 @@ use proc_macro::{self, TokenStream}; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::quote; +use ser_error::CONTENT; +use ser_error::TAG; use syn::Meta::{List, NameValue, Path}; use syn::NestedMeta; use syn::{parse_macro_input, Data, DeriveInput, Error}; -use ser_error::CONTENT; -use ser_error::TAG; - const SERDE_IDENT: &str = "serde"; const TAG_ATTR: &str = "tag"; const CONTENT_ATTR: &str = "content"; diff --git a/mm2src/hw_common/src/transport/libusb.rs b/mm2src/hw_common/src/transport/libusb.rs index da33494dc5..8ba8a43899 100644 --- a/mm2src/hw_common/src/transport/libusb.rs +++ b/mm2src/hw_common/src/transport/libusb.rs @@ -1,7 +1,9 @@ //! TODO consider refactoring [`UsbDevice::connect`] not to spawn a thread for every device. //! We can spawn it once on [`UsbContext::new`], but we have to set the read/write chunk timeout to 0.5s or smaller. -use super::{send_event_recv_response, InternalError}; +use std::thread; +use std::time::{Duration, Instant}; + use common::log::error; use common::{block_on, some_or_return_ok_none}; use derive_more::Display; @@ -10,8 +12,8 @@ use futures::StreamExt; use mm2_err_handle::prelude::*; use rusb::Error as RusbError; use rusb::UsbContext as RusbContext; -use std::thread; -use std::time::{Duration, Instant}; + +use super::{send_event_recv_response, InternalError}; pub const READ_ENDPOINT_MASK: u8 = 0x80; diff --git a/mm2src/hw_common/src/transport/webusb_driver.rs b/mm2src/hw_common/src/transport/webusb_driver.rs index 14e6ad6cd8..a92e3851e7 100644 --- a/mm2src/hw_common/src/transport/webusb_driver.rs +++ b/mm2src/hw_common/src/transport/webusb_driver.rs @@ -1,4 +1,3 @@ -use crate::transport::{send_event_recv_response, InternalError}; use common::executor::{spawn_local_abortable, AbortOnDropHandle}; use common::{deserialize_from_js, log::error, serialize_to_js, stringify_js_error}; use derive_more::Display; @@ -12,6 +11,8 @@ use wasm_bindgen::JsCast; use wasm_bindgen_futures::JsFuture; use web_sys::{Usb, UsbDevice, UsbDeviceRequestOptions, UsbInTransferResult}; +use crate::transport::{send_event_recv_response, InternalError}; + pub type WebUsbResult = Result>; type EventResultSender = oneshot::Sender>; type WebUsbEventSender = mpsc::UnboundedSender; diff --git a/mm2src/mm2_bin_lib/build.rs b/mm2src/mm2_bin_lib/build.rs index c05c39a364..55b6da24ef 100644 --- a/mm2src/mm2_bin_lib/build.rs +++ b/mm2src/mm2_bin_lib/build.rs @@ -1,12 +1,13 @@ -use chrono::DateTime; -use gstuff::slurp; -use regex::Regex; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::Command; use std::str::from_utf8; +use chrono::DateTime; +use gstuff::slurp; +use regex::Regex; + fn path2s(path: PathBuf) -> String { path.to_str() .unwrap_or_else(|| panic!("Non-stringy path {:?}", path)) diff --git a/mm2src/mm2_bin_lib/src/lib.rs b/mm2src/mm2_bin_lib/src/lib.rs index 008f0d775c..8783882762 100644 --- a/mm2src/mm2_bin_lib/src/lib.rs +++ b/mm2src/mm2_bin_lib/src/lib.rs @@ -1,7 +1,8 @@ +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + use enum_primitive_derive::Primitive; use mm2_core::mm_ctx::MmArc; use mm2_main::mm2::lp_dispatcher::{dispatch_lp_event, StopCtxEvent}; -use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; #[cfg(target_arch = "wasm32")] use wasm_bindgen::prelude::*; #[cfg(not(target_arch = "wasm32"))] mod mm2_native_lib; diff --git a/mm2src/mm2_bin_lib/src/mm2_native_lib.rs b/mm2src/mm2_bin_lib/src/mm2_native_lib.rs index 5f85596311..1076b8cd44 100644 --- a/mm2src/mm2_bin_lib/src/mm2_native_lib.rs +++ b/mm2src/mm2_bin_lib/src/mm2_native_lib.rs @@ -1,4 +1,9 @@ -use super::*; +use std::ffi::{CStr, CString}; +use std::panic::catch_unwind; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::thread; +use std::time::Duration; + use common::crash_reports::init_crash_reports; use common::executor::SpawnFuture; use common::log::{register_callback, FfiCallback}; @@ -9,11 +14,8 @@ use libc::c_char; use mm2_core::mm_ctx::MmArc; use num_traits::FromPrimitive; use serde_json::{self as json}; -use std::ffi::{CStr, CString}; -use std::panic::catch_unwind; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::thread; -use std::time::Duration; + +use super::*; #[derive(Debug, PartialEq, Primitive)] enum MainErr { diff --git a/mm2src/mm2_bin_lib/src/mm2_wasm_lib.rs b/mm2src/mm2_bin_lib/src/mm2_wasm_lib.rs index 4cafd6509e..fafa97fa2f 100644 --- a/mm2src/mm2_bin_lib/src/mm2_wasm_lib.rs +++ b/mm2src/mm2_bin_lib/src/mm2_wasm_lib.rs @@ -12,7 +12,6 @@ //! but it won't be safe when wasm becomes multi-threaded. //! [blogpost]: https://rustwasm.github.io/2018/10/24/multithreading-rust-and-wasm.html -use super::*; use common::log::{register_callback, LogLevel, WasmCallback}; use common::{console_err, console_info, deserialize_from_js, executor, serialize_to_js, set_panic_hook}; use enum_primitive_derive::Primitive; @@ -22,6 +21,8 @@ use mm2_rpc::wasm_rpc::WasmRpcResponse; use serde::{Deserialize, Serialize}; use serde_json::Value as Json; +use super::*; + /// The errors can be thrown when using the `mm2_main` function incorrectly. #[wasm_bindgen] #[derive(Primitive)] diff --git a/mm2src/mm2_bitcoin/chain/src/block.rs b/mm2src/mm2_bitcoin/chain/src/block.rs index 747da3ac88..7826083221 100644 --- a/mm2src/mm2_bitcoin/chain/src/block.rs +++ b/mm2src/mm2_bitcoin/chain/src/block.rs @@ -1,10 +1,11 @@ -use super::RepresentH256; use hash::H256; use hex::FromHex; use merkle_root::merkle_root; use ser::deserialize; use {BlockHeader, Transaction}; +use super::RepresentH256; + #[derive(Debug, PartialEq, Clone, Serializable, Deserializable)] pub struct Block { pub block_header: BlockHeader, @@ -55,11 +56,12 @@ impl Block { #[cfg(test)] mod tests { - use super::Block; use hash::H256; use hex::FromHex; use ser::deserialize; + use super::Block; + // Block 80000 // https://blockchain.info/rawblock/000000000043a8c0fd1d6f726790caa2a406010d19efd2780db27bdbbd93baf6 // https://blockchain.info/rawblock/000000000043a8c0fd1d6f726790caa2a406010d19efd2780db27bdbbd93baf6?format=hex diff --git a/mm2src/mm2_bitcoin/chain/src/block_header.rs b/mm2src/mm2_bitcoin/chain/src/block_header.rs index 2fce20a799..bfae117d2c 100644 --- a/mm2src/mm2_bitcoin/chain/src/block_header.rs +++ b/mm2src/mm2_bitcoin/chain/src/block_header.rs @@ -1,3 +1,5 @@ +use std::io; + use compact::Compact; use crypto::dhash256; #[cfg(not(target_arch = "wasm32"))] @@ -9,7 +11,6 @@ use hex::FromHex; use primitives::bytes::Bytes; use primitives::U256; use ser::{deserialize, serialize, CoinVariant, Deserializable, Reader, Serializable, Stream}; -use std::io; use transaction::{deserialize_tx, TxType}; use {OutPoint, Transaction}; @@ -379,7 +380,6 @@ impl From for ExtBlockHeader { #[cfg(test)] mod tests { - use super::ExtBlockHeader; use block_header::{BlockHeader, BlockHeaderBits, BlockHeaderNonce, AUX_POW_VERSION_DOGE, AUX_POW_VERSION_NMC, AUX_POW_VERSION_SYS, BIP9_NO_SOFT_FORK_BLOCK_HEADER_VERSION, KAWPOW_VERSION, MTP_POW_VERSION, PROG_POW_SWITCH_TIME}; @@ -387,6 +387,8 @@ mod tests { use primitives::bytes::Bytes; use ser::{deserialize, serialize, serialize_list, CoinVariant, Error as ReaderError, Reader, Stream}; + use super::ExtBlockHeader; + #[test] fn test_block_header_stream() { let block_header = BlockHeader { diff --git a/mm2src/mm2_bitcoin/chain/src/lib.rs b/mm2src/mm2_bitcoin/chain/src/lib.rs index 58133355bf..2989ebd27f 100644 --- a/mm2src/mm2_bitcoin/chain/src/lib.rs +++ b/mm2src/mm2_bitcoin/chain/src/lib.rs @@ -22,14 +22,12 @@ pub trait RepresentH256 { fn h256(&self) -> hash::H256; } -pub use primitives::{bytes, compact, hash, U256}; - pub use block::Block; pub use block_header::{BlockHeader, BlockHeaderBits, BlockHeaderNonce}; pub use merkle_root::{merkle_node_hash, merkle_root}; +pub use primitives::{bytes, compact, hash, U256}; +pub use read_and_hash::{HashedData, ReadAndHash}; pub use transaction::{JoinSplit, OutPoint, ShieldedOutput, ShieldedSpend, Transaction, TransactionInput, TransactionOutput, TxHashAlgo}; -pub use read_and_hash::{HashedData, ReadAndHash}; - pub type ShortTransactionId = hash::H48; diff --git a/mm2src/mm2_bitcoin/chain/src/merkle_root.rs b/mm2src/mm2_bitcoin/chain/src/merkle_root.rs index 2be5acc4a9..17703a0670 100644 --- a/mm2src/mm2_bitcoin/chain/src/merkle_root.rs +++ b/mm2src/mm2_bitcoin/chain/src/merkle_root.rs @@ -48,9 +48,10 @@ where #[cfg(test)] mod tests { - use super::merkle_root; use hash::H256; + use super::merkle_root; + // block 80_000 // https://blockchain.info/block/000000000043a8c0fd1d6f726790caa2a406010d19efd2780db27bdbbd93baf6 #[test] diff --git a/mm2src/mm2_bitcoin/chain/src/read_and_hash.rs b/mm2src/mm2_bitcoin/chain/src/read_and_hash.rs index 72467144b4..2f1cb29757 100644 --- a/mm2src/mm2_bitcoin/chain/src/read_and_hash.rs +++ b/mm2src/mm2_bitcoin/chain/src/read_and_hash.rs @@ -1,7 +1,8 @@ +use std::io; + use crypto::dhash256; use hash::H256; use ser::{Deserializable, Error as ReaderError, Reader}; -use std::io; pub struct HashedData { pub size: usize, diff --git a/mm2src/mm2_bitcoin/chain/src/transaction.rs b/mm2src/mm2_bitcoin/chain/src/transaction.rs index ca75eaa1ad..fcdf5542e0 100644 --- a/mm2src/mm2_bitcoin/chain/src/transaction.rs +++ b/mm2src/mm2_bitcoin/chain/src/transaction.rs @@ -1,6 +1,9 @@ //! Bitcoin transaction. //! https://en.bitcoin.it/wiki/Protocol_documentation#tx +use std::io; +use std::io::Read; + use bytes::Bytes; use constants::{LOCKTIME_THRESHOLD, SEQUENCE_FINAL}; use crypto::{dhash256, sha256}; @@ -14,8 +17,6 @@ use hash::{CipherText, EncCipherText, OutCipherText, ZkProof, ZkProofSapling, H2 use hex::FromHex; use ser::{deserialize, serialize, serialize_with_flags, SERIALIZE_TRANSACTION_WITNESS}; use ser::{CompactInteger, Deserializable, Error, Reader, Serializable, Stream}; -use std::io; -use std::io::Read; /// Must be zero. const WITNESS_MARKER: u8 = 0; @@ -583,12 +584,13 @@ impl Deserializable for Transaction { #[cfg(test)] mod tests { - use super::{Bytes, ExtTransaction, OutPoint, Transaction, TransactionInput, TransactionOutput}; use hash::{H256, H512}; use hex::ToHex; use ser::{deserialize, serialize, serialize_with_flags, Serializable, SERIALIZE_TRANSACTION_WITNESS}; use TxHashAlgo; + use super::{Bytes, ExtTransaction, OutPoint, Transaction, TransactionInput, TransactionOutput}; + // real transaction from block 80000 // https://blockchain.info/rawtx/5a4ebf66822b0b2d56bd9dc64ece0bc38ee7844a23ff1d7320a88c5fdb2ad3e2 // https://blockchain.info/rawtx/5a4ebf66822b0b2d56bd9dc64ece0bc38ee7844a23ff1d7320a88c5fdb2ad3e2?format=hex diff --git a/mm2src/mm2_bitcoin/crypto/src/lib.rs b/mm2src/mm2_bitcoin/crypto/src/lib.rs index afaa9e4102..825912f0ea 100644 --- a/mm2src/mm2_bitcoin/crypto/src/lib.rs +++ b/mm2src/mm2_bitcoin/crypto/src/lib.rs @@ -7,6 +7,8 @@ extern crate sha2; extern crate sha3; extern crate siphasher; +use std::hash::Hasher; + use groestl::Groestl512; use primitives::hash::{H160, H256, H32, H512}; use ripemd160::{Digest, Ripemd160}; @@ -14,7 +16,6 @@ use sha1::Sha1; use sha2::Sha256; use sha3::Keccak256; use siphasher::sip::SipHasher24; -use std::hash::Hasher; /// Enum representing different variants of checksum calculation /// Most coins use double sha256 @@ -110,11 +111,12 @@ pub fn checksum(data: &[u8], sum_type: &ChecksumType) -> H32 { #[cfg(test)] mod tests { - use super::{checksum, dhash160, dhash256, ripemd160, sha1, sha256, siphash24}; use primitives::bytes::Bytes; use primitives::hash::{H160, H256, H32}; use ChecksumType; + use super::{checksum, dhash160, dhash256, ripemd160, sha1, sha256, siphash24}; + #[test] fn test_ripemd160() { let expected: H160 = "108f07b8382412612c048d07d13f814118445acd".into(); diff --git a/mm2src/mm2_bitcoin/keys/src/address.rs b/mm2src/mm2_bitcoin/keys/src/address.rs index 1b37b0f568..5ce798d275 100644 --- a/mm2src/mm2_bitcoin/keys/src/address.rs +++ b/mm2src/mm2_bitcoin/keys/src/address.rs @@ -5,13 +5,14 @@ //! //! https://en.bitcoin.it/wiki/Address +use std::fmt; +use std::ops::Deref; +use std::str::FromStr; + use base58::{FromBase58, ToBase58}; use crypto::{checksum, dgroestl512, dhash256, keccak256, ChecksumType}; use derive_more::Display; use serde::{Deserialize, Serialize}; -use std::fmt; -use std::ops::Deref; -use std::str::FromStr; use {AddressHashEnum, CashAddrType, CashAddress, DisplayLayout, Error, SegwitAddress}; /// There are two address formats currently in use. diff --git a/mm2src/mm2_bitcoin/keys/src/display.rs b/mm2src/mm2_bitcoin/keys/src/display.rs index f1139d1afb..bef4c973c7 100644 --- a/mm2src/mm2_bitcoin/keys/src/display.rs +++ b/mm2src/mm2_bitcoin/keys/src/display.rs @@ -1,4 +1,5 @@ use std::ops::Deref; + use Error; pub trait DisplayLayout { diff --git a/mm2src/mm2_bitcoin/keys/src/error.rs b/mm2src/mm2_bitcoin/keys/src/error.rs index fefafc2b83..0dad04923e 100644 --- a/mm2src/mm2_bitcoin/keys/src/error.rs +++ b/mm2src/mm2_bitcoin/keys/src/error.rs @@ -1,6 +1,7 @@ -use secp256k1::Error as SecpError; use std::fmt; +use secp256k1::Error as SecpError; + #[derive(Debug, PartialEq, Serialize)] pub enum Error { InvalidPublic, diff --git a/mm2src/mm2_bitcoin/keys/src/keypair.rs b/mm2src/mm2_bitcoin/keys/src/keypair.rs index 0e29150f60..93b57250ad 100644 --- a/mm2src/mm2_bitcoin/keys/src/keypair.rs +++ b/mm2src/mm2_bitcoin/keys/src/keypair.rs @@ -1,12 +1,14 @@ //! Bitcoin key pair. -use crate::SECP_SIGN; +use std::fmt; + use crypto::ChecksumType; use hash::{H264, H520}; use secp256k1::{PublicKey, SecretKey}; -use std::fmt; use {Error, Private, Public, Secret}; +use crate::SECP_SIGN; + #[derive(Clone, Copy, Default, PartialEq)] pub struct KeyPair { private: Private, @@ -95,9 +97,10 @@ impl KeyPair { #[cfg(test)] mod tests { - use super::KeyPair; use crypto::dhash256; + use super::KeyPair; + /// Tests from: /// https://github.com/bitcoin/bitcoin/blob/a6a860796a44a2805a58391a009ba22752f64e32/src/test/key_tests.cpp const SECRET_0: &str = "5KSCKP8NUyBZPCCQusxRwgmz9sfvJQEgbGukmmHepWw5Bzp95mu"; diff --git a/mm2src/mm2_bitcoin/keys/src/lib.rs b/mm2src/mm2_bitcoin/keys/src/lib.rs index af93a421ea..d98a0d8579 100644 --- a/mm2src/mm2_bitcoin/keys/src/lib.rs +++ b/mm2src/mm2_bitcoin/keys/src/lib.rs @@ -22,24 +22,23 @@ mod public; mod segwitaddress; mod signature; -pub use primitives::{bytes, hash}; +use std::fmt; pub use address::{Address, AddressFormat, Type}; pub use cashaddress::{AddressType as CashAddrType, CashAddress, NetworkPrefix}; pub use display::DisplayLayout; pub use error::Error; +use hash::{H160, H256}; pub use keypair::KeyPair; +use lazy_static::lazy_static; pub use network::Network; +pub use primitives::{bytes, hash}; pub use private::Private; pub use public::Public; +use secp256k1::{Secp256k1, SignOnly, VerifyOnly}; pub use segwitaddress::SegwitAddress; pub use signature::{CompactSignature, Signature}; -use hash::{H160, H256}; -use lazy_static::lazy_static; -use secp256k1::{Secp256k1, SignOnly, VerifyOnly}; -use std::fmt; - /// 32 bytes long secret key pub type Secret = H256; /// 32 bytes long signable message diff --git a/mm2src/mm2_bitcoin/keys/src/private.rs b/mm2src/mm2_bitcoin/keys/src/private.rs index c60d9e7af1..9e12f3b17e 100644 --- a/mm2src/mm2_bitcoin/keys/src/private.rs +++ b/mm2src/mm2_bitcoin/keys/src/private.rs @@ -1,15 +1,17 @@ //! Secret with additional network identifier and format type -use crate::SECP_SIGN; +use std::fmt; +use std::str::FromStr; + use address::detect_checksum; use base58::{FromBase58, ToBase58}; use crypto::{checksum, ChecksumType}; use hex::ToHex; use secp256k1::{Message as SecpMessage, SecretKey}; -use std::fmt; -use std::str::FromStr; use {DisplayLayout, Error, Message, Secret, Signature}; +use crate::SECP_SIGN; + /// Secret with additional network prefix and format type #[derive(Clone, Copy, Default, PartialEq)] pub struct Private { @@ -121,9 +123,10 @@ impl From<&'static str> for Private { #[cfg(test)] mod tests { - use super::{ChecksumType, Private}; use hash::H256; + use super::{ChecksumType, Private}; + #[test] fn test_private_to_string() { let private = Private { diff --git a/mm2src/mm2_bitcoin/keys/src/public.rs b/mm2src/mm2_bitcoin/keys/src/public.rs index b57f376ee9..9fb02d305d 100644 --- a/mm2src/mm2_bitcoin/keys/src/public.rs +++ b/mm2src/mm2_bitcoin/keys/src/public.rs @@ -1,12 +1,14 @@ -use crate::SECP_VERIFY; +use std::{fmt, ops}; + use crypto::dhash160; use hash::{H160, H264, H520}; use hex::ToHex; use secp256k1::{recovery::{RecoverableSignature, RecoveryId}, Message as SecpMessage, PublicKey, Signature as SecpSignature}; -use std::{fmt, ops}; use {CompactSignature, Error, Message, Signature}; +use crate::SECP_VERIFY; + /// Secret public key #[derive(Copy, Clone)] pub enum Public { diff --git a/mm2src/mm2_bitcoin/keys/src/segwitaddress.rs b/mm2src/mm2_bitcoin/keys/src/segwitaddress.rs index eb8112e238..bccaf735c6 100644 --- a/mm2src/mm2_bitcoin/keys/src/segwitaddress.rs +++ b/mm2src/mm2_bitcoin/keys/src/segwitaddress.rs @@ -185,11 +185,12 @@ impl FromStr for SegwitAddress { #[cfg(test)] mod tests { - use super::*; use crypto::sha256; use hex::ToHex; use Public; + use super::*; + fn hex_to_bytes(s: &str) -> Option> { if s.len() % 2 == 0 { (0..s.len()) diff --git a/mm2src/mm2_bitcoin/keys/src/signature.rs b/mm2src/mm2_bitcoin/keys/src/signature.rs index 46edce268f..2404c62f9b 100644 --- a/mm2src/mm2_bitcoin/keys/src/signature.rs +++ b/mm2src/mm2_bitcoin/keys/src/signature.rs @@ -2,9 +2,10 @@ //! //! http://bitcoin.stackexchange.com/q/12554/40688 +use std::{fmt, ops, str}; + use hash::H520; use hex::{FromHex, ToHex}; -use std::{fmt, ops, str}; use Error; #[derive(PartialEq, Clone)] diff --git a/mm2src/mm2_bitcoin/primitives/src/bytes.rs b/mm2src/mm2_bitcoin/primitives/src/bytes.rs index 95f249e431..864b6366b4 100644 --- a/mm2src/mm2_bitcoin/primitives/src/bytes.rs +++ b/mm2src/mm2_bitcoin/primitives/src/bytes.rs @@ -1,8 +1,9 @@ //! Wrapper around `Vec` -use hex::{FromHex, FromHexError, ToHex}; use std::{fmt, io, marker, ops, str}; +use hex::{FromHex, FromHexError, ToHex}; + /// Wrapper around `Vec` #[derive(Default, PartialEq, Clone, Eq, Hash)] pub struct Bytes(Vec); diff --git a/mm2src/mm2_bitcoin/primitives/src/hash.rs b/mm2src/mm2_bitcoin/primitives/src/hash.rs index 46f86df4d4..90efdbb8f3 100644 --- a/mm2src/mm2_bitcoin/primitives/src/hash.rs +++ b/mm2src/mm2_bitcoin/primitives/src/hash.rs @@ -1,10 +1,11 @@ //! Fixed-size hashes -use bitcoin_hashes::{sha256d, Hash as ExtHash}; -use hex::{FromHex, FromHexError, ToHex}; use std::hash::{Hash, Hasher}; use std::{cmp, fmt, ops, str}; +use bitcoin_hashes::{sha256d, Hash as ExtHash}; +use hex::{FromHex, FromHexError, ToHex}; + macro_rules! impl_hash { ($name: ident, $size: expr) => { #[derive(Copy)] diff --git a/mm2src/mm2_bitcoin/rpc/src/v1/types/address.rs b/mm2src/mm2_bitcoin/rpc/src/v1/types/address.rs index 6147430821..bc24891115 100644 --- a/mm2src/mm2_bitcoin/rpc/src/v1/types/address.rs +++ b/mm2src/mm2_bitcoin/rpc/src/v1/types/address.rs @@ -1,7 +1,8 @@ +use std::fmt; + use keys::Address; use serde::de::{Unexpected, Visitor}; use serde::{Deserializer, Serialize, Serializer}; -use std::fmt; pub fn serialize(address: &Address, serializer: S) -> Result where @@ -36,11 +37,12 @@ impl<'b> Visitor<'b> for AddressVisitor { } pub mod vec { - use super::AddressVisitor; use keys::Address; use serde::de::Visitor; use serde::{Deserialize, Deserializer, Serialize, Serializer}; + use super::AddressVisitor; + pub fn serialize(addresses: &[Address], serializer: S) -> Result where S: Serializer, diff --git a/mm2src/mm2_bitcoin/rpc/src/v1/types/block_template_request.rs b/mm2src/mm2_bitcoin/rpc/src/v1/types/block_template_request.rs index 3380d99815..00dbd15c1f 100644 --- a/mm2src/mm2_bitcoin/rpc/src/v1/types/block_template_request.rs +++ b/mm2src/mm2_bitcoin/rpc/src/v1/types/block_template_request.rs @@ -30,9 +30,10 @@ pub struct BlockTemplateRequest { #[cfg(test)] mod tests { - use super::*; use serde_json; + use super::*; + #[test] fn block_template_request_mode_serialize() { assert_eq!( diff --git a/mm2src/mm2_bitcoin/rpc/src/v1/types/bytes.rs b/mm2src/mm2_bitcoin/rpc/src/v1/types/bytes.rs index 2305264580..cff0307b72 100644 --- a/mm2src/mm2_bitcoin/rpc/src/v1/types/bytes.rs +++ b/mm2src/mm2_bitcoin/rpc/src/v1/types/bytes.rs @@ -1,9 +1,10 @@ +///! Serializable wrapper around vector of bytes +use std::{fmt, ops}; + use hex::{FromHex, ToHex}; use primitives::bytes::Bytes as GlobalBytes; use serde::de::{Error, Visitor}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -///! Serializable wrapper around vector of bytes -use std::{fmt, ops}; /// Wrapper structure around vector of bytes. #[derive(Debug, PartialEq, Eq, Default, Hash, Clone)] @@ -95,10 +96,11 @@ impl ::core::fmt::LowerHex for Bytes { #[cfg(test)] mod tests { - use super::*; use hex::FromHex; use serde_json; + use super::*; + #[test] fn test_bytes_serialize() { let bytes = Bytes("0123456789abcdef".from_hex().unwrap()); diff --git a/mm2src/mm2_bitcoin/rpc/src/v1/types/get_block_response.rs b/mm2src/mm2_bitcoin/rpc/src/v1/types/get_block_response.rs index ba29704208..cd88617021 100644 --- a/mm2src/mm2_bitcoin/rpc/src/v1/types/get_block_response.rs +++ b/mm2src/mm2_bitcoin/rpc/src/v1/types/get_block_response.rs @@ -1,7 +1,8 @@ +use serde::{Serialize, Serializer}; + use super::block::RawBlock; use super::hash::H256; use super::uint::U256; -use serde::{Serialize, Serializer}; /// Response to getblock RPC request #[derive(Debug)] @@ -113,11 +114,12 @@ impl Serialize for GetBlockResponse { #[cfg(test)] mod tests { + use serde_json; + use super::super::bytes::Bytes; use super::super::hash::H256; use super::super::uint::U256; use super::*; - use serde_json; #[test] fn verbose_block_serialize() { diff --git a/mm2src/mm2_bitcoin/rpc/src/v1/types/get_tx_out_response.rs b/mm2src/mm2_bitcoin/rpc/src/v1/types/get_tx_out_response.rs index f6de8226ca..4898231217 100644 --- a/mm2src/mm2_bitcoin/rpc/src/v1/types/get_tx_out_response.rs +++ b/mm2src/mm2_bitcoin/rpc/src/v1/types/get_tx_out_response.rs @@ -22,12 +22,13 @@ pub struct GetTxOutResponse { #[cfg(test)] mod tests { + use serde_json; + use super::super::bytes::Bytes; use super::super::hash::H256; use super::super::script::ScriptType; use super::super::transaction::TransactionOutputScript; use super::*; - use serde_json; #[test] fn tx_out_response_serialize() { diff --git a/mm2src/mm2_bitcoin/rpc/src/v1/types/hash.rs b/mm2src/mm2_bitcoin/rpc/src/v1/types/hash.rs index 1911d11781..8050c12778 100644 --- a/mm2src/mm2_bitcoin/rpc/src/v1/types/hash.rs +++ b/mm2src/mm2_bitcoin/rpc/src/v1/types/hash.rs @@ -1,13 +1,14 @@ +use std::cmp::Ordering; +use std::fmt; +use std::hash::{Hash, Hasher}; +use std::str::FromStr; + use hex::{FromHex, ToHex}; use primitives::hash::H160 as GlobalH160; use primitives::hash::H256 as GlobalH256; use primitives::hash::H264 as GlobalH264; use serde; use serde::de::Unexpected; -use std::cmp::Ordering; -use std::fmt; -use std::hash::{Hash, Hasher}; -use std::str::FromStr; macro_rules! impl_hash { ($name: ident, $other: ident, $size: expr) => { @@ -173,10 +174,12 @@ impl H256 { #[cfg(test)] mod tests { - use super::H256; - use primitives::hash::H256 as GlobalH256; use std::str::FromStr; + use primitives::hash::H256 as GlobalH256; + + use super::H256; + #[test] fn hash_debug() { let str_reversed = "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048"; diff --git a/mm2src/mm2_bitcoin/rpc/src/v1/types/script.rs b/mm2src/mm2_bitcoin/rpc/src/v1/types/script.rs index dfc51b8866..e44ba5257f 100644 --- a/mm2src/mm2_bitcoin/rpc/src/v1/types/script.rs +++ b/mm2src/mm2_bitcoin/rpc/src/v1/types/script.rs @@ -1,7 +1,8 @@ +use std::fmt; + use global_script::ScriptType as GlobalScriptType; use serde::de::Unexpected; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use std::fmt; #[derive(Clone, Debug, PartialEq)] pub enum ScriptType { @@ -110,9 +111,10 @@ impl<'a> Deserialize<'a> for ScriptType { #[cfg(test)] mod tests { - use super::ScriptType; use serde_json; + use super::ScriptType; + #[test] fn script_type_serialize() { assert_eq!( diff --git a/mm2src/mm2_bitcoin/rpc/src/v1/types/transaction.rs b/mm2src/mm2_bitcoin/rpc/src/v1/types/transaction.rs index 89bc7d3e01..261a000b83 100644 --- a/mm2src/mm2_bitcoin/rpc/src/v1/types/transaction.rs +++ b/mm2src/mm2_bitcoin/rpc/src/v1/types/transaction.rs @@ -1,12 +1,14 @@ -use super::bytes::Bytes; -use super::hash::H256; -use super::script::ScriptType; +use std::fmt; + use keys::Address; use serde::ser::SerializeMap; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use std::fmt; use v1::types; +use super::bytes::Bytes; +use super::hash::H256; +use super::script::ScriptType; + /// Hex-encoded transaction pub type RawTransaction = Bytes; @@ -317,13 +319,15 @@ impl<'a> Deserialize<'a> for TransactionOutputs { #[cfg(test)] mod tests { + use std::collections::HashMap; + + use lazy_static::lazy_static; + use serde_json; + use super::super::bytes::Bytes; use super::super::hash::H256; use super::super::script::ScriptType; use super::*; - use lazy_static::lazy_static; - use serde_json; - use std::collections::HashMap; const TRANSACTIONS_STR: &str = include_str!("../../for_tests/txTestVectors.json"); diff --git a/mm2src/mm2_bitcoin/rpc/src/v1/types/uint.rs b/mm2src/mm2_bitcoin/rpc/src/v1/types/uint.rs index 5fd7abf4c8..bf9f56d6c0 100644 --- a/mm2src/mm2_bitcoin/rpc/src/v1/types/uint.rs +++ b/mm2src/mm2_bitcoin/rpc/src/v1/types/uint.rs @@ -1,8 +1,9 @@ +use std::fmt; +use std::str::FromStr; + use primitives::U256 as GlobalU256; use serde; use serde::de::Unexpected; -use std::fmt; -use std::str::FromStr; macro_rules! impl_uint { ($name: ident, $other: ident, $size: expr) => { @@ -85,9 +86,10 @@ impl_uint!(U256, GlobalU256, 4); #[cfg(test)] mod tests { - use super::U256; use serde_json; + use super::U256; + #[test] fn u256_serialize() { let u256 = U256::from(256); diff --git a/mm2src/mm2_bitcoin/script/src/error.rs b/mm2src/mm2_bitcoin/script/src/error.rs index 7231ebb05d..9eb665fbf0 100644 --- a/mm2src/mm2_bitcoin/script/src/error.rs +++ b/mm2src/mm2_bitcoin/script/src/error.rs @@ -1,6 +1,7 @@ //! Interpreter errors use std::fmt; + use Opcode; /// Interpreter errors diff --git a/mm2src/mm2_bitcoin/script/src/num.rs b/mm2src/mm2_bitcoin/script/src/num.rs index 5d98826a93..689727d792 100644 --- a/mm2src/mm2_bitcoin/script/src/num.rs +++ b/mm2src/mm2_bitcoin/script/src/num.rs @@ -1,7 +1,8 @@ //! Script numeric -use bytes::Bytes; use std::ops; + +use bytes::Bytes; use Error; /// Script numeric diff --git a/mm2src/mm2_bitcoin/script/src/opcode.rs b/mm2src/mm2_bitcoin/script/src/opcode.rs index 7633899668..3a1024ccf4 100644 --- a/mm2src/mm2_bitcoin/script/src/opcode.rs +++ b/mm2src/mm2_bitcoin/script/src/opcode.rs @@ -1,7 +1,8 @@ //! Script opcodes. -use flags::VerificationFlags; use std::fmt; +use flags::VerificationFlags; + /// Script opcodes. #[repr(u8)] #[allow(non_camel_case_types)] diff --git a/mm2src/mm2_bitcoin/script/src/script.rs b/mm2src/mm2_bitcoin/script/src/script.rs index a644f00ed4..3147357f2b 100644 --- a/mm2src/mm2_bitcoin/script/src/script.rs +++ b/mm2src/mm2_bitcoin/script/src/script.rs @@ -1,8 +1,9 @@ //! Serialized script, used inside transaction inputs and outputs. +use std::{fmt, ops}; + use bytes::Bytes; use keys::{self, AddressHashEnum, Public}; -use std::{fmt, ops}; use {Error, Opcode}; /// Maximum number of public keys per multisig @@ -607,11 +608,12 @@ pub fn is_witness_commitment_script(script: &[u8]) -> bool { #[cfg(test)] mod tests { - use super::{Script, ScriptAddress, ScriptType}; use crypto::ChecksumType; use keys::{Address, Public}; use {Builder, Error, Opcode}; + use super::{Script, ScriptAddress, ScriptType}; + /// Maximum number of bytes pushable to the stack const MAX_SCRIPT_ELEMENT_SIZE: usize = 52; diff --git a/mm2src/mm2_bitcoin/script/src/sign.rs b/mm2src/mm2_bitcoin/script/src/sign.rs index 1bd01127a4..d0ce87756b 100644 --- a/mm2src/mm2_bitcoin/script/src/sign.rs +++ b/mm2src/mm2_bitcoin/script/src/sign.rs @@ -622,8 +622,6 @@ fn blake_2b_256_personal(input: &[u8], personal: &[u8]) -> H256 { #[cfg(test)] mod tests { - use super::{blake_2b_256_personal, Sighash, SighashBase, SignatureVersion, TransactionInputSigner, - UnsignedTransactionInput}; use bytes::Bytes; use chain::{OutPoint, Transaction, TransactionOutput}; use hash::{H160, H256}; @@ -632,6 +630,9 @@ mod tests { use ser::deserialize; use sign::SignerHashAlgo; + use super::{blake_2b_256_personal, Sighash, SighashBase, SignatureVersion, TransactionInputSigner, + UnsignedTransactionInput}; + // http://www.righto.com/2014/02/bitcoins-hard-way-using-raw-bitcoin.html // https://blockchain.info/rawtx/81b4c832d70cb56ff957589752eb4125a4cab78a25a8fc52d6a09e5bd4404d48 // https://blockchain.info/rawtx/3f285f083de7c0acabd9f106a43ec42687ab0bebe2e6f0d529db696794540fea diff --git a/mm2src/mm2_bitcoin/script/src/stack.rs b/mm2src/mm2_bitcoin/script/src/stack.rs index 924f292845..aa4cfe03e8 100644 --- a/mm2src/mm2_bitcoin/script/src/stack.rs +++ b/mm2src/mm2_bitcoin/script/src/stack.rs @@ -1,4 +1,5 @@ use std::ops; + use Error; #[derive(Debug, Default, PartialEq, Clone)] @@ -145,9 +146,10 @@ impl Stack { #[cfg(test)] mod tests { - use super::Stack; use Error; + use super::Stack; + #[test] fn test_stack_require() { let stack: Stack = vec![].into(); diff --git a/mm2src/mm2_bitcoin/serialization/src/compact_integer.rs b/mm2src/mm2_bitcoin/serialization/src/compact_integer.rs index 840145cabd..a36c8b3c9b 100644 --- a/mm2src/mm2_bitcoin/serialization/src/compact_integer.rs +++ b/mm2src/mm2_bitcoin/serialization/src/compact_integer.rs @@ -1,6 +1,7 @@ //! Variable-length integer commonly used in the Bitcoin [P2P protocol](https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers) use std::{fmt, io}; + use {Deserializable, Error as ReaderError, Reader, Serializable, Stream}; #[derive(Debug, PartialEq, Eq, Clone)] @@ -155,10 +156,11 @@ impl Deserializable for CompactInteger { #[cfg(test)] mod tests { - use super::{parse_compact_int, CompactInteger, CompactIntegerError}; use test_helpers::hex::force_deserialize_hex; use {Error as ReaderError, Reader, Stream}; + use super::{parse_compact_int, CompactInteger, CompactIntegerError}; + #[test] fn test_compact_integer_data_length() { let input: u8 = 1; diff --git a/mm2src/mm2_bitcoin/serialization/src/impls.rs b/mm2src/mm2_bitcoin/serialization/src/impls.rs index 80c037ce93..f29d92ede8 100644 --- a/mm2src/mm2_bitcoin/serialization/src/impls.rs +++ b/mm2src/mm2_bitcoin/serialization/src/impls.rs @@ -1,10 +1,11 @@ +use std::io; + use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use bytes::Bytes; use compact::Compact; use compact_integer::CompactInteger; use hash::{CipherText, EncCipherText, EquihashSolution, OutCipherText, ZkProof, ZkProofSapling, H128, H160, H256, H264, H32, H48, H512, H520, H64, H96}; -use std::io; use {Deserializable, Error, Reader, Serializable, Stream}; impl Serializable for bool { diff --git a/mm2src/mm2_bitcoin/serialization/src/lib.rs b/mm2src/mm2_bitcoin/serialization/src/lib.rs index 389c28f072..b2dc4bbbdd 100644 --- a/mm2src/mm2_bitcoin/serialization/src/lib.rs +++ b/mm2src/mm2_bitcoin/serialization/src/lib.rs @@ -9,10 +9,9 @@ mod list; mod reader; mod stream; -pub use primitives::{bytes, compact, hash}; - pub use compact_integer::{parse_compact_int, CompactInteger}; pub use list::List; +pub use primitives::{bytes, compact, hash}; pub use reader::{deserialize, deserialize_iterator, CoinVariant, Deserializable, Error, ReadIterator, Reader}; pub use stream::{serialize, serialize_list, serialize_with_flags, serialized_list_size, serialized_list_size_with_flags, Serializable, Stream, SERIALIZE_TRANSACTION_WITNESS}; diff --git a/mm2src/mm2_bitcoin/serialization/src/list.rs b/mm2src/mm2_bitcoin/serialization/src/list.rs index 03acbdbe78..04917d4a2c 100644 --- a/mm2src/mm2_bitcoin/serialization/src/list.rs +++ b/mm2src/mm2_bitcoin/serialization/src/list.rs @@ -1,4 +1,5 @@ use std::io; + use {Deserializable, Error, Reader, Serializable, Stream}; #[derive(Debug, Clone)] diff --git a/mm2src/mm2_bitcoin/serialization/src/reader.rs b/mm2src/mm2_bitcoin/serialization/src/reader.rs index 453baa26a7..dd0bc2b8e1 100644 --- a/mm2src/mm2_bitcoin/serialization/src/reader.rs +++ b/mm2src/mm2_bitcoin/serialization/src/reader.rs @@ -1,6 +1,7 @@ +use std::{io, marker}; + use compact_integer::CompactInteger; use derive_more::Display; -use std::{io, marker}; pub fn deserialize(buffer: R) -> Result where diff --git a/mm2src/mm2_bitcoin/serialization/src/stream.rs b/mm2src/mm2_bitcoin/serialization/src/stream.rs index 01cc7a75c3..5cf5527d4b 100644 --- a/mm2src/mm2_bitcoin/serialization/src/stream.rs +++ b/mm2src/mm2_bitcoin/serialization/src/stream.rs @@ -1,9 +1,10 @@ //! Stream used for serialization of Bitcoin structures -use bytes::Bytes; -use compact_integer::CompactInteger; use std::borrow::Borrow; use std::io::{self, Write}; +use bytes::Bytes; +use compact_integer::CompactInteger; + /// Do not serialize transaction witness data. pub const SERIALIZE_TRANSACTION_WITNESS: u32 = 0x40000000; diff --git a/mm2src/mm2_bitcoin/spv_validation/src/conf.rs b/mm2src/mm2_bitcoin/spv_validation/src/conf.rs index 7fe6425ee9..9fe6d7be2e 100644 --- a/mm2src/mm2_bitcoin/spv_validation/src/conf.rs +++ b/mm2src/mm2_bitcoin/spv_validation/src/conf.rs @@ -1,11 +1,13 @@ -use crate::helpers_validation::SPVError; -use crate::work::{DifficultyAlgorithm, RETARGETING_INTERVAL}; +use std::num::NonZeroU64; +use std::str::FromStr; + use chain::{BlockHeader, BlockHeaderBits}; use primitives::hash::H256; use serde::de::Error; use serde::{Deserialize, Deserializer}; -use std::num::NonZeroU64; -use std::str::FromStr; + +use crate::helpers_validation::SPVError; +use crate::work::{DifficultyAlgorithm, RETARGETING_INTERVAL}; fn from_hash_str<'de, D>(deserializer: D) -> Result where diff --git a/mm2src/mm2_bitcoin/spv_validation/src/helpers_validation.rs b/mm2src/mm2_bitcoin/spv_validation/src/helpers_validation.rs index d3ce01813d..fd7c813ce9 100644 --- a/mm2src/mm2_bitcoin/spv_validation/src/helpers_validation.rs +++ b/mm2src/mm2_bitcoin/spv_validation/src/helpers_validation.rs @@ -1,6 +1,3 @@ -use crate::conf::{SPVBlockHeader, SPVConf}; -use crate::storage::{BlockHeaderStorageError, BlockHeaderStorageOps}; -use crate::work::{next_block_bits, NextBlockBitsError}; use chain::{BlockHeader, RawHeaderError}; use derive_more::Display; use primitives::hash::H256; @@ -8,6 +5,10 @@ use ripemd160::Digest; use serialization::parse_compact_int; use sha2::Sha256; +use crate::conf::{SPVBlockHeader, SPVConf}; +use crate::storage::{BlockHeaderStorageError, BlockHeaderStorageOps}; +use crate::work::{next_block_bits, NextBlockBitsError}; + #[derive(Clone, Debug, Display, Eq, PartialEq)] pub enum SPVError { #[display(fmt = "Error validating initial spv parameters: {_0}")] @@ -399,15 +400,17 @@ pub async fn validate_headers( mod tests { extern crate std; + use std::{println, vec}; + + use chain::BlockHeaderBits; + use common::block_on; + use test_helpers::hex::force_deserialize_hex; + use super::*; use crate::conf::{BlockHeaderValidationParams, SPVBlockHeader}; use crate::test_utils::{self}; use crate::work::tests::TestBlockHeadersStorage; use crate::work::DifficultyAlgorithm; - use chain::BlockHeaderBits; - use common::block_on; - use std::{println, vec}; - use test_helpers::hex::force_deserialize_hex; #[test] fn it_does_bitcoin_hash256() { diff --git a/mm2src/mm2_bitcoin/spv_validation/src/lib.rs b/mm2src/mm2_bitcoin/spv_validation/src/lib.rs index 4c57937ba2..3c71d03f42 100644 --- a/mm2src/mm2_bitcoin/spv_validation/src/lib.rs +++ b/mm2src/mm2_bitcoin/spv_validation/src/lib.rs @@ -29,10 +29,10 @@ pub(crate) mod test_utils { extern crate serde; extern crate std; - use self::serde::Deserialize; - use std::{fs::File, io::Read, panic, string::String, vec, vec::Vec}; + use self::serde::Deserialize; + #[derive(Deserialize)] pub(crate) struct TestCase { pub input: serde_json::Value, diff --git a/mm2src/mm2_bitcoin/spv_validation/src/spv_proof.rs b/mm2src/mm2_bitcoin/spv_validation/src/spv_proof.rs index 396417e6d1..867c35def8 100644 --- a/mm2src/mm2_bitcoin/spv_validation/src/spv_proof.rs +++ b/mm2src/mm2_bitcoin/spv_validation/src/spv_proof.rs @@ -1,7 +1,8 @@ -use crate::helpers_validation::{merkle_prove, validate_vin, validate_vout, SPVError}; use chain::BlockHeader; use primitives::hash::H256; +use crate::helpers_validation::{merkle_prove, validate_vin, validate_vout, SPVError}; + pub const TRY_SPV_PROOF_INTERVAL: u64 = 10; #[derive(PartialEq, Clone)] @@ -49,12 +50,13 @@ impl SPVProof { #[cfg(test)] mod spv_proof_tests { - use crate::spv_proof::SPVProof; use chain::{BlockHeader, Transaction}; use hex::FromHex; use primitives::hash::H256; use serialization::{deserialize, serialize_list}; + use crate::spv_proof::SPVProof; + #[test] fn test_validate() { // https://live.blockcypher.com/btc-testnet/block/000000000000004d36632fda8180ff16855d606e5515aab0750d9d4fe55fe7d6/ diff --git a/mm2src/mm2_bitcoin/spv_validation/src/storage.rs b/mm2src/mm2_bitcoin/spv_validation/src/storage.rs index 7e922abe91..5280328dd1 100644 --- a/mm2src/mm2_bitcoin/spv_validation/src/storage.rs +++ b/mm2src/mm2_bitcoin/spv_validation/src/storage.rs @@ -1,8 +1,9 @@ +use std::collections::HashMap; + use async_trait::async_trait; use chain::BlockHeader; use derive_more::Display; use primitives::hash::H256; -use std::collections::HashMap; #[derive(Clone, Debug, Display, Eq, PartialEq)] pub enum BlockHeaderStorageError { diff --git a/mm2src/mm2_bitcoin/spv_validation/src/work.rs b/mm2src/mm2_bitcoin/spv_validation/src/work.rs index b77652c06c..6f0bf3f3b9 100644 --- a/mm2src/mm2_bitcoin/spv_validation/src/work.rs +++ b/mm2src/mm2_bitcoin/spv_validation/src/work.rs @@ -1,11 +1,13 @@ -use crate::conf::SPVBlockHeader; -use crate::storage::{BlockHeaderStorageError, BlockHeaderStorageOps}; +use std::cmp; + use chain::BlockHeaderBits; use derive_more::Display; use primitives::compact::Compact; use primitives::U256; use serde::{Deserialize, Serialize}; -use std::cmp; + +use crate::conf::SPVBlockHeader; +use crate::storage::{BlockHeaderStorageError, BlockHeaderStorageOps}; const RETARGETING_FACTOR: u32 = 4; const TARGET_SPACING_SECONDS: u32 = 10 * 60; @@ -163,15 +165,17 @@ async fn btc_testnet_next_block_bits( #[cfg(test)] pub(crate) mod tests { - use super::*; - use crate::storage::{BlockHeaderStorageError, BlockHeaderStorageOps}; + use std::collections::HashMap; + use async_trait::async_trait; use chain::BlockHeader; use common::block_on; use lazy_static::lazy_static; use primitives::hash::H256; use serde::Deserialize; - use std::collections::HashMap; + + use super::*; + use crate::storage::{BlockHeaderStorageError, BlockHeaderStorageOps}; const BLOCK_HEADERS_STR: &str = include_str!("./for_tests/workTestVectors.json"); diff --git a/mm2src/mm2_core/src/event_dispatcher.rs b/mm2src/mm2_core/src/event_dispatcher.rs index 479ca7d616..125ff2289e 100644 --- a/mm2src/mm2_core/src/event_dispatcher.rs +++ b/mm2src/mm2_core/src/event_dispatcher.rs @@ -1,8 +1,10 @@ -use crate::mm_ctx::MmArc; -use async_trait::async_trait; use std::any::TypeId; use std::collections::{HashMap, HashSet}; +use async_trait::async_trait; + +use crate::mm_ctx::MmArc; + pub type Listeners = Vec>>; pub type DispatchTable = HashMap>; @@ -68,15 +70,17 @@ where #[cfg(test)] mod event_dispatcher_tests { - use crate::event_dispatcher::{Dispatcher, EventListener, EventUniqueId}; - use crate::mm_ctx::{MmArc, MmCtxBuilder}; - use async_trait::async_trait; - use common::block_on; use std::any::TypeId; use std::ops::Deref; use std::sync::Arc; + + use async_trait::async_trait; + use common::block_on; use uuid::Uuid; + use crate::event_dispatcher::{Dispatcher, EventListener, EventUniqueId}; + use crate::mm_ctx::{MmArc, MmCtxBuilder}; + #[derive(Clone, Default)] struct EventSwapStatusChanged { uuid: Uuid, diff --git a/mm2src/mm2_core/src/mm_ctx.rs b/mm2src/mm2_core/src/mm_ctx.rs index fc7fc5f0d9..af83fa6166 100644 --- a/mm2src/mm2_core/src/mm_ctx.rs +++ b/mm2src/mm2_core/src/mm_ctx.rs @@ -1,3 +1,11 @@ +use std::any::Any; +use std::collections::hash_map::{Entry, HashMap}; +use std::collections::HashSet; +use std::fmt; +use std::future::Future; +use std::ops::Deref; +use std::sync::{Arc, Mutex}; + #[cfg(feature = "track-ctx-pointer")] use common::executor::Timer; use common::executor::{abortable_queue::{AbortableQueue, WeakSpawner}, @@ -12,13 +20,6 @@ use primitives::hash::H160; use rand::Rng; use serde_json::{self as json, Value as Json}; use shared_ref_counter::{SharedRc, WeakRc}; -use std::any::Any; -use std::collections::hash_map::{Entry, HashMap}; -use std::collections::HashSet; -use std::fmt; -use std::future::Future; -use std::ops::Deref; -use std::sync::{Arc, Mutex}; cfg_wasm32! { use mm2_rpc::wasm_rpc::WasmRpcSender; diff --git a/mm2src/mm2_db/src/indexed_db/be_big_uint.rs b/mm2src/mm2_db/src/indexed_db/be_big_uint.rs index d1c94d2503..fba4666bb6 100644 --- a/mm2src/mm2_db/src/indexed_db/be_big_uint.rs +++ b/mm2src/mm2_db/src/indexed_db/be_big_uint.rs @@ -44,6 +44,9 @@ //! assert([2, 4294967295, 2147483647] < [4, 4294967295, 4294967295, 4294967295, 2147483647]); //! ``` +use std::fmt; +use std::ops::Add; + use common::ifrom_inner; use derive_more::Display; use mm2_number::BigUint; @@ -51,8 +54,6 @@ use num_traits::ToPrimitive; use serde::de::Error as DeError; use serde::ser::Error as SerError; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use std::fmt; -use std::ops::Add; #[derive(Debug, Display)] pub enum BigUintError { @@ -176,9 +177,10 @@ impl<'de> Deserialize<'de> for BeBigUint { } mod tests { - use super::*; use serde_json::{self as json, json, Value as Json}; use wasm_bindgen_test::*; + + use super::*; wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] diff --git a/mm2src/mm2_db/src/indexed_db/db_driver.rs b/mm2src/mm2_db/src/indexed_db/db_driver.rs index 0329b9b9a0..c01de717a0 100644 --- a/mm2src/mm2_db/src/indexed_db/db_driver.rs +++ b/mm2src/mm2_db/src/indexed_db/db_driver.rs @@ -6,6 +6,10 @@ //! Since the wrappers represented below are not `Send`, it's strongly recommended NOT to use them directly. //! Please consider using a higher-level interface from `indexed_db.rs`. +use std::collections::HashSet; +use std::fmt; +use std::sync::Mutex; + use common::log::{error, info}; use common::stringify_js_error; use futures::channel::mpsc; @@ -14,9 +18,6 @@ use lazy_static::lazy_static; use mm2_err_handle::prelude::*; use serde::{Deserialize, Serialize}; use serde_json::Value as Json; -use std::collections::HashSet; -use std::fmt; -use std::sync::Mutex; use wasm_bindgen::prelude::*; use web_sys::{IdbDatabase, IdbTransactionMode}; diff --git a/mm2src/mm2_db/src/indexed_db/db_lock.rs b/mm2src/mm2_db/src/indexed_db/db_lock.rs index 2a650f0c5f..608b4f694f 100644 --- a/mm2src/mm2_db/src/indexed_db/db_lock.rs +++ b/mm2src/mm2_db/src/indexed_db/db_lock.rs @@ -1,8 +1,10 @@ -use super::{DbIdentifier, DbInstance, InitDbResult}; +use std::sync::{Arc, Weak}; + use futures::lock::{MappedMutexGuard as AsyncMappedMutexGuard, Mutex as AsyncMutex, MutexGuard as AsyncMutexGuard}; use mm2_core::{mm_ctx::MmArc, DbNamespaceId}; use primitives::hash::H160; -use std::sync::{Arc, Weak}; + +use super::{DbIdentifier, DbInstance, InitDbResult}; /// The mapped mutex guard. /// This implements `Deref`. diff --git a/mm2src/mm2_db/src/indexed_db/drivers/builder.rs b/mm2src/mm2_db/src/indexed_db/drivers/builder.rs index 7d8c6bb79c..1ce427e6a0 100644 --- a/mm2src/mm2_db/src/indexed_db/drivers/builder.rs +++ b/mm2src/mm2_db/src/indexed_db/drivers/builder.rs @@ -1,14 +1,16 @@ -use super::{construct_event_closure, DbUpgrader, IdbDatabaseImpl, OnUpgradeError, OnUpgradeNeededCb, OPEN_DATABASES}; +use std::collections::{HashMap, HashSet}; + use common::{log::info, stringify_js_error}; use derive_more::Display; use futures::channel::mpsc; use futures::StreamExt; use mm2_err_handle::prelude::*; -use std::collections::{HashMap, HashSet}; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{IdbDatabase, IdbOpenDbRequest, IdbTransaction, IdbVersionChangeEvent}; +use super::{construct_event_closure, DbUpgrader, IdbDatabaseImpl, OnUpgradeError, OnUpgradeNeededCb, OPEN_DATABASES}; + pub type InitDbResult = Result>; #[derive(Debug, Display, PartialEq)] diff --git a/mm2src/mm2_db/src/indexed_db/drivers/cursor/cursor.rs b/mm2src/mm2_db/src/indexed_db/drivers/cursor/cursor.rs index bba549d3bd..bda0bcb406 100644 --- a/mm2src/mm2_db/src/indexed_db/drivers/cursor/cursor.rs +++ b/mm2src/mm2_db/src/indexed_db/drivers/cursor/cursor.rs @@ -1,6 +1,5 @@ -use super::construct_event_closure; -use crate::indexed_db::db_driver::{InternalItem, ItemId}; -use crate::indexed_db::BeBigUint; +use std::convert::TryInto; + use common::wasm::{deserialize_from_js, serialize_to_js, stringify_js_error}; use derive_more::Display; use enum_from::EnumFromTrait; @@ -9,11 +8,14 @@ use futures::StreamExt; use js_sys::Array; use mm2_err_handle::prelude::*; use serde_json::{self as json, Value as Json}; -use std::convert::TryInto; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{IdbCursorDirection, IdbCursorWithValue, IdbIndex, IdbKeyRange, IdbRequest}; +use super::construct_event_closure; +use crate::indexed_db::db_driver::{InternalItem, ItemId}; +use crate::indexed_db::BeBigUint; + mod empty_cursor; mod multi_key_bound_cursor; mod multi_key_cursor; diff --git a/mm2src/mm2_db/src/indexed_db/drivers/cursor/empty_cursor.rs b/mm2src/mm2_db/src/indexed_db/drivers/cursor/empty_cursor.rs index 441180d8bb..74b1901c6c 100644 --- a/mm2src/mm2_db/src/indexed_db/drivers/cursor/empty_cursor.rs +++ b/mm2src/mm2_db/src/indexed_db/drivers/cursor/empty_cursor.rs @@ -1,7 +1,8 @@ -use super::{CursorAction, CursorDriverImpl, CursorItemAction, CursorResult}; use wasm_bindgen::prelude::*; use web_sys::IdbKeyRange; +use super::{CursorAction, CursorDriverImpl, CursorItemAction, CursorResult}; + /// The representation of a range that includes all records. pub struct IdbEmptyCursor; diff --git a/mm2src/mm2_db/src/indexed_db/drivers/cursor/multi_key_bound_cursor.rs b/mm2src/mm2_db/src/indexed_db/drivers/cursor/multi_key_bound_cursor.rs index 18a5962498..2ed4590e0d 100644 --- a/mm2src/mm2_db/src/indexed_db/drivers/cursor/multi_key_bound_cursor.rs +++ b/mm2src/mm2_db/src/indexed_db/drivers/cursor/multi_key_bound_cursor.rs @@ -1,5 +1,3 @@ -use super::{index_key_as_array, CursorAction, CursorBoundValue, CursorDriverImpl, CursorError, CursorItemAction, - CursorResult}; use common::{deserialize_from_js, serialize_to_js, stringify_js_error}; use js_sys::Array; use mm2_err_handle::prelude::*; @@ -7,6 +5,9 @@ use serde_json::{json, Value as Json}; use wasm_bindgen::prelude::*; use web_sys::IdbKeyRange; +use super::{index_key_as_array, CursorAction, CursorBoundValue, CursorDriverImpl, CursorError, CursorItemAction, + CursorResult}; + /// The representation of a range that includes records /// with the multiple `only` and `bound` restrictions. /// https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/bound @@ -199,10 +200,11 @@ impl CursorDriverImpl for IdbMultiKeyBoundCursor { } mod tests { - use super::*; use common::log::wasm_log::register_wasm_log; use wasm_bindgen_test::*; + use super::*; + wasm_bindgen_test_configure!(run_in_browser); /// The given indexes are expected to be in the bound. diff --git a/mm2src/mm2_db/src/indexed_db/drivers/cursor/multi_key_cursor.rs b/mm2src/mm2_db/src/indexed_db/drivers/cursor/multi_key_cursor.rs index f6b128aa1b..911ccfe19a 100644 --- a/mm2src/mm2_db/src/indexed_db/drivers/cursor/multi_key_cursor.rs +++ b/mm2src/mm2_db/src/indexed_db/drivers/cursor/multi_key_cursor.rs @@ -1,4 +1,3 @@ -use super::{CursorAction, CursorDriverImpl, CursorError, CursorItemAction, CursorResult}; use common::{serialize_to_js, stringify_js_error}; use js_sys::Array; use mm2_err_handle::prelude::*; @@ -6,6 +5,8 @@ use serde_json::Value as Json; use wasm_bindgen::prelude::*; use web_sys::IdbKeyRange; +use super::{CursorAction, CursorDriverImpl, CursorError, CursorItemAction, CursorResult}; + /// The representation of a range that includes records /// whose fields have only the specified [`IdbSingleCursor::only_values`] values. /// https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/only diff --git a/mm2src/mm2_db/src/indexed_db/drivers/cursor/single_key_bound_cursor.rs b/mm2src/mm2_db/src/indexed_db/drivers/cursor/single_key_bound_cursor.rs index 92e7ee087b..9e7419ac5d 100644 --- a/mm2src/mm2_db/src/indexed_db/drivers/cursor/single_key_bound_cursor.rs +++ b/mm2src/mm2_db/src/indexed_db/drivers/cursor/single_key_bound_cursor.rs @@ -1,9 +1,10 @@ -use super::{CursorAction, CursorBoundValue, CursorDriverImpl, CursorError, CursorItemAction, CursorResult}; use common::{log::warn, stringify_js_error}; use mm2_err_handle::prelude::*; use wasm_bindgen::prelude::*; use web_sys::IdbKeyRange; +use super::{CursorAction, CursorBoundValue, CursorDriverImpl, CursorError, CursorItemAction, CursorResult}; + /// The representation of a range that includes records /// whose value of the [`IdbSingleBoundCursor::field_name`] field is lower than [`IdbSingleBoundCursor::lower_bound_value`] /// and greater than [`IdbSingleBoundCursor::upper_bound_value`]. diff --git a/mm2src/mm2_db/src/indexed_db/drivers/cursor/single_key_cursor.rs b/mm2src/mm2_db/src/indexed_db/drivers/cursor/single_key_cursor.rs index b3d6efa476..7523f75d07 100644 --- a/mm2src/mm2_db/src/indexed_db/drivers/cursor/single_key_cursor.rs +++ b/mm2src/mm2_db/src/indexed_db/drivers/cursor/single_key_cursor.rs @@ -1,10 +1,11 @@ -use super::{CursorAction, CursorDriverImpl, CursorError, CursorItemAction, CursorResult}; use common::{serialize_to_js, stringify_js_error}; use mm2_err_handle::prelude::*; use serde_json::Value as Json; use wasm_bindgen::prelude::*; use web_sys::IdbKeyRange; +use super::{CursorAction, CursorDriverImpl, CursorError, CursorItemAction, CursorResult}; + /// The representation of a range that includes records /// whose value of the [`IdbSingleKeyCursor::field_name`] field equals to the [`IdbSingleKeyCursor::field_value`] value. /// https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/only diff --git a/mm2src/mm2_db/src/indexed_db/drivers/object_store.rs b/mm2src/mm2_db/src/indexed_db/drivers/object_store.rs index a7b8081e9c..95a01c8da2 100644 --- a/mm2src/mm2_db/src/indexed_db/drivers/object_store.rs +++ b/mm2src/mm2_db/src/indexed_db/drivers/object_store.rs @@ -1,15 +1,17 @@ -use super::{construct_event_closure, DbTransactionError, DbTransactionResult, InternalItem, ItemId}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + use common::{deserialize_from_js, serialize_to_js, stringify_js_error}; use futures::channel::mpsc; use futures::StreamExt; use mm2_err_handle::prelude::*; use serde_json::Value as Json; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{IdbIndex, IdbObjectStore, IdbRequest}; +use super::{construct_event_closure, DbTransactionError, DbTransactionResult, InternalItem, ItemId}; + pub struct IdbObjectStoreImpl { pub(crate) object_store: IdbObjectStore, pub(crate) aborted: Arc, diff --git a/mm2src/mm2_db/src/indexed_db/drivers/transaction.rs b/mm2src/mm2_db/src/indexed_db/drivers/transaction.rs index f76794b2de..d0ee16e66c 100644 --- a/mm2src/mm2_db/src/indexed_db/drivers/transaction.rs +++ b/mm2src/mm2_db/src/indexed_db/drivers/transaction.rs @@ -1,15 +1,17 @@ -use super::IdbObjectStoreImpl; +use std::collections::HashSet; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + use common::wasm::stringify_js_error; use derive_more::Display; use enum_from::EnumFromTrait; use mm2_err_handle::prelude::*; use serde_json::Value as Json; -use std::collections::HashSet; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; use wasm_bindgen::{closure::Closure, JsCast, JsValue}; use web_sys::IdbTransaction; +use super::IdbObjectStoreImpl; + pub type DbTransactionResult = Result>; #[derive(Debug, Display, EnumFromTrait, PartialEq)] diff --git a/mm2src/mm2_db/src/indexed_db/indexed_cursor.rs b/mm2src/mm2_db/src/indexed_db/indexed_cursor.rs index cdbc019f1a..bb5f34dc00 100644 --- a/mm2src/mm2_db/src/indexed_db/indexed_cursor.rs +++ b/mm2src/mm2_db/src/indexed_db/indexed_cursor.rs @@ -52,17 +52,19 @@ //! because ['RICK', 'MORTY', 13] < ['RICK', 'MORTY', 13, 1000000030], //! although it is expected to be within the specified bounds. -use crate::indexed_db::db_driver::cursor::CursorBoundValue; -pub(crate) use crate::indexed_db::db_driver::cursor::{CursorDriver, CursorFilters}; -pub use crate::indexed_db::db_driver::cursor::{CursorError, CursorResult}; -use crate::indexed_db::{DbTable, ItemId, TableSignature}; +use std::fmt; +use std::marker::PhantomData; + use futures::channel::{mpsc, oneshot}; use futures::{SinkExt, StreamExt}; use mm2_err_handle::prelude::*; use serde::Serialize; use serde_json::{self as json, Value as Json}; -use std::fmt; -use std::marker::PhantomData; + +use crate::indexed_db::db_driver::cursor::CursorBoundValue; +pub(crate) use crate::indexed_db::db_driver::cursor::{CursorDriver, CursorFilters}; +pub use crate::indexed_db::db_driver::cursor::{CursorError, CursorResult}; +use crate::indexed_db::{DbTable, ItemId, TableSignature}; pub(super) type DbCursorEventTx = mpsc::UnboundedSender; pub(super) type DbCursorEventRx = mpsc::UnboundedReceiver; @@ -180,13 +182,14 @@ pub(crate) async fn cursor_event_loop(mut rx: DbCursorEventRx, mut cursor: Curso } mod tests { - use super::*; - use crate::indexed_db::{BeBigUint, DbIdentifier, DbTable, DbUpgrader, IndexedDbBuilder, OnUpgradeResult}; use common::log::wasm_log::register_wasm_log; use itertools::Itertools; use serde::{Deserialize, Serialize}; use wasm_bindgen_test::*; + use super::*; + use crate::indexed_db::{BeBigUint, DbIdentifier, DbTable, DbUpgrader, IndexedDbBuilder, OnUpgradeResult}; + wasm_bindgen_test_configure!(run_in_browser); macro_rules! swap_item { diff --git a/mm2src/mm2_db/src/indexed_db/indexed_db.rs b/mm2src/mm2_db/src/indexed_db/indexed_db.rs index 3bad052869..2162ffeef4 100644 --- a/mm2src/mm2_db/src/indexed_db/indexed_db.rs +++ b/mm2src/mm2_db/src/indexed_db/indexed_db.rs @@ -7,6 +7,10 @@ //! the implementation below initializes and spawns a `IdbDatabaseImpl` database instance locally //! and communicate with it through the `mpsc` channel. +use std::collections::HashMap; +use std::marker::PhantomData; +use std::sync::Mutex; + use async_trait::async_trait; use common::executor::spawn_local; use common::log::debug; @@ -19,9 +23,6 @@ use primitives::hash::H160; use serde::de::DeserializeOwned; use serde::Serialize; use serde_json::{self as json, Value as Json}; -use std::collections::HashMap; -use std::marker::PhantomData; -use std::sync::Mutex; macro_rules! try_serialize_index_value { ($exp:expr, $index:expr) => {{ @@ -45,9 +46,8 @@ mod indexed_cursor; pub use be_big_uint::BeBigUint; pub use db_driver::{DbTransactionError, DbTransactionResult, DbUpgrader, InitDbError, InitDbResult, ItemId, OnUpgradeError, OnUpgradeResult}; -pub use db_lock::{ConstructibleDb, DbLocked, SharedDb, WeakDb}; - use db_driver::{IdbDatabaseBuilder, IdbDatabaseImpl, IdbObjectStoreImpl, IdbTransactionImpl, OnUpgradeNeededCb}; +pub use db_lock::{ConstructibleDb, DbLocked, SharedDb, WeakDb}; use indexed_cursor::{cursor_event_loop, CursorBuilder, CursorDriver, CursorError, CursorFilters, CursorResult, DbCursorEventTx}; @@ -870,12 +870,13 @@ mod internal { } mod tests { - use super::*; use common::log::wasm_log::register_wasm_log; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use wasm_bindgen_test::*; + use super::*; + wasm_bindgen_test_configure!(run_in_browser); #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] diff --git a/mm2src/mm2_err_handle/src/lib.rs b/mm2src/mm2_err_handle/src/lib.rs index 93b5030af3..13ebb68103 100644 --- a/mm2src/mm2_err_handle/src/lib.rs +++ b/mm2src/mm2_err_handle/src/lib.rs @@ -13,6 +13,8 @@ pub mod or_mm_error; pub mod split_mm; pub mod prelude { + pub use ser_error::SerializeErrorType; + pub use crate::common_errors::{WithInternal, WithTimeout}; pub use crate::discard_mm_trace::DiscardMmTrace; pub use crate::map_mm_error::MapMmError; @@ -22,5 +24,4 @@ pub mod prelude { pub use crate::mm_json_error::MmJsonError; pub use crate::or_mm_error::OrMmError; pub use crate::split_mm::SplitMmResult; - pub use ser_error::SerializeErrorType; } diff --git a/mm2src/mm2_err_handle/src/map_to_mm_fut.rs b/mm2src/mm2_err_handle/src/map_to_mm_fut.rs index 01de1b7d7e..aa76427c5e 100644 --- a/mm2src/mm2_err_handle/src/map_to_mm_fut.rs +++ b/mm2src/mm2_err_handle/src/map_to_mm_fut.rs @@ -1,7 +1,9 @@ -use crate::mm_error::{MmError, NotMmError, TraceLocation}; -use futures01::{Future, Poll}; use std::panic::Location; +use futures01::{Future, Poll}; + +use crate::mm_error::{MmError, NotMmError, TraceLocation}; + pub trait MapToMmFutureExt<'a, T, E1: NotMmError, E2: NotMmError> { fn map_to_mm_fut(self, f: F) -> MapToMmFuture<'a, T, E1, E2> where diff --git a/mm2src/mm2_err_handle/src/mm_error.rs b/mm2src/mm2_err_handle/src/mm_error.rs index 5f2f11e480..f33cb2d2dc 100644 --- a/mm2src/mm2_err_handle/src/mm_error.rs +++ b/mm2src/mm2_err_handle/src/mm_error.rs @@ -84,17 +84,18 @@ //! } //! ``` +use std::alloc::Allocator; +use std::cell::UnsafeCell; +use std::error::Error as StdError; +use std::fmt; +use std::panic::Location; + use common::{filename, HttpStatusCode}; use derive_more::Display; use http::StatusCode; use itertools::Itertools; use ser_error::SerializeErrorType; use serde::{Serialize, Serializer}; -use std::alloc::Allocator; -use std::cell::UnsafeCell; -use std::error::Error as StdError; -use std::fmt; -use std::panic::Location; pub type MmResult = Result>; @@ -326,12 +327,13 @@ impl FormattedTrace for Vec { #[cfg(test)] mod tests { - use super::*; - use crate::prelude::*; use futures01::Future; use ser_error_derive::SerializeErrorType; use serde_json::{self as json, json}; + use super::*; + use crate::prelude::*; + enum ErrorKind { NotSufficientBalance { actual: u64, required: u64 }, } diff --git a/mm2src/mm2_err_handle/src/mm_json_error.rs b/mm2src/mm2_err_handle/src/mm_json_error.rs index 14423121d1..80b1d8fe67 100644 --- a/mm2src/mm2_err_handle/src/mm_json_error.rs +++ b/mm2src/mm2_err_handle/src/mm_json_error.rs @@ -1,9 +1,11 @@ -use crate::mm_error::{MmError, NotMmError}; +use std::fmt; + use common::SerializationError; use ser_error::SerializeErrorType; use serde::{Deserialize, Serialize}; use serde_json::{self as json, Error as JsonError, Value as Json}; -use std::fmt; + +use crate::mm_error::{MmError, NotMmError}; #[derive(Clone, Debug, Deserialize, Serialize)] pub struct MmJsonError(Json); diff --git a/mm2src/mm2_eth/src/address.rs b/mm2src/mm2_eth/src/address.rs index de517e4a2e..43fe84a4eb 100644 --- a/mm2src/mm2_eth/src/address.rs +++ b/mm2src/mm2_eth/src/address.rs @@ -1,8 +1,7 @@ +pub use ethkey::Address; use ethkey::{public_to_address, Public}; use web3::types::H520; -pub use ethkey::Address; - pub fn address_from_pubkey_uncompressed(bytes: H520) -> Address { // Skip the first byte of the uncompressed public key. let public = Public::from_slice(&bytes[1..]); @@ -11,9 +10,10 @@ pub fn address_from_pubkey_uncompressed(bytes: H520) -> Address { #[cfg(test)] mod tests { - use super::*; use std::str::FromStr; + use super::*; + #[test] fn test_address_from_pubkey_uncompressed() { let pubkey = H520::from_str("04d5f11f3cf90d165af39b17caec89162c607ddfc2d64d4eba2058c2eb8c2347cc422eaf112cb01a662f5f29924e2a6322153ae05d4e73526cb83cc1759c09fc01").unwrap(); diff --git a/mm2src/mm2_eth/src/eip712.rs b/mm2src/mm2_eth/src/eip712.rs index bca185225f..d493fc974c 100644 --- a/mm2src/mm2_eth/src/eip712.rs +++ b/mm2src/mm2_eth/src/eip712.rs @@ -1,10 +1,11 @@ //! Inspired by https://github.com/openethereum/parity-ethereum/blob/v2.7.2-stable/util/EIP-712/src/eip712.rs -use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fmt; use std::str::FromStr; +use serde::{Deserialize, Serialize}; + pub(crate) const EIP712_DOMAIN: &str = "EIP712Domain"; pub(crate) type CustomTypes = HashMap>; diff --git a/mm2src/mm2_eth/src/eip712_encode.rs b/mm2src/mm2_eth/src/eip712_encode.rs index dbda992b83..083535dc88 100644 --- a/mm2src/mm2_eth/src/eip712_encode.rs +++ b/mm2src/mm2_eth/src/eip712_encode.rs @@ -1,18 +1,20 @@ //! Inspired by https://github.com/openethereum/parity-ethereum/blob/v2.7.2-stable/util/EIP-712/src/encode.rs -use crate::eip712::{CustomTypes, Eip712, PropertyType, EIP712_DOMAIN}; +use std::collections::HashSet; +use std::fmt; +use std::str::FromStr; + use ethabi::{encode, Token}; use indexmap::IndexSet; use itertools::Itertools; use serde::{Deserialize, Serialize}; use serde_json::Value as Json; -use std::collections::HashSet; -use std::fmt; -use std::str::FromStr; use web3::signing::keccak256; use web3::types::{Address, H256, U256}; use web3::{Error, Result}; +use crate::eip712::{CustomTypes, Eip712, PropertyType, EIP712_DOMAIN}; + type H256Bytes = Vec; pub fn hash_typed_data(data: Eip712) -> Result diff --git a/mm2src/mm2_eth/src/recovery.rs b/mm2src/mm2_eth/src/recovery.rs index 1afa478e6f..a0b363decc 100644 --- a/mm2src/mm2_eth/src/recovery.rs +++ b/mm2src/mm2_eth/src/recovery.rs @@ -1,10 +1,9 @@ +pub use ethkey::{Error, Signature}; use mm2_err_handle::prelude::*; use secp256k1::recovery::{RecoverableSignature, RecoveryId}; use secp256k1::{Message as SecpMessage, Secp256k1}; use web3::types::{H256, H520}; -pub use ethkey::{Error, Signature}; - /// Inspired by `ethkey::recover` with the only one difference: /// this methods returns the full `H520` pubkey instead of unprefixed `H512`. pub fn recover_pubkey(message_hash: H256, mut signature: Signature) -> MmResult { @@ -27,9 +26,10 @@ pub fn recover_pubkey(message_hash: H256, mut signature: Signature) -> MmResult< #[cfg(test)] mod tests { - use super::*; use std::str::FromStr; + use super::*; + /// https://testnet.bscscan.com/tx/0xbff2c07134a32da9f96588c03502f1caf2948c529c2ce9ce067f320f7c990b81 #[test] fn test_recover_pubkey_for_signed_tx() { diff --git a/mm2src/mm2_event_stream/src/behaviour.rs b/mm2src/mm2_event_stream/src/behaviour.rs index bb905af3fc..d7238ae969 100644 --- a/mm2src/mm2_event_stream/src/behaviour.rs +++ b/mm2src/mm2_event_stream/src/behaviour.rs @@ -1,6 +1,7 @@ -use crate::EventStreamConfiguration; use async_trait::async_trait; +use crate::EventStreamConfiguration; + #[async_trait] pub trait EventBehaviour { /// Unique name of the event. diff --git a/mm2src/mm2_event_stream/src/controller.rs b/mm2src/mm2_event_stream/src/controller.rs index 098c6e4bb7..10c866206f 100644 --- a/mm2src/mm2_event_stream/src/controller.rs +++ b/mm2src/mm2_event_stream/src/controller.rs @@ -1,5 +1,6 @@ -use parking_lot::Mutex; use std::{collections::HashMap, sync::Arc}; + +use parking_lot::Mutex; use tokio::sync::mpsc::{self, Receiver, Sender}; type ChannelId = u64; diff --git a/mm2src/mm2_event_stream/src/lib.rs b/mm2src/mm2_event_stream/src/lib.rs index afa5c7e1be..202a578738 100644 --- a/mm2src/mm2_event_stream/src/lib.rs +++ b/mm2src/mm2_event_stream/src/lib.rs @@ -1,6 +1,7 @@ -use serde::Deserialize; use std::collections::HashMap; +use serde::Deserialize; + /// Multi-purpose/generic event type that can easily be used over the event streaming pub struct Event { _type: String, diff --git a/mm2src/mm2_git/src/github_client.rs b/mm2src/mm2_git/src/github_client.rs index 5686e78814..8ce18ade77 100644 --- a/mm2src/mm2_git/src/github_client.rs +++ b/mm2src/mm2_git/src/github_client.rs @@ -75,10 +75,10 @@ impl RepositoryOperations for GithubClient { #[cfg(test)] #[allow(unused)] mod tests { - use crate::{GitController, GITHUB_API_URI}; + use serde::Deserialize; use super::*; - use serde::Deserialize; + use crate::{GitController, GITHUB_API_URI}; #[derive(Debug, Deserialize)] struct ChainRegistry { diff --git a/mm2src/mm2_gui_storage/src/account/mod.rs b/mm2src/mm2_gui_storage/src/account/mod.rs index 4350b0c939..635c8eb4c7 100644 --- a/mm2src/mm2_gui_storage/src/account/mod.rs +++ b/mm2src/mm2_gui_storage/src/account/mod.rs @@ -1,10 +1,12 @@ -use crate::account::storage::AccountStorageError; +use std::collections::BTreeSet; + use mm2_err_handle::prelude::*; use mm2_number::BigDecimal; use rpc::v1::types::H160 as H160Json; use serde::{Deserialize, Serialize}; use serde_repr::{Deserialize_repr, Serialize_repr}; -use std::collections::BTreeSet; + +use crate::account::storage::AccountStorageError; pub(crate) mod storage; diff --git a/mm2src/mm2_gui_storage/src/account/storage/account_storage_tests.rs b/mm2src/mm2_gui_storage/src/account/storage/account_storage_tests.rs index b44e83190a..e071911d8d 100644 --- a/mm2src/mm2_gui_storage/src/account/storage/account_storage_tests.rs +++ b/mm2src/mm2_gui_storage/src/account/storage/account_storage_tests.rs @@ -1,8 +1,10 @@ -use crate::account::storage::{AccountStorage, AccountStorageBuilder, AccountStorageError, AccountStorageResult}; -use crate::account::{AccountId, AccountInfo, AccountWithCoins, AccountWithEnabledFlag, EnabledAccountId, HwPubkey}; +use std::collections::{BTreeMap, BTreeSet}; + use mm2_number::BigDecimal; use mm2_test_helpers::for_tests::mm_ctx_with_custom_db; -use std::collections::{BTreeMap, BTreeSet}; + +use crate::account::storage::{AccountStorage, AccountStorageBuilder, AccountStorageError, AccountStorageResult}; +use crate::account::{AccountId, AccountInfo, AccountWithCoins, AccountWithEnabledFlag, EnabledAccountId, HwPubkey}; const HD_0_ACCOUNT: AccountId = AccountId::HD { account_idx: 0 }; const HD_1_ACCOUNT: AccountId = AccountId::HD { account_idx: 1 }; diff --git a/mm2src/mm2_gui_storage/src/account/storage/mod.rs b/mm2src/mm2_gui_storage/src/account/storage/mod.rs index a2a186d490..b6d3093c40 100644 --- a/mm2src/mm2_gui_storage/src/account/storage/mod.rs +++ b/mm2src/mm2_gui_storage/src/account/storage/mod.rs @@ -1,12 +1,14 @@ -use crate::account::{AccountId, AccountInfo, AccountType, AccountWithCoins, AccountWithEnabledFlag, EnabledAccountId, - EnabledAccountType, HwPubkey}; +use std::collections::{BTreeMap, BTreeSet}; +use std::error::Error as StdError; + use async_trait::async_trait; use derive_more::Display; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; use mm2_number::BigDecimal; -use std::collections::{BTreeMap, BTreeSet}; -use std::error::Error as StdError; + +use crate::account::{AccountId, AccountInfo, AccountType, AccountWithCoins, AccountWithEnabledFlag, EnabledAccountId, + EnabledAccountType, HwPubkey}; #[cfg(any(test, target_arch = "wasm32"))] mod account_storage_tests; diff --git a/mm2src/mm2_gui_storage/src/account/storage/sqlite_storage.rs b/mm2src/mm2_gui_storage/src/account/storage/sqlite_storage.rs index 916854de63..4b42a16d59 100644 --- a/mm2src/mm2_gui_storage/src/account/storage/sqlite_storage.rs +++ b/mm2src/mm2_gui_storage/src/account/storage/sqlite_storage.rs @@ -1,7 +1,7 @@ -use crate::account::storage::{AccountStorage, AccountStorageError, AccountStorageResult}; -use crate::account::{AccountId, AccountInfo, AccountType, AccountWithCoins, AccountWithEnabledFlag, EnabledAccountId, - EnabledAccountType, HwPubkey, MAX_ACCOUNT_DESCRIPTION_LENGTH, MAX_ACCOUNT_NAME_LENGTH, - MAX_TICKER_LENGTH}; +use std::collections::{BTreeMap, BTreeSet}; +use std::str::FromStr; +use std::sync::{Arc, MutexGuard}; + use async_trait::async_trait; use common::some_or_return_ok_none; use db_common::foreign_columns; @@ -12,9 +12,11 @@ use db_common::sqlite::{is_constraint_error, SqliteConnShared}; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; use mm2_number::BigDecimal; -use std::collections::{BTreeMap, BTreeSet}; -use std::str::FromStr; -use std::sync::{Arc, MutexGuard}; + +use crate::account::storage::{AccountStorage, AccountStorageError, AccountStorageResult}; +use crate::account::{AccountId, AccountInfo, AccountType, AccountWithCoins, AccountWithEnabledFlag, EnabledAccountId, + EnabledAccountType, HwPubkey, MAX_ACCOUNT_DESCRIPTION_LENGTH, MAX_ACCOUNT_NAME_LENGTH, + MAX_TICKER_LENGTH}; const DEVICE_PUBKEY_MAX_LENGTH: usize = 20; const BALANCE_MAX_LENGTH: usize = 255; diff --git a/mm2src/mm2_gui_storage/src/account/storage/wasm_storage.rs b/mm2src/mm2_gui_storage/src/account/storage/wasm_storage.rs index 8392294c78..c0bdfc5b11 100644 --- a/mm2src/mm2_gui_storage/src/account/storage/wasm_storage.rs +++ b/mm2src/mm2_gui_storage/src/account/storage/wasm_storage.rs @@ -1,6 +1,5 @@ -use crate::account::storage::{AccountStorage, AccountStorageError, AccountStorageResult}; -use crate::account::{AccountId, AccountInfo, AccountType, AccountWithCoins, AccountWithEnabledFlag, EnabledAccountId, - EnabledAccountType, HwPubkey}; +use std::collections::{BTreeMap, BTreeSet}; + use async_trait::async_trait; use mm2_core::mm_ctx::MmArc; use mm2_db::indexed_db::{ConstructibleDb, DbIdentifier, DbInstance, DbLocked, DbTransaction, DbTransactionError, @@ -9,7 +8,10 @@ use mm2_db::indexed_db::{ConstructibleDb, DbIdentifier, DbInstance, DbLocked, Db use mm2_err_handle::prelude::*; use mm2_number::BigDecimal; use serde::{Deserialize, Serialize}; -use std::collections::{BTreeMap, BTreeSet}; + +use crate::account::storage::{AccountStorage, AccountStorageError, AccountStorageResult}; +use crate::account::{AccountId, AccountInfo, AccountType, AccountWithCoins, AccountWithEnabledFlag, EnabledAccountId, + EnabledAccountType, HwPubkey}; const DB_NAME: &str = "gui_account_storage"; const DB_VERSION: u32 = 1; diff --git a/mm2src/mm2_gui_storage/src/context.rs b/mm2src/mm2_gui_storage/src/context.rs index 4a15f48541..aee547e196 100644 --- a/mm2src/mm2_gui_storage/src/context.rs +++ b/mm2src/mm2_gui_storage/src/context.rs @@ -1,7 +1,9 @@ -use crate::account::storage::{AccountStorage, AccountStorageBoxed, AccountStorageBuilder, AccountStorageResult}; -use mm2_core::mm_ctx::{from_ctx, MmArc}; use std::sync::Arc; +use mm2_core::mm_ctx::{from_ctx, MmArc}; + +use crate::account::storage::{AccountStorage, AccountStorageBoxed, AccountStorageBuilder, AccountStorageResult}; + pub(crate) struct AccountContext { storage: AccountStorageBoxed, } diff --git a/mm2src/mm2_gui_storage/src/rpc_commands.rs b/mm2src/mm2_gui_storage/src/rpc_commands.rs index 2c3363443c..800736a79e 100644 --- a/mm2src/mm2_gui_storage/src/rpc_commands.rs +++ b/mm2src/mm2_gui_storage/src/rpc_commands.rs @@ -1,7 +1,5 @@ -use crate::account::storage::AccountStorageError; -use crate::account::{AccountId, AccountInfo, AccountWithCoins, AccountWithEnabledFlag, EnabledAccountId, - MAX_ACCOUNT_DESCRIPTION_LENGTH, MAX_ACCOUNT_NAME_LENGTH, MAX_TICKER_LENGTH}; -use crate::context::AccountContext; +use std::collections::BTreeSet; + use common::{HttpStatusCode, StatusCode, SuccessResponse}; use derive_more::Display; use mm2_core::mm_ctx::MmArc; @@ -9,7 +7,11 @@ use mm2_err_handle::prelude::*; use mm2_number::BigDecimal; use ser_error_derive::SerializeErrorType; use serde::{Deserialize, Serialize}; -use std::collections::BTreeSet; + +use crate::account::storage::AccountStorageError; +use crate::account::{AccountId, AccountInfo, AccountWithCoins, AccountWithEnabledFlag, EnabledAccountId, + MAX_ACCOUNT_DESCRIPTION_LENGTH, MAX_ACCOUNT_NAME_LENGTH, MAX_TICKER_LENGTH}; +use crate::context::AccountContext; #[derive(Display, Serialize, SerializeErrorType)] #[serde(tag = "error_type", content = "error_data")] diff --git a/mm2src/mm2_io/src/file_lock.rs b/mm2src/mm2_io/src/file_lock.rs index 9a2e04bdef..2b839f6731 100644 --- a/mm2src/mm2_io/src/file_lock.rs +++ b/mm2src/mm2_io/src/file_lock.rs @@ -1,8 +1,9 @@ +use std::path::{Path, PathBuf}; + use common::now_sec; use derive_more::Display; use gstuff::now_float; use mm2_err_handle::prelude::*; -use std::path::{Path, PathBuf}; pub type FileLockResult = std::result::Result>; @@ -90,9 +91,10 @@ impl> Drop for FileLock { #[cfg(test)] mod file_lock_tests { - use super::*; use std::{thread::sleep, time::Duration}; + use super::*; + #[test] fn test_file_lock_should_create_file_and_record_timestamp_and_then_delete_on_drop() { let now = now_sec(); diff --git a/mm2src/mm2_io/src/fs.rs b/mm2src/mm2_io/src/fs.rs index e844086d89..3012a6e44f 100644 --- a/mm2src/mm2_io/src/fs.rs +++ b/mm2src/mm2_io/src/fs.rs @@ -1,3 +1,9 @@ +use std::ffi::OsStr; +use std::fs::{self, DirEntry}; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; +use std::time::UNIX_EPOCH; + use async_std::fs as async_fs; use common::log::{error, LogOnError}; use derive_more::Display; @@ -8,11 +14,6 @@ use rand::random; use serde::de::DeserializeOwned; use serde::Serialize; use serde_json::{self as json, Error as JsonError}; -use std::ffi::OsStr; -use std::fs::{self, DirEntry}; -use std::io::{self, Read, Write}; -use std::path::{Path, PathBuf}; -use std::time::UNIX_EPOCH; pub type FsJsonResult = Result>; pub type IoResult = Result>; diff --git a/mm2src/mm2_main/src/database.rs b/mm2src/mm2_main/src/database.rs index 47b1241cb3..0016503cd9 100644 --- a/mm2src/mm2_main/src/database.rs +++ b/mm2src/mm2_main/src/database.rs @@ -6,15 +6,15 @@ pub mod my_orders; #[path = "database/stats_nodes.rs"] pub mod stats_nodes; #[path = "database/stats_swaps.rs"] pub mod stats_swaps; -use crate::CREATE_MY_SWAPS_TABLE; use common::log::{debug, error, info}; 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 stats_swaps::create_and_fill_stats_swaps_from_json_statements; +use crate::CREATE_MY_SWAPS_TABLE; + const SELECT_MIGRATION: &str = "SELECT * FROM migration ORDER BY current_migration DESC LIMIT 1;"; fn get_current_migration(ctx: &MmArc) -> SqlResult { diff --git a/mm2src/mm2_main/src/database/my_orders.rs b/mm2src/mm2_main/src/database/my_orders.rs index 898d1f1620..2f90d6bf4e 100644 --- a/mm2src/mm2_main/src/database/my_orders.rs +++ b/mm2src/mm2_main/src/database/my_orders.rs @@ -1,6 +1,8 @@ #![allow(deprecated)] // TODO: remove this once rusqlite is >= 0.29 -use crate::mm2::lp_ordermatch::{FilteringOrder, MakerOrder, MyOrdersFilter, RecentOrdersSelectResult, TakerOrder}; +use std::convert::TryInto; +use std::string::ParseError; + /// This module contains code to work with my_orders table in MM2 SQLite DB use common::log::debug; use common::{now_ms, PagingOptions}; @@ -9,10 +11,10 @@ use db_common::sqlite::rusqlite::{params_from_iter, Connection, Error as SqlErro use db_common::sqlite::sql_builder::SqlBuilder; use mm2_core::mm_ctx::MmArc; use mm2_rpc::data::legacy::TakerAction; -use std::convert::TryInto; -use std::string::ParseError; use uuid::Uuid; +use crate::mm2::lp_ordermatch::{FilteringOrder, MakerOrder, MyOrdersFilter, RecentOrdersSelectResult, TakerOrder}; + const MY_ORDERS_TABLE: &str = "my_orders"; pub const CREATE_MY_ORDERS_TABLE: &str = "CREATE TABLE IF NOT EXISTS my_orders ( diff --git a/mm2src/mm2_main/src/database/my_swaps.rs b/mm2src/mm2_main/src/database/my_swaps.rs index ab5a08b84b..058e0e8d25 100644 --- a/mm2src/mm2_main/src/database/my_swaps.rs +++ b/mm2src/mm2_main/src/database/my_swaps.rs @@ -1,16 +1,18 @@ #![allow(deprecated)] // TODO: remove this once rusqlite is >= 0.29 -/// This module contains code to work with my_swaps table in MM2 SQLite DB -use crate::mm2::lp_swap::{MyRecentSwapsUuids, MySwapsFilter, SavedSwap, SavedSwapIo}; +use std::convert::TryInto; + use common::log::debug; use common::PagingOptions; use db_common::sqlite::offset_by_uuid; use db_common::sqlite::rusqlite::{Connection, Error as SqlError, Result as SqlResult, ToSql}; use db_common::sqlite::sql_builder::SqlBuilder; use mm2_core::mm_ctx::MmArc; -use std::convert::TryInto; use uuid::Error as UuidError; +/// This module contains code to work with my_swaps table in MM2 SQLite DB +use crate::mm2::lp_swap::{MyRecentSwapsUuids, MySwapsFilter, SavedSwap, SavedSwapIo}; + const MY_SWAPS_TABLE: &str = "my_swaps"; // Using a macro because static variable can't be passed to concat! diff --git a/mm2src/mm2_main/src/database/stats_nodes.rs b/mm2src/mm2_main/src/database/stats_nodes.rs index 7a6330c24a..76397b7599 100644 --- a/mm2src/mm2_main/src/database/stats_nodes.rs +++ b/mm2src/mm2_main/src/database/stats_nodes.rs @@ -1,9 +1,11 @@ -/// This module contains code to work with nodes table for stats collection in MM2 SQLite DB -use crate::mm2::lp_stats::{NodeInfo, NodeVersionStat}; +use std::collections::hash_map::HashMap; + use common::log::debug; use db_common::sqlite::rusqlite::{params_from_iter, Error as SqlError, Result as SqlResult}; use mm2_core::mm_ctx::MmArc; -use std::collections::hash_map::HashMap; + +/// This module contains code to work with nodes table for stats collection in MM2 SQLite DB +use crate::mm2::lp_stats::{NodeInfo, NodeVersionStat}; pub const CREATE_NODES_TABLE: &str = "CREATE TABLE IF NOT EXISTS nodes ( id INTEGER NOT NULL PRIMARY KEY, diff --git a/mm2src/mm2_main/src/database/stats_swaps.rs b/mm2src/mm2_main/src/database/stats_swaps.rs index eb9c5e0fd1..cee307a749 100644 --- a/mm2src/mm2_main/src/database/stats_swaps.rs +++ b/mm2src/mm2_main/src/database/stats_swaps.rs @@ -1,12 +1,14 @@ #![allow(deprecated)] // TODO: remove this once rusqlite is >= 0.29 -use crate::mm2::lp_swap::{MakerSavedSwap, SavedSwap, SavedSwapIo, TakerSavedSwap}; +use std::collections::HashSet; + use common::log::{debug, error}; use db_common::{owned_named_params, sqlite::{rusqlite::{params_from_iter, Connection, OptionalExtension}, AsSqlNamedParams, OwnedSqlNamedParams}}; use mm2_core::mm_ctx::MmArc; -use std::collections::HashSet; + +use crate::mm2::lp_swap::{MakerSavedSwap, SavedSwap, SavedSwapIo, TakerSavedSwap}; const CREATE_STATS_SWAPS_TABLE: &str = "CREATE TABLE IF NOT EXISTS stats_swaps ( id INTEGER NOT NULL PRIMARY KEY, diff --git a/mm2src/mm2_main/src/lp_dispatcher.rs b/mm2src/mm2_main/src/lp_dispatcher.rs index 74f7a9a18d..3867b87ee7 100644 --- a/mm2src/mm2_main/src/lp_dispatcher.rs +++ b/mm2src/mm2_main/src/lp_dispatcher.rs @@ -1,10 +1,12 @@ -use crate::mm2::lp_ordermatch::TradingBotEvent; -use crate::mm2::lp_swap::MakerSwapStatusChanged; +use std::any::TypeId; +use std::sync::Arc; + use async_std::sync::RwLock; use mm2_core::{event_dispatcher::{Dispatcher, EventUniqueId}, mm_ctx::{from_ctx, MmArc}}; -use std::any::TypeId; -use std::sync::Arc; + +use crate::mm2::lp_ordermatch::TradingBotEvent; +use crate::mm2::lp_swap::MakerSwapStatusChanged; #[derive(Clone)] pub struct StopCtxEvent; diff --git a/mm2src/mm2_main/src/lp_init/init_context.rs b/mm2src/mm2_main/src/lp_init/init_context.rs index e1c045c098..39b53d5e04 100644 --- a/mm2src/mm2_main/src/lp_init/init_context.rs +++ b/mm2src/mm2_main/src/lp_init/init_context.rs @@ -1,9 +1,11 @@ +use std::sync::Arc; + +use mm2_core::mm_ctx::{from_ctx, MmArc}; +use rpc_task::RpcTaskManager; + use crate::mm2::lp_native_dex::init_hw::InitHwTaskManagerShared; #[cfg(target_arch = "wasm32")] use crate::mm2::lp_native_dex::init_metamask::InitMetamaskManagerShared; -use mm2_core::mm_ctx::{from_ctx, MmArc}; -use rpc_task::RpcTaskManager; -use std::sync::Arc; pub struct MmInitContext { pub init_hw_task_manager: InitHwTaskManagerShared, diff --git a/mm2src/mm2_main/src/lp_init/init_hw.rs b/mm2src/mm2_main/src/lp_init/init_hw.rs index 726bea7967..869e57dd30 100644 --- a/mm2src/mm2_main/src/lp_init/init_hw.rs +++ b/mm2src/mm2_main/src/lp_init/init_hw.rs @@ -1,4 +1,5 @@ -use crate::mm2::lp_native_dex::init_context::MmInitContext; +use std::time::Duration; + use async_trait::async_trait; use common::{HttpStatusCode, SuccessResponse}; use crypto::hw_rpc_task::{HwConnectStatuses, HwRpcTaskAwaitingStatus, HwRpcTaskUserAction, HwRpcTaskUserActionRequest, @@ -13,7 +14,8 @@ use mm2_err_handle::prelude::*; use rpc_task::rpc_common::{CancelRpcTaskError, CancelRpcTaskRequest, InitRpcTaskResponse, RpcTaskStatusError, RpcTaskStatusRequest, RpcTaskUserActionError}; use rpc_task::{RpcTask, RpcTaskError, RpcTaskHandle, RpcTaskManager, RpcTaskManagerShared, RpcTaskStatus, RpcTaskTypes}; -use std::time::Duration; + +use crate::mm2::lp_native_dex::init_context::MmInitContext; const TREZOR_CONNECT_TIMEOUT: Duration = Duration::from_secs(300); const TREZOR_PIN_TIMEOUT: Duration = Duration::from_secs(600); diff --git a/mm2src/mm2_main/src/lp_init/init_metamask.rs b/mm2src/mm2_main/src/lp_init/init_metamask.rs index b362920a54..53359b56d6 100644 --- a/mm2src/mm2_main/src/lp_init/init_metamask.rs +++ b/mm2src/mm2_main/src/lp_init/init_metamask.rs @@ -1,4 +1,5 @@ -use crate::mm2::lp_native_dex::init_context::MmInitContext; +use std::time::Duration; + use async_trait::async_trait; use common::{HttpStatusCode, SerdeInfallible, SuccessResponse}; use crypto::metamask::{from_metamask_error, MetamaskError, MetamaskRpcError, WithMetamaskRpcError}; @@ -12,7 +13,8 @@ use mm2_err_handle::prelude::*; use rpc_task::rpc_common::{CancelRpcTaskError, CancelRpcTaskRequest, InitRpcTaskResponse, RpcTaskStatusError, RpcTaskStatusRequest}; use rpc_task::{RpcTask, RpcTaskError, RpcTaskHandle, RpcTaskManager, RpcTaskManagerShared, RpcTaskStatus, RpcTaskTypes}; -use std::time::Duration; + +use crate::mm2::lp_native_dex::init_context::MmInitContext; pub type InitMetamaskManagerShared = RpcTaskManagerShared; pub type InitMetamaskStatus = diff --git a/mm2src/mm2_main/src/lp_message_service.rs b/mm2src/mm2_main/src/lp_message_service.rs index 018d6bf971..2bea6075da 100644 --- a/mm2src/mm2_main/src/lp_message_service.rs +++ b/mm2src/mm2_main/src/lp_message_service.rs @@ -1,6 +1,7 @@ #[path = "notification/telegram/telegram.rs"] pub mod telegram; -use crate::mm2::lp_message_service::telegram::{ChatIdRegistry, TelegramError, TgClient}; +use std::sync::Arc; + use async_trait::async_trait; use derive_more::Display; use futures::lock::Mutex as AsyncMutex; @@ -8,7 +9,8 @@ use mm2_core::mm_ctx::from_ctx; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; use serde_json::{self as json}; -use std::sync::Arc; + +use crate::mm2::lp_message_service::telegram::{ChatIdRegistry, TelegramError, TgClient}; pub type MessageResult = Result>; pub const MAKER_BOT_ROOM_ID: &str = "maker_bot"; @@ -121,12 +123,14 @@ pub async fn init_message_service(ctx: &MmArc) -> Result<(), MmError = Result>; +use super::{MakerOrder, MakerOrderCancellationReason, MyOrdersFilter, Order, RecentOrdersSelectResult, TakerOrder, + TakerOrderCancellationReason}; -#[cfg(target_arch = "wasm32")] -pub use wasm_impl::MyOrdersStorage; +pub type MyOrdersResult = Result>; #[cfg(not(target_arch = "wasm32"))] pub use native_impl::MyOrdersStorage; +#[cfg(target_arch = "wasm32")] +pub use wasm_impl::MyOrdersStorage; #[derive(Debug, Display, Eq, PartialEq)] pub enum MyOrdersError { @@ -204,13 +204,14 @@ pub trait MyOrdersFilteringHistory { #[cfg(not(target_arch = "wasm32"))] mod native_impl { + use mm2_io::fs::{read_dir_json, read_json, remove_file_async, write_json, FsJsonError}; + use super::*; use crate::mm2::database::my_orders::{insert_maker_order, insert_taker_order, select_orders_by_filter, select_status_by_uuid, update_maker_order, update_order_status, update_was_taker}; use crate::mm2::lp_ordermatch::{my_maker_order_file_path, my_maker_orders_dir, my_order_history_file_path, my_taker_order_file_path, my_taker_orders_dir}; - use mm2_io::fs::{read_dir_json, read_json, remove_file_async, write_json, FsJsonError}; const USE_TMP_FILE: bool = false; @@ -349,15 +350,17 @@ mod native_impl { #[cfg(target_arch = "wasm32")] mod wasm_impl { + use std::sync::Arc; + + use common::log::warn; + use mm2_rpc::data::legacy::TakerAction; + use num_traits::ToPrimitive; + use super::*; use crate::mm2::lp_ordermatch::ordermatch_wasm_db::{DbTransactionError, InitDbError, MyActiveMakerOrdersTable, MyActiveTakerOrdersTable, MyFilteringHistoryOrdersTable, MyHistoryOrdersTable}; use crate::mm2::lp_ordermatch::OrdermatchContext; - use common::log::warn; - use mm2_rpc::data::legacy::TakerAction; - use num_traits::ToPrimitive; - use std::sync::Arc; impl From for MyOrdersError { fn from(e: InitDbError) -> Self { MyOrdersError::InternalError(e.to_string()) } @@ -692,19 +695,21 @@ mod wasm_impl { #[cfg(target_arch = "wasm32")] mod tests { - use super::wasm_impl::{maker_order_to_filtering_history_item, taker_order_to_filtering_history_item}; - use super::*; - use crate::mm2::lp_ordermatch::ordermatch_wasm_db::{ItemId, MyFilteringHistoryOrdersTable}; - use crate::mm2::lp_ordermatch::{OrdermatchContext, TakerRequest}; + use std::collections::HashMap; + use common::{new_uuid, now_ms}; use futures::compat::Future01CompatExt; use itertools::Itertools; use mm2_core::mm_ctx::MmCtxBuilder; use mm2_db::indexed_db::TableSignature; use mm2_rpc::data::legacy::{MatchBy, OrderType, TakerAction}; - use std::collections::HashMap; use wasm_bindgen_test::*; + use super::wasm_impl::{maker_order_to_filtering_history_item, taker_order_to_filtering_history_item}; + use super::*; + use crate::mm2::lp_ordermatch::ordermatch_wasm_db::{ItemId, MyFilteringHistoryOrdersTable}; + use crate::mm2::lp_ordermatch::{OrdermatchContext, TakerRequest}; + wasm_bindgen_test_configure!(run_in_browser); fn maker_order_for_test() -> MakerOrder { diff --git a/mm2src/mm2_main/src/lp_ordermatch/new_protocol.rs b/mm2src/mm2_main/src/lp_ordermatch/new_protocol.rs index b15f5e6d38..55c5838b1b 100644 --- a/mm2src/mm2_main/src/lp_ordermatch/new_protocol.rs +++ b/mm2src/mm2_main/src/lp_ordermatch/new_protocol.rs @@ -1,8 +1,9 @@ +use std::collections::{HashMap, HashSet}; + use common::now_sec; use compact_uuid::CompactUuid; use mm2_number::{BigRational, MmNumber}; use mm2_rpc::data::legacy::{MatchBy as SuperMatchBy, OrderConfirmationsSettings, TakerAction}; -use std::collections::{HashMap, HashSet}; use uuid::Uuid; use crate::mm2::lp_ordermatch::{AlbOrderedOrderbookPair, H64}; @@ -60,8 +61,9 @@ impl From for SuperMatchBy { } mod compact_uuid { - use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::str::FromStr; + + use serde::{Deserialize, Deserializer, Serialize, Serializer}; use uuid::Uuid; /// Default MsgPack encoded UUID length is 38 bytes (seems like it is encoded as string) diff --git a/mm2src/mm2_main/src/lp_ordermatch/order_requests_tracker.rs b/mm2src/mm2_main/src/lp_ordermatch/order_requests_tracker.rs index 0c9a8d3bdd..0f66996174 100644 --- a/mm2src/mm2_main/src/lp_ordermatch/order_requests_tracker.rs +++ b/mm2src/mm2_main/src/lp_ordermatch/order_requests_tracker.rs @@ -1,9 +1,10 @@ #![allow(dead_code)] -use instant::Instant; use std::{collections::hash_map::{HashMap, RawEntryMut}, num::NonZeroUsize, time::Duration}; +use instant::Instant; + const ONE_SECOND: Duration = Duration::from_secs(1); /// Stores the timestamps of order requests sent to specific peer @@ -58,9 +59,10 @@ impl OrderRequestsTracker { #[cfg(test)] mod order_requests_tracker_tests { - use super::*; use std::{thread::sleep, time::Duration}; + use super::*; + // TODO investigate why this fails on MacOS #[test] #[ignore] diff --git a/mm2src/mm2_main/src/lp_ordermatch/orderbook_depth.rs b/mm2src/mm2_main/src/lp_ordermatch/orderbook_depth.rs index dcc991a361..dbd85fa946 100644 --- a/mm2src/mm2_main/src/lp_ordermatch/orderbook_depth.rs +++ b/mm2src/mm2_main/src/lp_ordermatch/orderbook_depth.rs @@ -1,11 +1,13 @@ -use super::{orderbook_topic_from_base_rel, OrdermatchContext, OrdermatchRequest}; -use crate::mm2::lp_network::{request_any_relay, P2PRequest}; +use std::collections::HashMap; + use coins::is_wallet_only_ticker; use common::log; use http::Response; use mm2_core::mm_ctx::MmArc; use serde_json::{self as json, Value as Json}; -use std::collections::HashMap; + +use super::{orderbook_topic_from_base_rel, OrdermatchContext, OrdermatchRequest}; +use crate::mm2::lp_network::{request_any_relay, P2PRequest}; #[derive(Debug, Deserialize)] struct OrderbookDepthReq { diff --git a/mm2src/mm2_main/src/lp_ordermatch/ordermatch_wasm_db.rs b/mm2src/mm2_main/src/lp_ordermatch/ordermatch_wasm_db.rs index 812a802999..76ccaa8876 100644 --- a/mm2src/mm2_main/src/lp_ordermatch/ordermatch_wasm_db.rs +++ b/mm2src/mm2_main/src/lp_ordermatch/ordermatch_wasm_db.rs @@ -1,13 +1,13 @@ -use async_trait::async_trait; -use mm2_db::indexed_db::{DbIdentifier, DbInstance, DbUpgrader, IndexedDb, IndexedDbBuilder, OnUpgradeResult, - TableSignature}; use std::ops::Deref; -use uuid::Uuid; +use async_trait::async_trait; pub use mm2_db::indexed_db::{cursor_prelude, DbTransactionError, DbTransactionResult, InitDbError, InitDbResult, ItemId}; +use mm2_db::indexed_db::{DbIdentifier, DbInstance, DbUpgrader, IndexedDb, IndexedDbBuilder, OnUpgradeResult, + TableSignature}; pub use tables::{MyActiveMakerOrdersTable, MyActiveTakerOrdersTable, MyFilteringHistoryOrdersTable, MyHistoryOrdersTable}; +use uuid::Uuid; const DB_NAME: &str = "ordermatch"; const DB_VERSION: u32 = 1; @@ -40,9 +40,10 @@ impl Deref for OrdermatchDb { } pub mod tables { + use serde_json::Value as Json; + use super::*; use crate::mm2::lp_ordermatch::{MakerOrder, Order, TakerOrder}; - use serde_json::Value as Json; #[derive(Debug, Deserialize, Eq, PartialEq, Serialize)] pub struct MyActiveMakerOrdersTable { diff --git a/mm2src/mm2_main/src/lp_ordermatch/simple_market_maker.rs b/mm2src/mm2_main/src/lp_ordermatch/simple_market_maker.rs index 4fde30b8ee..bdff58e71a 100644 --- a/mm2src/mm2_main/src/lp_ordermatch/simple_market_maker.rs +++ b/mm2src/mm2_main/src/lp_ordermatch/simple_market_maker.rs @@ -1,14 +1,5 @@ -use crate::mm2::lp_dispatcher::{dispatch_lp_event, DispatcherContext}; -use crate::mm2::lp_ordermatch::lp_bot::{RunningState, StoppedState, StoppingState, TradingBotStarted, - TradingBotStopped, TradingBotStopping, VolumeSettings}; -use crate::mm2::lp_ordermatch::{cancel_all_orders, CancelBy, TradingBotEvent}; -use crate::mm2::lp_swap::SavedSwap; -use crate::mm2::{lp_ordermatch::{cancel_order, create_maker_order, - lp_bot::{SimpleCoinMarketMakerCfg, SimpleMakerBotRegistry, TradingBotContext, - TradingBotState}, - update_maker_order, CancelOrderReq, MakerOrder, MakerOrderUpdateReq, - OrdermatchContext, SetPriceReq}, - lp_swap::{latest_swaps_for_pair, LatestSwapsErr}}; +use std::collections::{HashMap, HashSet}; + use coins::lp_price::{fetch_price_tickers, Provider, RateInfos}; use coins::{lp_coinfind, GetNonZeroBalance}; use common::{executor::{SpawnFuture, Timer}, @@ -19,9 +10,20 @@ use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; use mm2_number::MmNumber; use serde_json::Value as Json; -use std::collections::{HashMap, HashSet}; use uuid::Uuid; +use crate::mm2::lp_dispatcher::{dispatch_lp_event, DispatcherContext}; +use crate::mm2::lp_ordermatch::lp_bot::{RunningState, StoppedState, StoppingState, TradingBotStarted, + TradingBotStopped, TradingBotStopping, VolumeSettings}; +use crate::mm2::lp_ordermatch::{cancel_all_orders, CancelBy, TradingBotEvent}; +use crate::mm2::lp_swap::SavedSwap; +use crate::mm2::{lp_ordermatch::{cancel_order, create_maker_order, + lp_bot::{SimpleCoinMarketMakerCfg, SimpleMakerBotRegistry, TradingBotContext, + TradingBotState}, + update_maker_order, CancelOrderReq, MakerOrder, MakerOrderUpdateReq, + OrdermatchContext, SetPriceReq}, + lp_swap::{latest_swaps_for_pair, LatestSwapsErr}}; + // !< constants pub const KMD_PRICE_ENDPOINT: &str = "https://prices.komodo.earth/api/v2/tickers"; pub const BOT_DEFAULT_REFRESH_RATE: f64 = 30.0; @@ -778,11 +780,12 @@ pub async fn stop_simple_market_maker_bot(ctx: MmArc, _req: Json) -> StopSimpleM #[cfg(test)] mod tests { - use super::{start_simple_market_maker_bot, stop_simple_market_maker_bot, StartSimpleMakerBotRequest}; use common::block_on; use mm2_test_helpers::for_tests::mm_ctx_with_iguana; use serde_json::Value as Json; + use super::{start_simple_market_maker_bot, stop_simple_market_maker_bot, StartSimpleMakerBotRequest}; + #[test] fn test_start_and_stop_simple_market_maker_bot_from_ctx() { let ctx = mm_ctx_with_iguana(Some( diff --git a/mm2src/mm2_main/src/lp_ordermatch/simple_market_maker_tests.rs b/mm2src/mm2_main/src/lp_ordermatch/simple_market_maker_tests.rs index 8928656415..d4821d536c 100644 --- a/mm2src/mm2_main/src/lp_ordermatch/simple_market_maker_tests.rs +++ b/mm2src/mm2_main/src/lp_ordermatch/simple_market_maker_tests.rs @@ -1,8 +1,9 @@ +use common::{block_on, log::UnifiedLoggerBuilder}; +use mm2_number::MmNumber; + use crate::mm2::{lp_ordermatch::lp_bot::simple_market_maker_bot::vwap, lp_ordermatch::lp_bot::SimpleCoinMarketMakerCfg, lp_swap::{MakerSavedSwap, SavedSwap}}; -use common::{block_on, log::UnifiedLoggerBuilder}; -use mm2_number::MmNumber; fn generate_swaps_from_values(swaps_value: Vec<(MmNumber, MmNumber)>) -> Vec { swaps_value diff --git a/mm2src/mm2_main/src/lp_stats.rs b/mm2src/mm2_main/src/lp_stats.rs index 8a064c1d70..417a9e1dbd 100644 --- a/mm2src/mm2_main/src/lp_stats.rs +++ b/mm2src/mm2_main/src/lp_stats.rs @@ -1,3 +1,7 @@ +use std::collections::{HashMap, HashSet}; +use std::str::FromStr; +use std::sync::Arc; + /// The module is responsible for mm2 network stats collection /// use common::executor::{SpawnFuture, Timer}; @@ -9,12 +13,9 @@ use mm2_core::mm_ctx::{from_ctx, MmArc}; use mm2_err_handle::prelude::*; use mm2_libp2p::{encode_message, NetworkInfo, PeerId, RelayAddress, RelayAddressError}; use serde_json::{self as json, Value as Json}; -use std::collections::{HashMap, HashSet}; -use std::sync::Arc; use crate::mm2::lp_network::{add_reserved_peer_addresses, lp_network_ports, request_peers, NetIdError, P2PRequest, ParseAddressError, PeerDecodedResponse}; -use std::str::FromStr; pub type NodeVersionResult = Result>; diff --git a/mm2src/mm2_main/src/lp_swap.rs b/mm2src/mm2_main/src/lp_swap.rs index 3fa86a7bd2..2dfacee3dd 100644 --- a/mm2src/mm2_main/src/lp_swap.rs +++ b/mm2src/mm2_main/src/lp_swap.rs @@ -57,8 +57,15 @@ // marketmaker // -use super::lp_network::P2PRequestResult; -use crate::mm2::lp_network::{broadcast_p2p_msg, Libp2pPeerId, P2PProcessError, P2PProcessResult, P2PRequestError}; +use std::collections::{HashMap, HashSet}; +use std::num::NonZeroUsize; +use std::path::PathBuf; +use std::str::FromStr; +#[cfg(feature = "custom-swap-locktime")] +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, Weak}; +use std::time::Duration; + use bitcrypto::{dhash160, sha256}; use coins::{lp_coinfind, lp_coinfind_or_err, CoinFindError, MmCoin, MmCoinEnum, TradeFee, TransactionEnum}; use common::log::{debug, warn}; @@ -79,16 +86,10 @@ use rpc::v1::types::{Bytes as BytesJson, H256 as H256Json}; use secp256k1::{PublicKey, SecretKey, Signature}; use serde::Serialize; use serde_json::{self as json, Value as Json}; -use std::collections::{HashMap, HashSet}; -use std::num::NonZeroUsize; -use std::path::PathBuf; -use std::str::FromStr; -use std::sync::{Arc, Mutex, Weak}; -use std::time::Duration; use uuid::Uuid; -#[cfg(feature = "custom-swap-locktime")] -use std::sync::atomic::{AtomicU64, Ordering}; +use super::lp_network::P2PRequestResult; +use crate::mm2::lp_network::{broadcast_p2p_msg, Libp2pPeerId, P2PProcessError, P2PProcessResult, P2PRequestError}; #[path = "lp_swap/check_balance.rs"] mod check_balance; #[path = "lp_swap/maker_swap.rs"] mod maker_swap; @@ -1574,8 +1575,6 @@ async fn recv_swap_v2_msg( #[cfg(all(test, not(target_arch = "wasm32")))] mod lp_swap_tests { - use super::*; - use crate::mm2::lp_native_dex::{fix_directories, init_p2p}; use coins::utxo::rpc_clients::ElectrumRpcRequest; use coins::utxo::utxo_standard::utxo_standard_coin_with_priv_key; use coins::utxo::{UtxoActivationParams, UtxoRpcMode}; @@ -1586,6 +1585,9 @@ mod lp_swap_tests { use mm2_core::mm_ctx::MmCtxBuilder; use mm2_test_helpers::for_tests::{morty_conf, rick_conf, MORTY_ELECTRUM_ADDRS, RICK_ELECTRUM_ADDRS}; + use super::*; + use crate::mm2::lp_native_dex::{fix_directories, init_p2p}; + #[test] fn test_dex_fee_amount() { let min_tx_amount = MmNumber::from("0.0001"); diff --git a/mm2src/mm2_main/src/lp_swap/check_balance.rs b/mm2src/mm2_main/src/lp_swap/check_balance.rs index 5590679f6f..c871afc317 100644 --- a/mm2src/mm2_main/src/lp_swap/check_balance.rs +++ b/mm2src/mm2_main/src/lp_swap/check_balance.rs @@ -1,5 +1,3 @@ -use super::taker_swap::MaxTakerVolumeLessThanDust; -use super::{get_locked_amount, get_locked_amount_by_other_swaps}; use coins::{BalanceError, MmCoin, TradeFee, TradePreimageError}; use common::log::debug; use derive_more::Display; @@ -9,6 +7,9 @@ use mm2_err_handle::prelude::*; use mm2_number::{BigDecimal, MmNumber}; use uuid::Uuid; +use super::taker_swap::MaxTakerVolumeLessThanDust; +use super::{get_locked_amount, get_locked_amount_by_other_swaps}; + pub type CheckBalanceResult = Result>; /// Check the coin balance before the swap has started. diff --git a/mm2src/mm2_main/src/lp_swap/maker_swap.rs b/mm2src/mm2_main/src/lp_swap/maker_swap.rs index 7c51fe0c30..2bd0596fa5 100644 --- a/mm2src/mm2_main/src/lp_swap/maker_swap.rs +++ b/mm2src/mm2_main/src/lp_swap/maker_swap.rs @@ -1,19 +1,9 @@ -use super::check_balance::{check_base_coin_balance_for_swap, check_my_coin_balance_for_swap, CheckBalanceError, - CheckBalanceResult}; -use super::pubkey_banning::ban_pubkey_on_failed_swap; -use super::swap_lock::{SwapLock, SwapLockOps}; -use super::trade_preimage::{TradePreimageRequest, TradePreimageRpcError, TradePreimageRpcResult}; -use super::{broadcast_my_swap_status, broadcast_p2p_tx_msg, broadcast_swap_msg_every, - check_other_coin_balance_for_swap, detect_secret_hash_algo, dex_fee_amount_from_taker_coin, - 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, WAIT_CONFIRM_INTERVAL_SEC}; -use crate::mm2::lp_dispatcher::{DispatcherContext, LpEvents}; -use crate::mm2::lp_network::subscribe_to_topic; -use crate::mm2::lp_ordermatch::MakerOrderBuilder; -use crate::mm2::lp_swap::{broadcast_swap_message, taker_payment_spend_duration}; +use std::any::TypeId; +use std::ops::Deref; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard}; + use coins::lp_price::fetch_swap_coins_price; use coins::{CanRefundHtlc, CheckIfMyPaymentSentArgs, ConfirmPaymentInput, FeeApproxStage, FoundSwapTxSpend, MmCoin, MmCoinEnum, PaymentInstructionArgs, PaymentInstructions, PaymentInstructionsErr, RefundPaymentArgs, @@ -33,13 +23,25 @@ use mm2_rpc::data::legacy::OrderConfirmationsSettings; use parking_lot::Mutex as PaMutex; use primitives::hash::{H256, H264}; use rpc::v1::types::{Bytes as BytesJson, H256 as H256Json, H264 as H264Json}; -use std::any::TypeId; -use std::ops::Deref; -use std::path::PathBuf; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard}; use uuid::Uuid; +use super::check_balance::{check_base_coin_balance_for_swap, check_my_coin_balance_for_swap, CheckBalanceError, + CheckBalanceResult}; +use super::pubkey_banning::ban_pubkey_on_failed_swap; +use super::swap_lock::{SwapLock, SwapLockOps}; +use super::trade_preimage::{TradePreimageRequest, TradePreimageRpcError, TradePreimageRpcResult}; +use super::{broadcast_my_swap_status, broadcast_p2p_tx_msg, broadcast_swap_msg_every, + check_other_coin_balance_for_swap, detect_secret_hash_algo, dex_fee_amount_from_taker_coin, + 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, WAIT_CONFIRM_INTERVAL_SEC}; +use crate::mm2::lp_dispatcher::{DispatcherContext, LpEvents}; +use crate::mm2::lp_network::subscribe_to_topic; +use crate::mm2::lp_ordermatch::MakerOrderBuilder; +use crate::mm2::lp_swap::{broadcast_swap_message, taker_payment_spend_duration}; + pub const MAKER_SUCCESS_EVENTS: [&str; 12] = [ "Started", "Negotiated", @@ -2345,7 +2347,6 @@ pub async fn calc_max_maker_vol( #[cfg(all(test, not(target_arch = "wasm32")))] mod maker_swap_tests { - use super::*; use coins::eth::{addr_from_str, signed_eth_tx_from_bytes, SignedEthTx}; use coins::{MarketCoinOps, MmCoin, SwapOps, TestCoin}; use common::block_on; @@ -2353,6 +2354,8 @@ mod maker_swap_tests { use mocktopus::mocking::*; use serde_json as json; + use super::*; + const PASSPHRASE: Option<&str> = Some("spice describe gravity federal blast come thank unfair canal monkey style afraid"); diff --git a/mm2src/mm2_main/src/lp_swap/maker_swap_v2.rs b/mm2src/mm2_main/src/lp_swap/maker_swap_v2.rs index eb601df2e2..a8bd038d0f 100644 --- a/mm2src/mm2_main/src/lp_swap/maker_swap_v2.rs +++ b/mm2src/mm2_main/src/lp_swap/maker_swap_v2.rs @@ -1,8 +1,6 @@ -use super::{NEGOTIATE_SEND_INTERVAL, NEGOTIATION_TIMEOUT_SEC}; -use crate::mm2::lp_network::subscribe_to_topic; -use crate::mm2::lp_swap::swap_v2_pb::*; -use crate::mm2::lp_swap::{broadcast_swap_v2_msg_every, check_balance_for_maker_swap, recv_swap_v2_msg, SecretHashAlgo, - SwapConfirmationsSettings, SwapsContext, TransactionIdentifier}; +use std::collections::HashMap; +use std::marker::PhantomData; + use async_trait::async_trait; use bitcrypto::{dhash160, sha256}; use coins::{ConfirmPaymentInput, FeeApproxStage, GenTakerPaymentSpendArgs, MarketCoinOps, MmCoin, SendPaymentArgs, @@ -15,12 +13,15 @@ use mm2_number::MmNumber; use mm2_state_machine::prelude::*; use mm2_state_machine::storable_state_machine::*; use primitives::hash::H256; -use std::collections::HashMap; -use std::marker::PhantomData; -use uuid::Uuid; - // This is needed to have Debug on messages #[allow(unused_imports)] use prost::Message; +use uuid::Uuid; + +use super::{NEGOTIATE_SEND_INTERVAL, NEGOTIATION_TIMEOUT_SEC}; +use crate::mm2::lp_network::subscribe_to_topic; +use crate::mm2::lp_swap::swap_v2_pb::*; +use crate::mm2::lp_swap::{broadcast_swap_v2_msg_every, check_balance_for_maker_swap, recv_swap_v2_msg, SecretHashAlgo, + SwapConfirmationsSettings, SwapsContext, TransactionIdentifier}; /// Represents events produced by maker swap states. #[derive(Debug, PartialEq)] diff --git a/mm2src/mm2_main/src/lp_swap/max_maker_vol_rpc.rs b/mm2src/mm2_main/src/lp_swap/max_maker_vol_rpc.rs index cceb5cb3ed..1c7df892ea 100644 --- a/mm2src/mm2_main/src/lp_swap/max_maker_vol_rpc.rs +++ b/mm2src/mm2_main/src/lp_swap/max_maker_vol_rpc.rs @@ -1,4 +1,3 @@ -use crate::mm2::lp_swap::{get_max_maker_vol, CheckBalanceError, CoinVolumeInfo}; use coins::{lp_coinfind_or_err, CoinFindError}; use common::HttpStatusCode; use derive_more::Display; @@ -8,6 +7,8 @@ use mm2_err_handle::prelude::*; use mm2_number::{BigDecimal, MmNumberMultiRepr}; use ser_error_derive::SerializeErrorType; +use crate::mm2::lp_swap::{get_max_maker_vol, CheckBalanceError, CoinVolumeInfo}; + #[derive(Display, Serialize, SerializeErrorType)] #[serde(tag = "error_type", content = "error_data")] pub enum MaxMakerVolRpcError { diff --git a/mm2src/mm2_main/src/lp_swap/my_swaps_storage.rs b/mm2src/mm2_main/src/lp_swap/my_swaps_storage.rs index b396a4f54a..46148be142 100644 --- a/mm2src/mm2_main/src/lp_swap/my_swaps_storage.rs +++ b/mm2src/mm2_main/src/lp_swap/my_swaps_storage.rs @@ -1,4 +1,3 @@ -use super::{MyRecentSwapsUuids, MySwapsFilter}; use async_trait::async_trait; use common::PagingOptions; use derive_more::Display; @@ -6,6 +5,8 @@ use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; use uuid::Uuid; +use super::{MyRecentSwapsUuids, MySwapsFilter}; + pub type MySwapsResult = Result>; #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] @@ -50,9 +51,10 @@ impl MySwapsStorage { #[cfg(not(target_arch = "wasm32"))] mod native_impl { + use db_common::sqlite::rusqlite::Error as SqlError; + use super::*; use crate::mm2::database::my_swaps::{insert_new_swap, select_uuids_by_my_swaps_filter, SelectRecentSwapsUuidsErr}; - use db_common::sqlite::rusqlite::Error as SqlError; impl From for MySwapsError { fn from(e: SelectRecentSwapsUuidsErr) -> Self { @@ -101,12 +103,14 @@ mod native_impl { #[cfg(target_arch = "wasm32")] mod wasm_impl { + use std::collections::BTreeSet; + + use uuid::Uuid; + use super::*; use crate::mm2::lp_swap::swap_wasm_db::cursor_prelude::*; use crate::mm2::lp_swap::swap_wasm_db::{DbTransactionError, InitDbError, MySwapsFiltersTable}; use crate::mm2::lp_swap::SwapsContext; - use std::collections::BTreeSet; - use uuid::Uuid; impl From for MySwapsError { fn from(e: DbTransactionError) -> Self { @@ -309,19 +313,21 @@ mod wasm_impl { #[cfg(target_arch = "wasm32")] mod wasm_tests { - use super::wasm_impl::*; - use super::*; + use std::collections::BTreeSet; + use std::num::NonZeroUsize; + use std::ops::Range; + use common::log::wasm_log::register_wasm_log; use common::new_uuid; use mm2_core::mm_ctx::MmCtxBuilder; use rand::seq::SliceRandom; use rand::Rng; - use std::collections::BTreeSet; - use std::num::NonZeroUsize; - use std::ops::Range; use uuid::Uuid; use wasm_bindgen_test::*; + use super::wasm_impl::*; + use super::*; + wasm_bindgen_test_configure!(run_in_browser); fn is_applied(filters: &MySwapsFilter, my_coin: &str, other_coin: &str, started_at: u64) -> bool { diff --git a/mm2src/mm2_main/src/lp_swap/pubkey_banning.rs b/mm2src/mm2_main/src/lp_swap/pubkey_banning.rs index 5aa8f94103..d6250e6589 100644 --- a/mm2src/mm2_main/src/lp_swap/pubkey_banning.rs +++ b/mm2src/mm2_main/src/lp_swap/pubkey_banning.rs @@ -1,12 +1,14 @@ -use super::{SwapEvent, SwapsContext}; +use std::collections::hash_map::{Entry, HashMap}; + use chain::hash::H256; use http::Response; use mm2_core::mm_ctx::MmArc; use rpc::v1::types::H256 as H256Json; use serde_json::{self as json, Value as Json}; -use std::collections::hash_map::{Entry, HashMap}; use uuid::Uuid; +use super::{SwapEvent, SwapsContext}; + #[derive(Serialize)] #[serde(tag = "type")] #[allow(clippy::large_enum_variant)] diff --git a/mm2src/mm2_main/src/lp_swap/recreate_swap_data.rs b/mm2src/mm2_main/src/lp_swap/recreate_swap_data.rs index a816695d84..ee6bdd6c65 100644 --- a/mm2src/mm2_main/src/lp_swap/recreate_swap_data.rs +++ b/mm2src/mm2_main/src/lp_swap/recreate_swap_data.rs @@ -1,9 +1,3 @@ -use crate::mm2::lp_swap::maker_swap::{MakerSwapData, MakerSwapEvent, TakerNegotiationData, MAKER_ERROR_EVENTS, - MAKER_SUCCESS_EVENTS}; -use crate::mm2::lp_swap::taker_swap::{MakerNegotiationData, TakerPaymentSpentData, TakerSavedEvent, TakerSwapData, - TakerSwapEvent, TAKER_ERROR_EVENTS, TAKER_SUCCESS_EVENTS}; -use crate::mm2::lp_swap::{wait_for_maker_payment_conf_until, MakerSavedEvent, MakerSavedSwap, SavedSwap, SwapError, - TakerSavedSwap}; use coins::{lp_coinfind, MmCoinEnum}; use common::{HttpStatusCode, StatusCode}; use derive_more::Display; @@ -11,6 +5,13 @@ use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; use rpc::v1::types::{Bytes as BytesJson, H256 as H256Json}; +use crate::mm2::lp_swap::maker_swap::{MakerSwapData, MakerSwapEvent, TakerNegotiationData, MAKER_ERROR_EVENTS, + MAKER_SUCCESS_EVENTS}; +use crate::mm2::lp_swap::taker_swap::{MakerNegotiationData, TakerPaymentSpentData, TakerSavedEvent, TakerSwapData, + TakerSwapEvent, TAKER_ERROR_EVENTS, TAKER_SUCCESS_EVENTS}; +use crate::mm2::lp_swap::{wait_for_maker_payment_conf_until, MakerSavedEvent, MakerSavedSwap, SavedSwap, SwapError, + TakerSavedSwap}; + pub type RecreateSwapResult = Result>; #[derive(Debug, Display, Serialize, SerializeErrorType)] @@ -488,13 +489,14 @@ async fn convert_maker_to_taker_events( #[cfg(test)] mod tests { - use super::*; use coins::{CoinsContext, MarketCoinOps, SwapOps, TestCoin}; use common::block_on; use mm2_core::mm_ctx::MmCtxBuilder; use mocktopus::mocking::{MockResult, Mockable}; use serde_json as json; + use super::*; + #[test] fn test_recreate_maker_swap() { let taker_saved_swap: TakerSavedSwap = diff --git a/mm2src/mm2_main/src/lp_swap/saved_swap.rs b/mm2src/mm2_main/src/lp_swap/saved_swap.rs index 3519d45596..a523ab0af8 100644 --- a/mm2src/mm2_main/src/lp_swap/saved_swap.rs +++ b/mm2src/mm2_main/src/lp_swap/saved_swap.rs @@ -1,6 +1,3 @@ -use crate::mm2::lp_swap::maker_swap::{MakerSavedSwap, MakerSwap, MakerSwapEvent}; -use crate::mm2::lp_swap::taker_swap::{TakerSavedSwap, TakerSwap, TakerSwapEvent}; -use crate::mm2::lp_swap::{MySwapInfo, RecoveredSwap}; use async_trait::async_trait; use coins::lp_coinfind; use derive_more::Display; @@ -9,6 +6,10 @@ use mm2_err_handle::prelude::*; use rpc::v1::types::H256 as H256Json; use uuid::Uuid; +use crate::mm2::lp_swap::maker_swap::{MakerSavedSwap, MakerSwap, MakerSwapEvent}; +use crate::mm2::lp_swap::taker_swap::{TakerSavedSwap, TakerSwap, TakerSwapEvent}; +use crate::mm2::lp_swap::{MySwapInfo, RecoveredSwap}; + pub type SavedSwapResult = Result>; #[derive(Debug, Display, Deserialize, Serialize)] @@ -173,11 +174,12 @@ pub trait SavedSwapIo { #[cfg(not(target_arch = "wasm32"))] mod native_impl { + use mm2_io::fs::{read_dir_json, read_json, write_json, FsJsonError}; + use super::*; use crate::mm2::lp_swap::maker_swap::{stats_maker_swap_dir, stats_maker_swap_file_path}; use crate::mm2::lp_swap::taker_swap::{stats_taker_swap_dir, stats_taker_swap_file_path}; use crate::mm2::lp_swap::{my_swap_file_path, my_swaps_dir}; - use mm2_io::fs::{read_dir_json, read_json, write_json, FsJsonError}; const USE_TMP_FILE: bool = false; @@ -251,10 +253,11 @@ mod native_impl { #[cfg(target_arch = "wasm32")] mod wasm_impl { + use serde_json as json; + use super::*; use crate::mm2::lp_swap::swap_wasm_db::{DbTransactionError, InitDbError, SavedSwapTable}; use crate::mm2::lp_swap::SwapsContext; - use serde_json as json; impl From for SavedSwapError { fn from(e: DbTransactionError) -> Self { @@ -338,13 +341,14 @@ mod wasm_impl { #[cfg(target_arch = "wasm32")] mod tests { - use super::*; - use crate::mm2::lp_swap::swap_wasm_db::{ItemId, SavedSwapTable}; - use crate::mm2::lp_swap::SwapsContext; use mm2_core::mm_ctx::MmCtxBuilder; use serde_json as json; use wasm_bindgen_test::*; + use super::*; + use crate::mm2::lp_swap::swap_wasm_db::{ItemId, SavedSwapTable}; + use crate::mm2::lp_swap::SwapsContext; + wasm_bindgen_test_configure!(run_in_browser); async fn get_all_items(ctx: &MmArc) -> Vec<(ItemId, SavedSwapTable)> { diff --git a/mm2src/mm2_main/src/lp_swap/swap_lock.rs b/mm2src/mm2_main/src/lp_swap/swap_lock.rs index 25e752d14b..39a8bf7470 100644 --- a/mm2src/mm2_main/src/lp_swap/swap_lock.rs +++ b/mm2src/mm2_main/src/lp_swap/swap_lock.rs @@ -1,12 +1,11 @@ use async_trait::async_trait; +#[cfg(target_arch = "wasm32")] use common::now_sec; use derive_more::Display; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; -use uuid::Uuid; - -#[cfg(target_arch = "wasm32")] use common::now_sec; #[cfg(not(target_arch = "wasm32"))] pub use native_lock::SwapLock; +use uuid::Uuid; #[cfg(target_arch = "wasm32")] pub use wasm_lock::SwapLock; pub type SwapLockResult = Result>; @@ -31,10 +30,12 @@ pub trait SwapLockOps: Sized { #[cfg(not(target_arch = "wasm32"))] mod native_lock { + use std::path::PathBuf; + + use mm2_io::file_lock::{FileLock, FileLockError}; + use super::*; use crate::mm2::lp_swap::my_swaps_dir; - use mm2_io::file_lock::{FileLock, FileLockError}; - use std::path::PathBuf; impl From for SwapLockError { fn from(e: FileLockError) -> Self { @@ -69,13 +70,14 @@ mod native_lock { #[cfg(target_arch = "wasm32")] mod wasm_lock { - use super::*; - use crate::mm2::lp_swap::swap_wasm_db::{DbTransactionError, InitDbError, ItemId, SwapLockTable}; - use crate::mm2::lp_swap::SwapsContext; use common::executor::SpawnFuture; use common::log::{debug, error}; use common::{now_float, now_ms}; + use super::*; + use crate::mm2::lp_swap::swap_wasm_db::{DbTransactionError, InitDbError, ItemId, SwapLockTable}; + use crate::mm2::lp_swap::SwapsContext; + impl From for SwapLockError { fn from(e: DbTransactionError) -> Self { match e { @@ -192,10 +194,6 @@ mod wasm_lock { #[cfg(target_arch = "wasm32")] mod tests { - use super::wasm_lock::*; - use super::*; - use crate::mm2::lp_swap::swap_wasm_db::SwapLockTable; - use crate::mm2::lp_swap::SwapsContext; use common::executor::Timer; use common::new_uuid; use common::now_ms; @@ -203,6 +201,11 @@ mod tests { use mm2_db::indexed_db::ItemId; use wasm_bindgen_test::*; + use super::wasm_lock::*; + use super::*; + use crate::mm2::lp_swap::swap_wasm_db::SwapLockTable; + use crate::mm2::lp_swap::SwapsContext; + wasm_bindgen_test_configure!(run_in_browser); async fn get_all_items(ctx: &MmArc) -> Vec<(ItemId, SwapLockTable)> { diff --git a/mm2src/mm2_main/src/lp_swap/swap_wasm_db.rs b/mm2src/mm2_main/src/lp_swap/swap_wasm_db.rs index d680ba4eb8..1de89f65c0 100644 --- a/mm2src/mm2_main/src/lp_swap/swap_wasm_db.rs +++ b/mm2src/mm2_main/src/lp_swap/swap_wasm_db.rs @@ -1,12 +1,12 @@ -use async_trait::async_trait; -use mm2_db::indexed_db::{DbIdentifier, DbInstance, DbUpgrader, IndexedDb, IndexedDbBuilder, OnUpgradeResult, - TableSignature}; use std::ops::Deref; -use uuid::Uuid; +use async_trait::async_trait; pub use mm2_db::indexed_db::{cursor_prelude, DbTransactionError, DbTransactionResult, InitDbError, InitDbResult, ItemId}; +use mm2_db::indexed_db::{DbIdentifier, DbInstance, DbUpgrader, IndexedDb, IndexedDbBuilder, OnUpgradeResult, + TableSignature}; pub use tables::{MySwapsFiltersTable, SavedSwapTable, SwapLockTable}; +use uuid::Uuid; const DB_NAME: &str = "swap"; const DB_VERSION: u32 = 1; @@ -38,9 +38,10 @@ impl Deref for SwapDb { } pub mod tables { - use super::*; use serde_json::Value as Json; + use super::*; + #[derive(Debug, Deserialize, Clone, Serialize, PartialEq)] pub struct SwapLockTable { pub uuid: Uuid, diff --git a/mm2src/mm2_main/src/lp_swap/swap_watcher.rs b/mm2src/mm2_main/src/lp_swap/swap_watcher.rs index bd0d0f564f..dea5fbc868 100644 --- a/mm2src/mm2_main/src/lp_swap/swap_watcher.rs +++ b/mm2src/mm2_main/src/lp_swap/swap_watcher.rs @@ -1,7 +1,7 @@ -use super::{broadcast_p2p_tx_msg, get_payment_locktime, lp_coinfind, taker_payment_spend_deadline, tx_helper_topic, - H256Json, SwapsContext, WAIT_CONFIRM_INTERVAL_SEC}; -use crate::mm2::lp_network::{P2PRequestError, P2PRequestResult}; -use crate::mm2::MmError; +use std::cmp::min; +use std::convert::Infallible; +use std::sync::Arc; + use async_trait::async_trait; use coins::{CanRefundHtlc, ConfirmPaymentInput, FoundSwapTxSpend, MmCoinEnum, RefundPaymentArgs, SendMakerPaymentSpendPreimageInput, WaitForHTLCTxSpendArgs, WatcherSearchForSwapTxSpendInput, @@ -17,11 +17,13 @@ use mm2_state_machine::prelude::*; use mm2_state_machine::state_machine::StateMachineTrait; use serde::{Deserialize, Serialize}; use serde_json as json; -use std::cmp::min; -use std::convert::Infallible; -use std::sync::Arc; use uuid::Uuid; +use super::{broadcast_p2p_tx_msg, get_payment_locktime, lp_coinfind, taker_payment_spend_deadline, tx_helper_topic, + H256Json, SwapsContext, WAIT_CONFIRM_INTERVAL_SEC}; +use crate::mm2::lp_network::{P2PRequestError, P2PRequestResult}; +use crate::mm2::MmError; + pub const WATCHER_PREFIX: TopicPrefix = "swpwtchr"; const TAKER_SWAP_CONFIRMATIONS: u64 = 1; pub const TAKER_SWAP_ENTRY_TIMEOUT_SEC: u64 = 21600; diff --git a/mm2src/mm2_main/src/lp_swap/taker_swap.rs b/mm2src/mm2_main/src/lp_swap/taker_swap.rs index 168d8fc1ac..89ef83a030 100644 --- a/mm2src/mm2_main/src/lp_swap/taker_swap.rs +++ b/mm2src/mm2_main/src/lp_swap/taker_swap.rs @@ -1,19 +1,8 @@ -use super::check_balance::{check_my_coin_balance_for_swap, CheckBalanceError, CheckBalanceResult, - TakerFeeAdditionalInfo}; -use super::pubkey_banning::ban_pubkey_on_failed_swap; -use super::swap_lock::{SwapLock, SwapLockOps}; -use super::swap_watcher::{watcher_topic, SwapWatcherMsg}; -use super::trade_preimage::{TradePreimageRequest, TradePreimageRpcError, TradePreimageRpcResult}; -use super::{broadcast_my_swap_status, broadcast_swap_message, broadcast_swap_msg_every, - check_other_coin_balance_for_swap, dex_fee_amount_from_taker_coin, dex_fee_rate, get_locked_amount, - recv_swap_msg, swap_topic, wait_for_maker_payment_conf_until, AtomicSwap, LockedAmount, MySwapInfo, - NegotiationDataMsg, NegotiationDataV2, NegotiationDataV3, RecoveredSwap, RecoveredSwapAction, SavedSwap, - SavedSwapIo, SavedTradeFee, SwapConfirmationsSettings, SwapError, SwapMsg, SwapPubkeys, SwapTxDataMsg, - SwapsContext, TransactionIdentifier, WAIT_CONFIRM_INTERVAL_SEC}; -use crate::mm2::lp_network::subscribe_to_topic; -use crate::mm2::lp_ordermatch::TakerOrderBuilder; -use crate::mm2::lp_swap::{broadcast_p2p_tx_msg, broadcast_swap_msg_every_delayed, tx_helper_topic, - wait_for_maker_payment_conf_duration, TakerSwapWatcherData}; +use std::ops::Deref; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard}; + use coins::lp_price::fetch_swap_coins_price; use coins::{lp_coinfind, CanRefundHtlc, CheckIfMyPaymentSentArgs, ConfirmPaymentInput, FeeApproxStage, FoundSwapTxSpend, MmCoin, MmCoinEnum, PaymentInstructionArgs, PaymentInstructions, PaymentInstructionsErr, @@ -34,12 +23,25 @@ use parking_lot::Mutex as PaMutex; use primitives::hash::H264; use rpc::v1::types::{Bytes as BytesJson, H256 as H256Json, H264 as H264Json}; use serde_json::{self as json, Value as Json}; -use std::ops::Deref; -use std::path::PathBuf; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard}; use uuid::Uuid; +use super::check_balance::{check_my_coin_balance_for_swap, CheckBalanceError, CheckBalanceResult, + TakerFeeAdditionalInfo}; +use super::pubkey_banning::ban_pubkey_on_failed_swap; +use super::swap_lock::{SwapLock, SwapLockOps}; +use super::swap_watcher::{watcher_topic, SwapWatcherMsg}; +use super::trade_preimage::{TradePreimageRequest, TradePreimageRpcError, TradePreimageRpcResult}; +use super::{broadcast_my_swap_status, broadcast_swap_message, broadcast_swap_msg_every, + check_other_coin_balance_for_swap, dex_fee_amount_from_taker_coin, dex_fee_rate, get_locked_amount, + recv_swap_msg, swap_topic, wait_for_maker_payment_conf_until, AtomicSwap, LockedAmount, MySwapInfo, + NegotiationDataMsg, NegotiationDataV2, NegotiationDataV3, RecoveredSwap, RecoveredSwapAction, SavedSwap, + SavedSwapIo, SavedTradeFee, SwapConfirmationsSettings, SwapError, SwapMsg, SwapPubkeys, SwapTxDataMsg, + SwapsContext, TransactionIdentifier, WAIT_CONFIRM_INTERVAL_SEC}; +use crate::mm2::lp_network::subscribe_to_topic; +use crate::mm2::lp_ordermatch::TakerOrderBuilder; +use crate::mm2::lp_swap::{broadcast_p2p_tx_msg, broadcast_swap_msg_every_delayed, tx_helper_topic, + wait_for_maker_payment_conf_duration, TakerSwapWatcherData}; + const TAKER_PAYMENT_SPEND_SEARCH_INTERVAL: f64 = 10.; pub const TAKER_SUCCESS_EVENTS: [&str; 11] = [ @@ -2589,8 +2591,6 @@ pub fn max_taker_vol_from_available( #[cfg(all(test, not(target_arch = "wasm32")))] mod taker_swap_tests { - use super::*; - use crate::mm2::lp_swap::{dex_fee_amount, get_locked_amount_by_other_swaps}; use coins::eth::{addr_from_str, signed_eth_tx_from_bytes, SignedEthTx}; use coins::utxo::UtxoTx; use coins::{FoundSwapTxSpend, MarketCoinOps, MmCoin, SwapOps, TestCoin}; @@ -2598,6 +2598,9 @@ mod taker_swap_tests { use mm2_test_helpers::for_tests::{mm_ctx_with_iguana, ETH_DEV_SWAP_CONTRACT}; use mocktopus::mocking::*; + use super::*; + use crate::mm2::lp_swap::{dex_fee_amount, get_locked_amount_by_other_swaps}; + const PASSPHRASE: Option<&str> = Some("spice describe gravity federal blast come thank unfair canal monkey style afraid"); diff --git a/mm2src/mm2_main/src/lp_swap/taker_swap_v2.rs b/mm2src/mm2_main/src/lp_swap/taker_swap_v2.rs index e4ae68b89b..a23d6c3c32 100644 --- a/mm2src/mm2_main/src/lp_swap/taker_swap_v2.rs +++ b/mm2src/mm2_main/src/lp_swap/taker_swap_v2.rs @@ -1,8 +1,6 @@ -use super::{NEGOTIATE_SEND_INTERVAL, NEGOTIATION_TIMEOUT_SEC}; -use crate::mm2::lp_network::subscribe_to_topic; -use crate::mm2::lp_swap::swap_v2_pb::*; -use crate::mm2::lp_swap::{broadcast_swap_v2_msg_every, check_balance_for_taker_swap, recv_swap_v2_msg, - SwapConfirmationsSettings, SwapsContext, TransactionIdentifier}; +use std::collections::HashMap; +use std::marker::PhantomData; + use async_trait::async_trait; use coins::{ConfirmPaymentInput, FeeApproxStage, GenTakerPaymentSpendArgs, MmCoin, SendCombinedTakerPaymentArgs, SpendPaymentArgs, SwapOpsV2, WaitForHTLCTxSpendArgs}; @@ -13,13 +11,16 @@ use mm2_core::mm_ctx::MmArc; use mm2_number::{BigDecimal, MmNumber}; use mm2_state_machine::prelude::*; use mm2_state_machine::storable_state_machine::*; +// This is needed to have Debug on messages +#[allow(unused_imports)] use prost::Message; use rpc::v1::types::Bytes as BytesJson; -use std::collections::HashMap; -use std::marker::PhantomData; use uuid::Uuid; -// This is needed to have Debug on messages -#[allow(unused_imports)] use prost::Message; +use super::{NEGOTIATE_SEND_INTERVAL, NEGOTIATION_TIMEOUT_SEC}; +use crate::mm2::lp_network::subscribe_to_topic; +use crate::mm2::lp_swap::swap_v2_pb::*; +use crate::mm2::lp_swap::{broadcast_swap_v2_msg_every, check_balance_for_taker_swap, recv_swap_v2_msg, + SwapConfirmationsSettings, SwapsContext, TransactionIdentifier}; /// Represents events produced by taker swap states. #[derive(Debug, PartialEq)] diff --git a/mm2src/mm2_main/src/lp_swap/trade_preimage.rs b/mm2src/mm2_main/src/lp_swap/trade_preimage.rs index 7f64b052db..a99d87ae9d 100644 --- a/mm2src/mm2_main/src/lp_swap/trade_preimage.rs +++ b/mm2src/mm2_main/src/lp_swap/trade_preimage.rs @@ -1,6 +1,5 @@ -use super::check_balance::CheckBalanceError; -use super::{maker_swap_trade_preimage, taker_swap_trade_preimage, MakerTradePreimage, TakerTradePreimage}; -use crate::mm2::lp_ordermatch::{MakerOrderBuildError, TakerOrderBuildError}; +use std::collections::HashMap; + use coins::{is_wallet_only_ticker, lp_coinfind_or_err, BalanceError, CoinFindError, TradeFee, TradePreimageError}; use common::HttpStatusCode; use crypto::CryptoCtxError; @@ -10,7 +9,10 @@ use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; use mm2_number::{construct_detailed, BigDecimal, MmNumber}; use mm2_rpc::data::legacy::TakerAction; -use std::collections::HashMap; + +use super::check_balance::CheckBalanceError; +use super::{maker_swap_trade_preimage, taker_swap_trade_preimage, MakerTradePreimage, TakerTradePreimage}; +use crate::mm2::lp_ordermatch::{MakerOrderBuildError, TakerOrderBuildError}; construct_detailed!(DetailedAmount, amount); construct_detailed!(DetailedVolume, volume); diff --git a/mm2src/mm2_main/src/mm2.rs b/mm2src/mm2_main/src/mm2.rs index e343f24ba9..4266bc9daf 100644 --- a/mm2src/mm2_main/src/mm2.rs +++ b/mm2src/mm2_main/src/mm2.rs @@ -24,35 +24,33 @@ #![cfg_attr(target_arch = "wasm32", allow(dead_code))] #![cfg_attr(target_arch = "wasm32", allow(unused_imports))] +use std::env; +use std::ffi::OsString; +use std::process::exit; +use std::ptr::null; +use std::str; +#[cfg(feature = "custom-swap-locktime")] +use std::sync::atomic::Ordering; + #[cfg(not(target_arch = "wasm32"))] use common::block_on; use common::crash_reports::init_crash_reports; use common::double_panic_crash; +#[cfg(feature = "custom-swap-locktime")] use common::log::warn; use common::log::LogLevel; use common::password_policy::password_policy; -use mm2_core::mm_ctx::MmCtxBuilder; - -#[cfg(feature = "custom-swap-locktime")] use common::log::warn; +use gstuff::slurp; #[cfg(feature = "custom-swap-locktime")] use lp_swap::PAYMENT_LOCKTIME; -#[cfg(feature = "custom-swap-locktime")] -use std::sync::atomic::Ordering; - -use gstuff::slurp; - +use mm2_core::mm_ctx::MmCtxBuilder; use serde::ser::Serialize; use serde_json::{self as json, Value as Json}; -use std::env; -use std::ffi::OsString; -use std::process::exit; -use std::ptr::null; -use std::str; - #[path = "lp_native_dex.rs"] mod lp_native_dex; -pub use self::lp_native_dex::lp_init; use coins::update_coins_config; use mm2_err_handle::prelude::*; +pub use self::lp_native_dex::lp_init; + #[cfg(not(target_arch = "wasm32"))] #[path = "database.rs"] pub mod database; diff --git a/mm2src/mm2_main/src/notification/telegram/telegram.rs b/mm2src/mm2_main/src/notification/telegram/telegram.rs index edfc5c15f7..562fc22462 100644 --- a/mm2src/mm2_main/src/notification/telegram/telegram.rs +++ b/mm2src/mm2_main/src/notification/telegram/telegram.rs @@ -1,8 +1,10 @@ -use crate::mm2::lp_message_service::{MessageResult, MessageServiceTraits}; +use std::collections::HashMap; + use async_trait::async_trait; use derive_more::Display; use mm2_net::transport::{post_json, SlurpError}; -use std::collections::HashMap; + +use crate::mm2::lp_message_service::{MessageResult, MessageServiceTraits}; pub const TELEGRAM_BOT_API_ENDPOINT: &str = "https://api.telegram.org/bot"; @@ -58,10 +60,12 @@ impl MessageServiceTraits for TgClient { #[cfg(all(test, not(target_arch = "wasm32")))] mod telegram_tests { + use std::env::var; + + use common::block_on; + use crate::mm2::lp_message_service::telegram::{ChatIdRegistry, TgClient}; use crate::mm2::lp_message_service::MessageServiceTraits; - use common::block_on; - use std::env::var; #[test] fn test_send_message() { diff --git a/mm2src/mm2_main/src/ordermatch_tests.rs b/mm2src/mm2_main/src/ordermatch_tests.rs index e9a1c1cb36..8a5f5de741 100644 --- a/mm2src/mm2_main/src/ordermatch_tests.rs +++ b/mm2src/mm2_main/src/ordermatch_tests.rs @@ -1,5 +1,7 @@ -use super::*; -use crate::mm2::lp_ordermatch::new_protocol::{MakerOrderUpdated, PubkeyKeepAlive}; +use std::collections::HashSet; +use std::iter::{self, FromIterator}; +use std::sync::Mutex; + use coins::{MmCoin, TestCoin}; use common::{block_on, executor::spawn}; use crypto::privkey::key_pair_from_seed; @@ -12,9 +14,9 @@ use mm2_net::p2p::P2PContext; use mm2_test_helpers::for_tests::mm_ctx_with_iguana; use mocktopus::mocking::*; use rand::{seq::SliceRandom, thread_rng, Rng}; -use std::collections::HashSet; -use std::iter::{self, FromIterator}; -use std::sync::Mutex; + +use super::*; +use crate::mm2::lp_ordermatch::new_protocol::{MakerOrderUpdated, PubkeyKeepAlive}; #[test] fn test_match_maker_order_and_taker_request() { diff --git a/mm2src/mm2_main/src/rpc.rs b/mm2src/mm2_main/src/rpc.rs index 001f8bea28..73356b2751 100644 --- a/mm2src/mm2_main/src/rpc.rs +++ b/mm2src/mm2_main/src/rpc.rs @@ -20,7 +20,9 @@ // Copyright © 2022 AtomicDEX. All rights reserved. // -use crate::mm2::rpc::rate_limiter::RateLimitError; +use std::borrow::Cow; +use std::net::SocketAddr; + use common::log::{error, info}; use common::{err_to_rpc_json_string, err_tp_rpc_json, HttpStatusCode, APPLICATION_JSON}; use derive_more::Display; @@ -35,8 +37,8 @@ use mm2_rpc::mm_protocol::{MmRpcBuilder, MmRpcResponse, MmRpcVersion}; use regex::Regex; use serde::Serialize; use serde_json::{self as json, Value as Json}; -use std::borrow::Cow; -use std::net::SocketAddr; + +use crate::mm2::rpc::rate_limiter::RateLimitError; cfg_native! { use hyper::{self, Body, Server}; @@ -308,6 +310,11 @@ async fn rpc_service(req: Request, ctx_h: u32, client: SocketAddr) -> Resp // handle various protocols within this function. #[cfg(not(target_arch = "wasm32"))] pub extern "C" fn spawn_rpc(ctx_h: u32) { + use std::convert::Infallible; + use std::env; + use std::fs::File; + use std::io::{self, BufReader}; + use common::now_sec; use common::wio::CORE; use hyper::server::conn::{AddrIncoming, AddrStream}; @@ -316,10 +323,6 @@ pub extern "C" fn spawn_rpc(ctx_h: u32) { use rcgen::{generate_simple_self_signed, RcgenError}; use rustls::{Certificate, PrivateKey}; use rustls_pemfile as pemfile; - use std::convert::Infallible; - use std::env; - use std::fs::File; - use std::io::{self, BufReader}; // Reads a certificate and a key from the specified files. fn read_certificate_and_key( @@ -487,10 +490,11 @@ pub extern "C" fn spawn_rpc(ctx_h: u32) { #[cfg(target_arch = "wasm32")] pub fn spawn_rpc(ctx_h: u32) { + use std::sync::Mutex; + use common::executor::SpawnFuture; use futures::StreamExt; use mm2_rpc::wasm_rpc; - use std::sync::Mutex; let ctx = MmArc::from_ffi_handle(ctx_h).expect("No context"); if ctx.wasm_rpc.is_some() { diff --git a/mm2src/mm2_main/src/rpc/dispatcher/dispatcher.rs b/mm2src/mm2_main/src/rpc/dispatcher/dispatcher.rs index 5645b9a68f..8e7f1ec5a9 100644 --- a/mm2src/mm2_main/src/rpc/dispatcher/dispatcher.rs +++ b/mm2src/mm2_main/src/rpc/dispatcher/dispatcher.rs @@ -1,14 +1,5 @@ -use super::{DispatcherError, DispatcherResult, PUBLIC_METHODS}; -use crate::mm2::lp_native_dex::init_hw::{cancel_init_trezor, init_trezor, init_trezor_status, init_trezor_user_action}; -#[cfg(target_arch = "wasm32")] -use crate::mm2::lp_native_dex::init_metamask::{cancel_connect_metamask, connect_metamask, connect_metamask_status}; -use crate::mm2::lp_ordermatch::{best_orders_rpc_v2, orderbook_rpc_v2, start_simple_market_maker_bot, - stop_simple_market_maker_bot}; -use crate::mm2::rpc::rate_limiter::{process_rate_limit, RateLimitContext}; -use crate::{mm2::lp_stats::{add_node_to_version_stat, remove_node_from_version_stat, start_version_stat_collection, - stop_version_stat_collection, update_version_stat_collection}, - mm2::lp_swap::{get_locked_amount_rpc, max_maker_vol, recreate_swap_data, trade_preimage_rpc}, - mm2::rpc::lp_commands::{get_public_key, get_public_key_hash, get_shared_db_id, trezor_connection_status}}; +use std::net::SocketAddr; + use coins::eth::EthCoin; use coins::my_tx_history_v2::my_tx_history_v2_rpc; use coins::nft; @@ -52,7 +43,18 @@ use mm2_rpc::mm_protocol::{MmRpcBuilder, MmRpcRequest, MmRpcVersion}; use nft::{get_nft_list, get_nft_metadata, get_nft_transfers, refresh_nft_metadata, update_nft, withdraw_nft}; use serde::de::DeserializeOwned; use serde_json::{self as json, Value as Json}; -use std::net::SocketAddr; + +use super::{DispatcherError, DispatcherResult, PUBLIC_METHODS}; +use crate::mm2::lp_native_dex::init_hw::{cancel_init_trezor, init_trezor, init_trezor_status, init_trezor_user_action}; +#[cfg(target_arch = "wasm32")] +use crate::mm2::lp_native_dex::init_metamask::{cancel_connect_metamask, connect_metamask, connect_metamask_status}; +use crate::mm2::lp_ordermatch::{best_orders_rpc_v2, orderbook_rpc_v2, start_simple_market_maker_bot, + stop_simple_market_maker_bot}; +use crate::mm2::rpc::rate_limiter::{process_rate_limit, RateLimitContext}; +use crate::{mm2::lp_stats::{add_node_to_version_stat, remove_node_from_version_stat, start_version_stat_collection, + stop_version_stat_collection, update_version_stat_collection}, + mm2::lp_swap::{get_locked_amount_rpc, max_maker_vol, recreate_swap_data, trade_preimage_rpc}, + mm2::rpc::lp_commands::{get_public_key, get_public_key_hash, get_shared_db_id, trezor_connection_status}}; cfg_native! { use coins::lightning::LightningCoin; diff --git a/mm2src/mm2_main/src/rpc/dispatcher/dispatcher_legacy.rs b/mm2src/mm2_main/src/rpc/dispatcher/dispatcher_legacy.rs index 795b76cee0..ccd48d0b31 100644 --- a/mm2src/mm2_main/src/rpc/dispatcher/dispatcher_legacy.rs +++ b/mm2src/mm2_main/src/rpc/dispatcher/dispatcher_legacy.rs @@ -1,13 +1,17 @@ -use super::PUBLIC_METHODS; +use std::net::SocketAddr; + +use coins::{convert_address, convert_utxo_address, get_enabled_coins, get_trade_fee, kmd_rewards_info, my_tx_history, + send_raw_transaction, set_required_confirmations, set_requires_notarization, show_priv_key, + validate_address}; use common::HyRes; use futures::compat::Future01CompatExt; use futures::{Future as Future03, FutureExt, TryFutureExt}; use http::Response; use mm2_core::mm_ctx::MmArc; use serde_json::{self as json, Value as Json}; -use std::net::SocketAddr; use super::lp_commands_legacy::*; +use super::PUBLIC_METHODS; use crate::mm2::lp_ordermatch::{best_orders_rpc, buy, cancel_all_orders_rpc, cancel_order_rpc, my_orders, order_status, orderbook_depth_rpc, orderbook_rpc, orders_history_by_filter, sell, set_price, update_maker_order_rpc}; @@ -15,9 +19,6 @@ use crate::mm2::lp_swap::{active_swaps_rpc, all_swaps_uuids_by_filter, ban_pubke import_swaps, list_banned_pubkeys_rpc, max_taker_vol, my_recent_swaps_rpc, my_swap_status, recover_funds_of_swap, stats_swap_status, unban_pubkeys_rpc}; use crate::mm2::rpc::rate_limiter::{process_rate_limit, RateLimitContext}; -use coins::{convert_address, convert_utxo_address, get_enabled_coins, get_trade_fee, kmd_rewards_info, my_tx_history, - send_raw_transaction, set_required_confirmations, set_requires_notarization, show_priv_key, - validate_address}; /// Result of `fn dispatcher`. pub enum DispatcherRes { diff --git a/mm2src/mm2_main/src/rpc/lp_commands/lp_commands_legacy.rs b/mm2src/mm2_main/src/rpc/lp_commands/lp_commands_legacy.rs index d5f3c41a50..0222ec7542 100644 --- a/mm2src/mm2_main/src/rpc/lp_commands/lp_commands_legacy.rs +++ b/mm2src/mm2_main/src/rpc/lp_commands/lp_commands_legacy.rs @@ -19,6 +19,10 @@ // marketmaker // +use std::borrow::Cow; +use std::collections::HashSet; +use std::iter::Extend; + use coins::{lp_coinfind, lp_coinfind_any, lp_coininit, CoinsContext, MmCoinEnum}; use common::executor::Timer; use common::log::error; @@ -31,9 +35,6 @@ use mm2_net::p2p::P2PContext; use mm2_number::construct_detailed; use mm2_rpc::data::legacy::{BalanceResponse, CoinInitResponse, Mm2RpcResult, MmVersionResponse, Status}; use serde_json::{self as json, Value as Json}; -use std::borrow::Cow; -use std::collections::HashSet; -use std::iter::Extend; use uuid::Uuid; use crate::mm2::lp_dispatcher::{dispatch_lp_event, StopCtxEvent}; diff --git a/mm2src/mm2_main/src/rpc/rate_limiter.rs b/mm2src/mm2_main/src/rpc/rate_limiter.rs index 9f07be2b46..b112d2087f 100644 --- a/mm2src/mm2_main/src/rpc/rate_limiter.rs +++ b/mm2src/mm2_main/src/rpc/rate_limiter.rs @@ -1,12 +1,14 @@ -use crate::mm2::rpc::DispatcherError; +use std::collections::HashMap; +use std::net::{IpAddr, SocketAddr}; +use std::sync::Arc; + use derive_more::Display; use futures::lock::Mutex as AsyncMutex; use mm2_core::mm_ctx::from_ctx; use mm2_core::mm_ctx::MmArc; use mm2_err_handle::prelude::*; -use std::collections::HashMap; -use std::net::{IpAddr, SocketAddr}; -use std::sync::Arc; + +use crate::mm2::rpc::DispatcherError; pub const LIMIT_FAILED_REQUEST: usize = 10; pub type RateInfosRegistry = HashMap; diff --git a/mm2src/mm2_main/src/wasm_tests.rs b/mm2src/mm2_main/src/wasm_tests.rs index f5025e85d3..f859c59eca 100644 --- a/mm2src/mm2_main/src/wasm_tests.rs +++ b/mm2src/mm2_main/src/wasm_tests.rs @@ -1,4 +1,3 @@ -use crate::mm2::lp_init; use common::executor::{spawn, Timer}; use common::log::wasm_log::register_wasm_log; use crypto::StandardHDCoinAddress; @@ -12,6 +11,8 @@ use mm2_test_helpers::get_passphrase; use serde_json::json; use wasm_bindgen_test::wasm_bindgen_test; +use crate::mm2::lp_init; + /// Starts the WASM version of MM. fn wasm_start(ctx: MmArc) { spawn(async move { diff --git a/mm2src/mm2_main/tests/docker_tests/docker_ordermatch_tests.rs b/mm2src/mm2_main/tests/docker_tests/docker_ordermatch_tests.rs index 2a08f18efc..f1f2355021 100644 --- a/mm2src/mm2_main/tests/docker_tests/docker_ordermatch_tests.rs +++ b/mm2src/mm2_main/tests/docker_tests/docker_ordermatch_tests.rs @@ -1,5 +1,6 @@ -use crate::generate_utxo_coin_with_random_privkey; -use crate::integration_tests_common::enable_native; +use std::thread; +use std::time::Duration; + use common::block_on; use mm2_number::BigDecimal; use mm2_rpc::data::legacy::OrderbookResponse; @@ -7,8 +8,9 @@ use mm2_test_helpers::for_tests::{mm_dump, MarketMakerIt}; use mm2_test_helpers::structs::{BestOrdersResponse, BestOrdersV2Response, BuyOrSellRpcResult, MyOrdersRpcResult, OrderbookDepthResponse, RpcV2Response, SetPriceResponse}; use serde_json::Value as Json; -use std::thread; -use std::time::Duration; + +use crate::generate_utxo_coin_with_random_privkey; +use crate::integration_tests_common::enable_native; fn check_asks_num(mm: &MarketMakerIt, base: &str, rel: &str, expected: usize) { log!("Get {}/{} orderbook", base, rel); diff --git a/mm2src/mm2_main/tests/docker_tests/docker_tests_common.rs b/mm2src/mm2_main/tests/docker_tests/docker_tests_common.rs index 3ddddf6801..ed35a97d66 100644 --- a/mm2src/mm2_main/tests/docker_tests/docker_tests_common.rs +++ b/mm2src/mm2_main/tests/docker_tests/docker_tests_common.rs @@ -1,15 +1,9 @@ -pub use common::{block_on, now_ms, now_sec, wait_until_ms, wait_until_sec}; -pub use mm2_number::MmNumber; -use mm2_rpc::data::legacy::BalanceResponse; -pub use mm2_test_helpers::for_tests::{check_my_swap_status, check_recent_swaps, check_stats_swap_status, - enable_native, enable_native_bch, eth_jst_testnet_conf, eth_sepolia_conf, - eth_testnet_conf, jst_sepolia_conf, mm_dump, MarketMakerIt, ETH_DEV_NODES, - ETH_DEV_SWAP_CONTRACT, ETH_DEV_TOKEN_CONTRACT, MAKER_ERROR_EVENTS, - MAKER_SUCCESS_EVENTS, TAKER_ERROR_EVENTS, TAKER_SUCCESS_EVENTS}; - -pub use secp256k1::{PublicKey, SecretKey}; pub use std::env; +use std::path::PathBuf; +use std::process::Command; +use std::sync::Mutex; pub use std::thread; +use std::time::Duration; use bitcrypto::{dhash160, ChecksumType}; use chain::TransactionOutput; @@ -25,6 +19,7 @@ use coins::utxo::utxo_standard::{utxo_standard_coin_with_priv_key, UtxoStandardC use coins::utxo::{coin_daemon_data_dir, sat_from_big_decimal, zcash_params_path, UtxoActivationParams, UtxoAddressFormat, UtxoCoinFields, UtxoCommonOps}; use coins::{CoinProtocol, ConfirmPaymentInput, MarketCoinOps, PrivKeyBuildPolicy, Transaction}; +pub use common::{block_on, now_ms, now_sec, wait_until_ms, wait_until_sec}; use crypto::privkey::key_pair_from_seed; use crypto::Secp256k1Secret; use ethereum_types::H160 as H160Eth; @@ -33,15 +28,19 @@ use http::StatusCode; use keys::{Address, AddressHashEnum, KeyPair, NetworkPrefix as CashAddrPrefix}; use mm2_core::mm_ctx::{MmArc, MmCtxBuilder}; use mm2_number::BigDecimal; +pub use mm2_number::MmNumber; +use mm2_rpc::data::legacy::BalanceResponse; +pub use mm2_test_helpers::for_tests::{check_my_swap_status, check_recent_swaps, check_stats_swap_status, + enable_native, enable_native_bch, eth_jst_testnet_conf, eth_sepolia_conf, + eth_testnet_conf, jst_sepolia_conf, mm_dump, MarketMakerIt, ETH_DEV_NODES, + ETH_DEV_SWAP_CONTRACT, ETH_DEV_TOKEN_CONTRACT, MAKER_ERROR_EVENTS, + MAKER_SUCCESS_EVENTS, TAKER_ERROR_EVENTS, TAKER_SUCCESS_EVENTS}; use mm2_test_helpers::structs::TransactionDetails; use primitives::hash::{H160, H256}; use script::Builder; use secp256k1::Secp256k1; +pub use secp256k1::{PublicKey, SecretKey}; use serde_json::{self as json, Value as Json}; -use std::path::PathBuf; -use std::process::Command; -use std::sync::Mutex; -use std::time::Duration; use testcontainers::clients::Cli; use testcontainers::images::generic::{GenericImage, WaitFor}; use testcontainers::{Container, Docker, Image}; diff --git a/mm2src/mm2_main/tests/docker_tests/docker_tests_inner.rs b/mm2src/mm2_main/tests/docker_tests/docker_tests_inner.rs index 1241dac2be..89213fdb17 100644 --- a/mm2src/mm2_main/tests/docker_tests/docker_tests_inner.rs +++ b/mm2src/mm2_main/tests/docker_tests/docker_tests_inner.rs @@ -1,7 +1,8 @@ -use crate::docker_tests::docker_tests_common::generate_utxo_coin_with_privkey; -use crate::integration_tests_common::*; -use crate::{fill_address, generate_utxo_coin_with_random_privkey, random_secp256k1_secret, rmd160_from_priv, - utxo_coin_from_privkey}; +use std::collections::HashMap; +use std::env; +use std::thread; +use std::time::Duration; + use bitcrypto::dhash160; use chain::OutPoint; use coins::utxo::rpc_clients::UnspentInfo; @@ -17,10 +18,11 @@ use mm2_test_helpers::for_tests::{check_my_swap_status_amounts, eth_testnet_conf MarketMakerIt, Mm2TestConf, ETH_DEV_NODES}; use mm2_test_helpers::{get_passphrase, structs::*}; use serde_json::Value as Json; -use std::collections::HashMap; -use std::env; -use std::thread; -use std::time::Duration; + +use crate::docker_tests::docker_tests_common::generate_utxo_coin_with_privkey; +use crate::integration_tests_common::*; +use crate::{fill_address, generate_utxo_coin_with_random_privkey, random_secp256k1_secret, rmd160_from_priv, + utxo_coin_from_privkey}; #[test] fn test_search_for_swap_tx_spend_native_was_refunded_taker() { diff --git a/mm2src/mm2_main/tests/docker_tests/qrc20_tests.rs b/mm2src/mm2_main/tests/docker_tests/qrc20_tests.rs index 03c484275d..b932b9cb58 100644 --- a/mm2src/mm2_main/tests/docker_tests/qrc20_tests.rs +++ b/mm2src/mm2_main/tests/docker_tests/qrc20_tests.rs @@ -1,5 +1,8 @@ -use crate::docker_tests::docker_tests_common::*; -use crate::integration_tests_common::enable_native; +use std::convert::TryFrom; +use std::process::Command; +use std::str::FromStr; +use std::time::Duration; + use bitcrypto::dhash160; use coins::qrc20::rpc_clients::for_tests::Qrc20NativeWalletOps; use coins::utxo::qtum::{qtum_coin_with_priv_key, QtumCoin}; @@ -22,14 +25,13 @@ use mm2_rpc::data::legacy::{CoinInitResponse, OrderbookResponse}; use mm2_test_helpers::structs::{trade_preimage_error, RpcErrorResponse, RpcSuccessResponse, TransactionDetails}; use rand6::Rng; use serde_json::{self as json, Value as Json}; -use std::convert::TryFrom; -use std::process::Command; -use std::str::FromStr; -use std::time::Duration; use testcontainers::clients::Cli; use testcontainers::images::generic::{GenericImage, WaitFor}; use testcontainers::{Docker, Image}; +use crate::docker_tests::docker_tests_common::*; +use crate::integration_tests_common::enable_native; + pub const QTUM_REGTEST_DOCKER_IMAGE: &str = "docker.io/sergeyboyko/qtumregtest"; const QRC20_TOKEN_BYTES: &str = "6080604052600860ff16600a0a633b9aca000260005534801561002157600080fd5b50600054600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610c69806100776000396000f3006080604052600436106100a4576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100a9578063095ea7b31461013957806318160ddd1461019e57806323b872dd146101c9578063313ce5671461024e5780635a3b7e421461027f57806370a082311461030f57806395d89b4114610366578063a9059cbb146103f6578063dd62ed3e1461045b575b600080fd5b3480156100b557600080fd5b506100be6104d2565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100fe5780820151818401526020810190506100e3565b50505050905090810190601f16801561012b5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561014557600080fd5b50610184600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061050b565b604051808215151515815260200191505060405180910390f35b3480156101aa57600080fd5b506101b36106bb565b6040518082815260200191505060405180910390f35b3480156101d557600080fd5b50610234600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506106c1565b604051808215151515815260200191505060405180910390f35b34801561025a57600080fd5b506102636109a1565b604051808260ff1660ff16815260200191505060405180910390f35b34801561028b57600080fd5b506102946109a6565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156102d45780820151818401526020810190506102b9565b50505050905090810190601f1680156103015780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561031b57600080fd5b50610350600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506109df565b6040518082815260200191505060405180910390f35b34801561037257600080fd5b5061037b6109f7565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156103bb5780820151818401526020810190506103a0565b50505050905090810190601f1680156103e85780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561040257600080fd5b50610441600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610a30565b604051808215151515815260200191505060405180910390f35b34801561046757600080fd5b506104bc600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610be1565b6040518082815260200191505060405180910390f35b6040805190810160405280600881526020017f515243205445535400000000000000000000000000000000000000000000000081525081565b60008260008173ffffffffffffffffffffffffffffffffffffffff161415151561053457600080fd5b60008314806105bf57506000600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054145b15156105ca57600080fd5b82600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508373ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925856040518082815260200191505060405180910390a3600191505092915050565b60005481565b60008360008173ffffffffffffffffffffffffffffffffffffffff16141515156106ea57600080fd5b8360008173ffffffffffffffffffffffffffffffffffffffff161415151561071157600080fd5b610797600260008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205485610c06565b600260008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610860600160008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205485610c06565b600160008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506108ec600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205485610c1f565b600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508473ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef866040518082815260200191505060405180910390a36001925050509392505050565b600881565b6040805190810160405280600981526020017f546f6b656e20302e31000000000000000000000000000000000000000000000081525081565b60016020528060005260406000206000915090505481565b6040805190810160405280600381526020017f515443000000000000000000000000000000000000000000000000000000000081525081565b60008260008173ffffffffffffffffffffffffffffffffffffffff1614151515610a5957600080fd5b610aa2600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205484610c06565b600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610b2e600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205484610c1f565b600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508373ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a3600191505092915050565b6002602052816000526040600020602052806000526040600020600091509150505481565b6000818310151515610c1457fe5b818303905092915050565b6000808284019050838110151515610c3357fe5b80915050929150505600a165627a7a723058207f2e5248b61b80365ea08a0f6d11ac0b47374c4dfd538de76bc2f19591bbbba40029"; diff --git a/mm2src/mm2_main/tests/docker_tests/slp_tests.rs b/mm2src/mm2_main/tests/docker_tests/slp_tests.rs index e5ce537b7b..576926bfa7 100644 --- a/mm2src/mm2_main/tests/docker_tests/slp_tests.rs +++ b/mm2src/mm2_main/tests/docker_tests/slp_tests.rs @@ -1,5 +1,6 @@ -use crate::docker_tests::docker_tests_common::*; -use crate::integration_tests_common::enable_native; +use std::collections::HashSet; +use std::time::Duration; + use http::StatusCode; use mm2_number::BigDecimal; use mm2_rpc::data::legacy::CoinInitResponse; @@ -7,8 +8,9 @@ use mm2_test_helpers::for_tests::{assert_coin_not_found_on_balance, disable_coin my_balance, UtxoRpcMode}; use mm2_test_helpers::structs::{EnableBchWithTokensResponse, EnableSlpResponse, RpcV2Response}; use serde_json::{self as json, json, Value as Json}; -use std::collections::HashSet; -use std::time::Duration; + +use crate::docker_tests::docker_tests_common::*; +use crate::integration_tests_common::enable_native; async fn enable_bch_with_tokens_without_balance( mm: &MarketMakerIt, diff --git a/mm2src/mm2_main/tests/docker_tests/solana_tests.rs b/mm2src/mm2_main/tests/docker_tests/solana_tests.rs index d1faa5d2a7..6bb3261171 100644 --- a/mm2src/mm2_main/tests/docker_tests/solana_tests.rs +++ b/mm2src/mm2_main/tests/docker_tests/solana_tests.rs @@ -1,10 +1,11 @@ -use crate::docker_tests::docker_tests_common::*; use mm2_number::bigdecimal::Zero; use mm2_test_helpers::for_tests::{disable_coin, enable_solana_with_tokens, enable_spl, sign_message, verify_message}; use mm2_test_helpers::structs::{EnableSolanaWithTokensResponse, EnableSplResponse, RpcV2Response, SignatureResponse, VerificationResponse}; use serde_json as json; +use crate::docker_tests::docker_tests_common::*; + #[test] fn test_solana_and_spl_balance_enable_spl_v2() { let mm = _solana_supplied_node(); diff --git a/mm2src/mm2_main/tests/docker_tests/swap_proto_v2_tests.rs b/mm2src/mm2_main/tests/docker_tests/swap_proto_v2_tests.rs index 331b5b918b..33e29a4665 100644 --- a/mm2src/mm2_main/tests/docker_tests/swap_proto_v2_tests.rs +++ b/mm2src/mm2_main/tests/docker_tests/swap_proto_v2_tests.rs @@ -1,4 +1,3 @@ -use crate::{generate_utxo_coin_with_random_privkey, MYCOIN, MYCOIN1}; use bitcrypto::dhash160; use coins::utxo::UtxoCommonOps; use coins::{GenTakerPaymentSpendArgs, RefundPaymentArgs, SendCombinedTakerPaymentArgs, SwapOpsV2, Transaction, @@ -8,6 +7,8 @@ use mm2_test_helpers::for_tests::{enable_native, mm_dump, mycoin1_conf, mycoin_c Mm2TestConf}; use script::{Builder, Opcode}; +use crate::{generate_utxo_coin_with_random_privkey, MYCOIN, MYCOIN1}; + #[test] fn send_and_refund_taker_payment() { let (_mm_arc, coin, _privkey) = generate_utxo_coin_with_random_privkey(MYCOIN, 1000.into()); diff --git a/mm2src/mm2_main/tests/docker_tests/swap_watcher_tests.rs b/mm2src/mm2_main/tests/docker_tests/swap_watcher_tests.rs index 55ef6dc435..002c4f25ba 100644 --- a/mm2src/mm2_main/tests/docker_tests/swap_watcher_tests.rs +++ b/mm2src/mm2_main/tests/docker_tests/swap_watcher_tests.rs @@ -1,6 +1,7 @@ -use crate::docker_tests::docker_tests_common::{eth_distributor, generate_jst_with_seed}; -use crate::integration_tests_common::*; -use crate::{generate_utxo_coin_with_privkey, generate_utxo_coin_with_random_privkey, random_secp256k1_secret}; +use std::str::FromStr; +use std::thread; +use std::time::Duration; + use coins::coin_errors::ValidatePaymentError; use coins::utxo::{dhash160, UtxoCommonOps}; use coins::{ConfirmPaymentInput, FoundSwapTxSpend, MarketCoinOps, MmCoin, MmCoinEnum, RefundPaymentArgs, RewardTarget, @@ -23,11 +24,12 @@ use mm2_test_helpers::get_passphrase; use mm2_test_helpers::structs::WatcherConf; use num_traits::{One, Zero}; use primitives::hash::H256; -use std::str::FromStr; -use std::thread; -use std::time::Duration; use uuid::Uuid; +use crate::docker_tests::docker_tests_common::{eth_distributor, generate_jst_with_seed}; +use crate::integration_tests_common::*; +use crate::{generate_utxo_coin_with_privkey, generate_utxo_coin_with_random_privkey, random_secp256k1_secret}; + #[derive(Debug, Clone)] struct BalanceResult { alice_acoin_balance_before: BigDecimal, diff --git a/mm2src/mm2_main/tests/docker_tests/swaps_confs_settings_sync_tests.rs b/mm2src/mm2_main/tests/docker_tests/swaps_confs_settings_sync_tests.rs index 13c35cb0be..5c735f5c6d 100644 --- a/mm2src/mm2_main/tests/docker_tests/swaps_confs_settings_sync_tests.rs +++ b/mm2src/mm2_main/tests/docker_tests/swaps_confs_settings_sync_tests.rs @@ -1,12 +1,14 @@ -use crate::generate_utxo_coin_with_random_privkey; -use crate::integration_tests_common::enable_native; +use std::thread; +use std::time::Duration; + use common::block_on; use mm2_main::mm2::lp_swap::get_payment_locktime; use mm2_rpc::data::legacy::OrderConfirmationsSettings; use mm2_test_helpers::for_tests::{mm_dump, MarketMakerIt}; use serde_json::Value as Json; -use std::thread; -use std::time::Duration; + +use crate::generate_utxo_coin_with_random_privkey; +use crate::integration_tests_common::enable_native; struct SwapConfirmationsSettings { maker_coin_confs: u64, diff --git a/mm2src/mm2_main/tests/docker_tests/swaps_file_lock_tests.rs b/mm2src/mm2_main/tests/docker_tests/swaps_file_lock_tests.rs index 8ca965e784..c8c5c37402 100644 --- a/mm2src/mm2_main/tests/docker_tests/swaps_file_lock_tests.rs +++ b/mm2src/mm2_main/tests/docker_tests/swaps_file_lock_tests.rs @@ -1,5 +1,6 @@ -use crate::generate_utxo_coin_with_random_privkey; -use crate::integration_tests_common::enable_native; +use std::thread; +use std::time::Duration; + use bitcrypto::ChecksumType; use common::block_on; use crypto::Secp256k1Secret; @@ -7,8 +8,9 @@ use keys::{KeyPair, Private}; use mm2_io::file_lock::FileLock; use mm2_test_helpers::for_tests::{mm_dump, new_mm2_temp_folder_path, MarketMakerIt}; use serde_json::Value as Json; -use std::thread; -use std::time::Duration; + +use crate::generate_utxo_coin_with_random_privkey; +use crate::integration_tests_common::enable_native; const UNFINISHED_MAKER_SWAP: &str = r#"{"type":"Maker","uuid":"5acb0e63-8b26-469e-81df-7dd9e4a9ad15","events":[{"timestamp":1588244036250,"event":{"type":"Started","data":{"taker_coin":"MYCOIN1","maker_coin":"MYCOIN","taker":"859a80b83941e4e8ff2f511080e3ea5021db4ba95caec30eb37864e71ae73521","secret":"dedf3c8dcfff9ee2787b4bf211f960fd044fdab7fa8e922ef613a0115848a498","secret_hash":"9304bce3196f344b2a22dc99db406e95ab6f3107","my_persistent_pub":"02987d5f82205a55d789616f470ae9df48537f050ee050d501aa316651642a0a4d","lock_duration":7800,"maker_amount":"999.99999","taker_amount":"999.99999","maker_payment_confirmations":1,"maker_payment_requires_nota":false,"taker_payment_confirmations":1,"taker_payment_requires_nota":false,"maker_payment_lock":1588259636,"uuid":"5acb0e63-8b26-469e-81df-7dd9e4a9ad15","started_at":1588244036,"maker_coin_start_block":12,"taker_coin_start_block":11}}},{"timestamp":1588244038035,"event":{"type":"Negotiated","data":{"taker_payment_locktime":1588251836,"taker_pubkey":"02859a80b83941e4e8ff2f511080e3ea5021db4ba95caec30eb37864e71ae73521"}}}],"maker_amount":"999.99999","maker_coin":"MYCOIN","taker_amount":"999.99999","taker_coin":"MYCOIN1","gui":"nogui","mm_version":"UNKNOWN","success_events":["Started","Negotiated","TakerFeeValidated","MakerPaymentSent","TakerPaymentReceived","TakerPaymentWaitConfirmStarted","TakerPaymentValidatedAndConfirmed","TakerPaymentSpent","Finished"],"error_events":["StartFailed","NegotiateFailed","TakerFeeValidateFailed","MakerPaymentTransactionFailed","MakerPaymentDataSendFailed","MakerPaymentWaitConfirmFailed","TakerPaymentValidateFailed","TakerPaymentWaitConfirmFailed","TakerPaymentSpendFailed","MakerPaymentWaitRefundStarted","MakerPaymentRefunded","MakerPaymentRefundFailed"]}"#; const FINISHED_MAKER_SWAP: &str = r#"{"type":"Maker","uuid":"5acb0e63-8b26-469e-81df-7dd9e4a9ad15","events":[{"timestamp":1588244036250,"event":{"type":"Started","data":{"taker_coin":"MYCOIN1","maker_coin":"MYCOIN","taker":"859a80b83941e4e8ff2f511080e3ea5021db4ba95caec30eb37864e71ae73521","secret":"dedf3c8dcfff9ee2787b4bf211f960fd044fdab7fa8e922ef613a0115848a498","secret_hash":"9304bce3196f344b2a22dc99db406e95ab6f3107","my_persistent_pub":"02987d5f82205a55d789616f470ae9df48537f050ee050d501aa316651642a0a4d","lock_duration":7800,"maker_amount":"999.99999","taker_amount":"999.99999","maker_payment_confirmations":1,"maker_payment_requires_nota":false,"taker_payment_confirmations":1,"taker_payment_requires_nota":false,"maker_payment_lock":1588259636,"uuid":"5acb0e63-8b26-469e-81df-7dd9e4a9ad15","started_at":1588244036,"maker_coin_start_block":12,"taker_coin_start_block":11}}},{"timestamp":1588244038035,"event":{"type":"Negotiated","data":{"taker_payment_locktime":1588251836,"taker_pubkey":"02859a80b83941e4e8ff2f511080e3ea5021db4ba95caec30eb37864e71ae73521"}}},{"timestamp":1588244038463,"event":{"type":"TakerFeeValidated","data":{"tx_hex":"0400008085202f8901bdde9bca02870787441f6068e4c2a869a3aac3d1d0925f6a6e27874343544d0a010000006a47304402206694a794693b55fbe8205cb1cbb992d92fa2a9a851763ad1bf1628c16deaf73e02203cfff465504bdd6c51e8fbd45dd2e1187142fdc29e82f36f577616d9d6097d7a012102859a80b83941e4e8ff2f511080e3ea5021db4ba95caec30eb37864e71ae73521ffffffff02dfceab07000000001976a914ca1e04745e8ca0c60d8c5881531d51bec470743f88ac39fd41892e0000001976a914d24e799df360da3ca3158d63b89ffaff27722c1588ac46aeaa5e000000000000000000000000000000","tx_hash":"7118d7484d1cbfdd6126673a848a228856f8748d946f6a9a440c90f0d62e27c6","from":["RUTBzLtJNTn89Wkb6oZocbesKrjBDTRMrC"],"to":["RThtXup6Zo7LZAi8kRWgjAyi1s4u6U9Cpf","RUTBzLtJNTn89Wkb6oZocbesKrjBDTRMrC"],"total_amount":"2000","spent_by_me":"0","received_by_me":"0","my_balance_change":"0","block_height":13,"timestamp":1588244038,"fee_details":{"amount":"0.00001"},"coin":"MYCOIN1","internal_id":"7118d7484d1cbfdd6126673a848a228856f8748d946f6a9a440c90f0d62e27c6"}}},{"timestamp":1588244038505,"event":{"type":"MakerPaymentSent","data":{"tx_hex":"0400008085202f890163cc0aceb3b432f84c1407991a0389b74b7842f030aa261203aa0b4b9a9a15fd010000006b483045022100f3239794b7b0e1c75aae084a65535270f154231ce86a4739976ff69eeff1ebd402206c0aeb28b7b4b2e77e98b3c3efd9a20d85c2cd0627acc3f45d577c0e88c34fb4012102987d5f82205a55d789616f470ae9df48537f050ee050d501aa316651642a0a4dffffffff0118e476481700000017a914dc4ed4686174503b85374bfb0aefe07a9fb37bcf8746aeaa5e000000000000000000000000000000","tx_hash":"9a4c0b3f85ed0bb24dc9575ce7c2fd6bc50ad9d37c91c478946f9c33d15abfdf","from":["RAzSdYQhjCFdyhjrBz1AZQDVg3Hu8DrzYc"],"to":["bYp9ncp3V7FYsymipriVbdd3QL72hK9hio"],"total_amount":"1000","spent_by_me":"1000","received_by_me":"0","my_balance_change":"-1000","block_height":0,"timestamp":0,"fee_details":{"amount":"0.00001"},"coin":"MYCOIN","internal_id":"9a4c0b3f85ed0bb24dc9575ce7c2fd6bc50ad9d37c91c478946f9c33d15abfdf"}}},{"timestamp":1588244053938,"event":{"type":"TakerPaymentReceived","data":{"tx_hex":"0400008085202f8901c6272ed6f0900c449a6a6f948d74f85688228a843a672661ddbf1c4d48d71871010000006b483045022100c37627385c66b7bdf466b4dd4e7095b7551e6f5ea35f9bcc6344eb629f2edcb202203280eaba64b4d72010500166fab62cf34a687a516b2fe83d4eceaf8572cb37a7012102859a80b83941e4e8ff2f511080e3ea5021db4ba95caec30eb37864e71ae73521ffffffff0218e476481700000017a91431ff75ed72cd135a7ce50d121e71efc37066b9f9873915cb40170000001976a914d24e799df360da3ca3158d63b89ffaff27722c1588ac55aeaa5e000000000000000000000000000000","tx_hash":"b4718ce94aa43f9073ab0b70c18ab4ea4b587338fb7110f20ff7d1bb452df08f","from":["RUTBzLtJNTn89Wkb6oZocbesKrjBDTRMrC"],"to":["RUTBzLtJNTn89Wkb6oZocbesKrjBDTRMrC","bHHdqM8XWDHee2oyzydwUJKEE2BjofEtZH"],"total_amount":"1998.71298873","spent_by_me":"0","received_by_me":"0","my_balance_change":"0","block_height":0,"timestamp":0,"fee_details":{"amount":"0.00001"},"coin":"MYCOIN1","internal_id":"b4718ce94aa43f9073ab0b70c18ab4ea4b587338fb7110f20ff7d1bb452df08f"}}},{"timestamp":1588244053939,"event":{"type":"TakerPaymentWaitConfirmStarted"}},{"timestamp":1588244068951,"event":{"type":"TakerPaymentValidatedAndConfirmed"}},{"timestamp":1588244068959,"event":{"type":"TakerPaymentSpent","data":{"tx_hex":"0400008085202f89018ff02d45bbd1f70ff21071fb3873584beab48ac1700bab73903fa44ae98c71b400000000d747304402204f0d641a3916e54d6788744c3229110a431eff18634c66fbd1741f9ca7dba99d02202315ee1d9317cc4d5d75d01f066f2c8a59876f790106d310144cdc03c25f985e0120dedf3c8dcfff9ee2787b4bf211f960fd044fdab7fa8e922ef613a0115848a498004c6b6304bcccaa5eb1752102859a80b83941e4e8ff2f511080e3ea5021db4ba95caec30eb37864e71ae73521ac6782012088a9149304bce3196f344b2a22dc99db406e95ab6f3107882102987d5f82205a55d789616f470ae9df48537f050ee050d501aa316651642a0a4dac68ffffffff0130e07648170000001976a91412c553e8469363f2d30268c475af1e9186cc90af88ac54a0aa5e000000000000000000000000000000","tx_hash":"e7aed7a77e47b44dc9d12166589bbade70faea10b64888f73ed4be04bcc9f9a9","from":["bHHdqM8XWDHee2oyzydwUJKEE2BjofEtZH"],"to":["RAzSdYQhjCFdyhjrBz1AZQDVg3Hu8DrzYc"],"total_amount":"999.99999","spent_by_me":"0","received_by_me":"999.99998","my_balance_change":"999.99998","block_height":0,"timestamp":0,"fee_details":{"amount":"0.00001"},"coin":"MYCOIN1","internal_id":"e7aed7a77e47b44dc9d12166589bbade70faea10b64888f73ed4be04bcc9f9a9"}}},{"timestamp":1588244068960,"event":{"type":"Finished"}}],"maker_amount":"999.99999","maker_coin":"MYCOIN","taker_amount":"999.99999","taker_coin":"MYCOIN1","gui":"nogui","mm_version":"UNKNOWN","success_events":["Started","Negotiated","TakerFeeValidated","MakerPaymentSent","TakerPaymentReceived","TakerPaymentWaitConfirmStarted","TakerPaymentValidatedAndConfirmed","TakerPaymentSpent","Finished"],"error_events":["StartFailed","NegotiateFailed","TakerFeeValidateFailed","MakerPaymentTransactionFailed","MakerPaymentDataSendFailed","MakerPaymentWaitConfirmFailed","TakerPaymentValidateFailed","TakerPaymentWaitConfirmFailed","TakerPaymentSpendFailed","MakerPaymentWaitRefundStarted","MakerPaymentRefunded","MakerPaymentRefundFailed"]}"#; diff --git a/mm2src/mm2_main/tests/docker_tests_main.rs b/mm2src/mm2_main/tests/docker_tests_main.rs index 70b31bf0d3..5c539b8550 100644 --- a/mm2src/mm2_main/tests/docker_tests_main.rs +++ b/mm2src/mm2_main/tests/docker_tests_main.rs @@ -24,6 +24,7 @@ extern crate serde_json; use std::io::{BufRead, BufReader}; use std::process::Command; + use test::{test_main, StaticBenchFn, StaticTestFn, TestDescAndFn}; use testcontainers::clients::Cli; mod docker_tests; diff --git a/mm2src/mm2_main/tests/integration_tests_common/mod.rs b/mm2src/mm2_main/tests/integration_tests_common/mod.rs index 12075d2974..2233fbe281 100644 --- a/mm2src/mm2_main/tests/integration_tests_common/mod.rs +++ b/mm2src/mm2_main/tests/integration_tests_common/mod.rs @@ -1,3 +1,7 @@ +use std::collections::HashMap; +use std::env::var; +use std::str::FromStr; + use common::executor::Timer; use common::log::LogLevel; use common::{block_on, log, now_ms, wait_until_ms}; @@ -11,9 +15,6 @@ use mm2_test_helpers::for_tests::{enable_native as enable_native_impl, init_utxo use mm2_test_helpers::structs::{InitTaskResult, InitUtxoStatus, InitZcoinStatus, RpcV2Response, UtxoStandardActivationResult, ZCoinActivationResult}; use serde_json::{self as json, Value as Json}; -use std::collections::HashMap; -use std::env::var; -use std::str::FromStr; /// This is not a separate test but a helper used by `MarketMakerIt` to run the MarketMaker from the test binary. #[test] diff --git a/mm2src/mm2_main/tests/mm2_tests/bch_and_slp_tests.rs b/mm2src/mm2_main/tests/mm2_tests/bch_and_slp_tests.rs index f4790b4b35..9eb8f847cb 100644 --- a/mm2src/mm2_main/tests/mm2_tests/bch_and_slp_tests.rs +++ b/mm2src/mm2_main/tests/mm2_tests/bch_and_slp_tests.rs @@ -1,3 +1,7 @@ +use std::env; +use std::thread; +use std::time::Duration; + use common::custom_futures::repeatable::{Ready, Retry}; use common::{block_on, log, repeatable}; use crypto::StandardHDCoinAddress; @@ -9,9 +13,6 @@ use mm2_test_helpers::for_tests::{disable_coin, enable_bch_with_tokens, enable_s use mm2_test_helpers::structs::{EnableBchWithTokensResponse, RpcV2Response, SignatureResponse, StandardHistoryV2Res, UtxoFeeDetails, VerificationResponse}; use serde_json::{self as json, json, Value as Json}; -use std::env; -use std::thread; -use std::time::Duration; #[cfg(not(target_arch = "wasm32"))] const T_BCH_ELECTRUMS: &[&str] = &[ diff --git a/mm2src/mm2_main/tests/mm2_tests/best_orders_tests.rs b/mm2src/mm2_main/tests/mm2_tests/best_orders_tests.rs index 9be563b420..2a4d2b9708 100644 --- a/mm2src/mm2_main/tests/mm2_tests/best_orders_tests.rs +++ b/mm2src/mm2_main/tests/mm2_tests/best_orders_tests.rs @@ -1,4 +1,8 @@ -use crate::integration_tests_common::*; +use std::collections::BTreeSet; +use std::env::{self}; +use std::thread; +use std::time::Duration; + use common::{block_on, log}; use http::StatusCode; use mm2_number::BigDecimal; @@ -9,12 +13,10 @@ use mm2_test_helpers::for_tests::{best_orders_v2, best_orders_v2_by_number, eth_ Mm2TestConf, RICK_ELECTRUM_ADDRS, TBTC_ELECTRUMS}; use mm2_test_helpers::structs::{BestOrdersResponse, SetPriceResponse}; use serde_json::{self as json, json}; -use std::collections::BTreeSet; -use std::env::{self}; -use std::thread; -use std::time::Duration; use uuid::Uuid; +use crate::integration_tests_common::*; + #[test] #[cfg(not(target_arch = "wasm32"))] fn test_best_orders() { @@ -1115,10 +1117,10 @@ fn best_orders_must_return_duplicate_for_orderbook_tickers() { #[test] #[cfg(feature = "zhtlc-native-tests")] fn zhtlc_best_orders() { - use super::enable_z_coin; + use mm2_test_helpers::electrums::rick_electrums; use mm2_test_helpers::for_tests::zombie_conf; - use mm2_test_helpers::electrums::rick_electrums; + use super::enable_z_coin; let bob_passphrase = get_passphrase(&".env.seed", "BOB_PASSPHRASE").unwrap(); let alice_passphrase = get_passphrase(&".env.client", "ALICE_PASSPHRASE").unwrap(); diff --git a/mm2src/mm2_main/tests/mm2_tests/eth_tests.rs b/mm2src/mm2_main/tests/mm2_tests/eth_tests.rs index 9d62aaf97f..ebfe119295 100644 --- a/mm2src/mm2_main/tests/mm2_tests/eth_tests.rs +++ b/mm2src/mm2_main/tests/mm2_tests/eth_tests.rs @@ -1,3 +1,7 @@ +use std::collections::HashSet; +use std::iter::FromIterator; +use std::str::FromStr; + use common::block_on; use http::StatusCode; use mm2_test_helpers::for_tests::{disable_coin, disable_coin_err, eth_jst_testnet_conf, eth_testnet_conf, @@ -5,9 +9,6 @@ use mm2_test_helpers::for_tests::{disable_coin, disable_coin_err, eth_jst_testne ETH_DEV_NODES, ETH_DEV_SWAP_CONTRACT}; use mm2_test_helpers::structs::{EnableEthWithTokensResponse, RpcV2Response}; use serde_json::{self as json, json, Value as Json}; -use std::collections::HashSet; -use std::iter::FromIterator; -use std::str::FromStr; #[cfg(not(target_arch = "wasm32"))] async fn enable_eth_with_tokens(mm: &MarketMakerIt, platform_coin: &str, tokens: &[&str], nodes: &[&str]) -> Json { diff --git a/mm2src/mm2_main/tests/mm2_tests/lightning_tests.rs b/mm2src/mm2_main/tests/mm2_tests/lightning_tests.rs index 5e69a89771..2d627c8600 100644 --- a/mm2src/mm2_main/tests/mm2_tests/lightning_tests.rs +++ b/mm2src/mm2_main/tests/mm2_tests/lightning_tests.rs @@ -1,4 +1,6 @@ -use crate::integration_tests_common::{enable_coins_rick_morty_electrum, enable_electrum}; +use std::env; +use std::str::FromStr; + use coins::lightning::ln_events::{CHANNEL_READY_LOG, PAYMENT_CLAIMABLE_LOG, SUCCESSFUL_CLAIM_LOG, SUCCESSFUL_SEND_LOG}; use common::executor::Timer; use common::{block_on, log, wait_until_ms}; @@ -10,8 +12,8 @@ use mm2_test_helpers::for_tests::{disable_coin, init_lightning, init_lightning_s use mm2_test_helpers::structs::{InitLightningStatus, InitTaskResult, LightningActivationResult, RpcV2Response, SignatureResponse, VerificationResponse}; use serde_json::{self as json, json, Value as Json}; -use std::env; -use std::str::FromStr; + +use crate::integration_tests_common::{enable_coins_rick_morty_electrum, enable_electrum}; const BTC_AVG_BLOCKTIME: u64 = 600; const T_BTC_ELECTRUMS: &[&str] = &[ diff --git a/mm2src/mm2_main/tests/mm2_tests/mm2_tests_inner.rs b/mm2src/mm2_main/tests/mm2_tests/mm2_tests_inner.rs index 10bdeb5a29..8163bccc61 100644 --- a/mm2src/mm2_main/tests/mm2_tests/mm2_tests_inner.rs +++ b/mm2src/mm2_main/tests/mm2_tests/mm2_tests_inner.rs @@ -1,9 +1,13 @@ -#[cfg(all(feature = "zhtlc-native-tests", not(target_arch = "wasm32")))] -use super::enable_z_coin; -use crate::integration_tests_common::*; +use std::collections::HashMap; +use std::env::{self, var}; +use std::str::FromStr; +use std::thread; +use std::time::Duration; + use common::executor::Timer; use common::{cfg_native, cfg_wasm32, get_utc_timestamp, log, new_uuid}; use crypto::privkey::key_pair_from_seed; +use crypto::StandardHDCoinAddress; use http::{HeaderMap, StatusCode}; use mm2_main::mm2::lp_ordermatch::MIN_ORDER_KEEP_ALIVE_INTERVAL; use mm2_metrics::{MetricType, MetricsJson}; @@ -23,18 +27,15 @@ use mm2_test_helpers::for_tests::{btc_segwit_conf, btc_with_spv_conf, btc_with_s ETH_DEV_NODES, ETH_DEV_SWAP_CONTRACT, ETH_DEV_TOKEN_CONTRACT, ETH_MAINNET_NODE, ETH_MAINNET_SWAP_CONTRACT, MORTY, QRC20_ELECTRUMS, RICK, RICK_ELECTRUM_ADDRS, TBTC_ELECTRUMS}; - -use crypto::StandardHDCoinAddress; use mm2_test_helpers::get_passphrase; use mm2_test_helpers::structs::*; use serde_json::{self as json, json, Value as Json}; -use std::collections::HashMap; -use std::env::{self, var}; -use std::str::FromStr; -use std::thread; -use std::time::Duration; use uuid::Uuid; +#[cfg(all(feature = "zhtlc-native-tests", not(target_arch = "wasm32")))] +use super::enable_z_coin; +use crate::integration_tests_common::*; + cfg_native! { use common::block_on; use mm2_test_helpers::for_tests::{get_passphrase, new_mm2_temp_folder_path}; diff --git a/mm2src/mm2_main/tests/mm2_tests/orderbook_sync_tests.rs b/mm2src/mm2_main/tests/mm2_tests/orderbook_sync_tests.rs index 1a5c0c8d4c..e27cd8b73f 100644 --- a/mm2src/mm2_main/tests/mm2_tests/orderbook_sync_tests.rs +++ b/mm2src/mm2_main/tests/mm2_tests/orderbook_sync_tests.rs @@ -1,5 +1,8 @@ -use crate::integration_tests_common::{enable_coins_eth_electrum, enable_coins_rick_morty_electrum, enable_electrum, - enable_electrum_json, enable_z_coin_light}; +use std::env; +use std::str::FromStr; +use std::thread; +use std::time::Duration; + use common::{block_on, log}; use http::StatusCode; use mm2_main::mm2::lp_ordermatch::MIN_ORDER_KEEP_ALIVE_INTERVAL; @@ -12,10 +15,9 @@ use mm2_test_helpers::for_tests::{eth_jst_testnet_conf, eth_testnet_conf, get_pa use mm2_test_helpers::get_passphrase; use mm2_test_helpers::structs::{GetPublicKeyResult, OrderbookV2Response, RpcV2Response, SetPriceResponse}; use serde_json::{self as json, json, Value as Json}; -use std::env; -use std::str::FromStr; -use std::thread; -use std::time::Duration; + +use crate::integration_tests_common::{enable_coins_eth_electrum, enable_coins_rick_morty_electrum, enable_electrum, + enable_electrum_json, enable_z_coin_light}; /// https://github.com/artemii235/SuperNET/issues/241 #[test] diff --git a/mm2src/mm2_main/tests/mm2_tests/tendermint_ibc_asset_tests.rs b/mm2src/mm2_main/tests/mm2_tests/tendermint_ibc_asset_tests.rs index 6bebbec41a..64d68468c5 100644 --- a/mm2src/mm2_main/tests/mm2_tests/tendermint_ibc_asset_tests.rs +++ b/mm2src/mm2_main/tests/mm2_tests/tendermint_ibc_asset_tests.rs @@ -1,3 +1,6 @@ +use std::collections::HashSet; +use std::iter::FromIterator; + use common::block_on; use mm2_number::BigDecimal; use mm2_rpc::data::legacy::OrderbookResponse; @@ -5,10 +8,7 @@ use mm2_test_helpers::for_tests::{enable_tendermint, enable_tendermint_without_b orderbook, orderbook_v2, set_price, usdc_ibc_iris_testnet_conf, MarketMakerIt, Mm2TestConf}; use mm2_test_helpers::structs::{OrderbookAddress, OrderbookV2Response, RpcV2Response, TendermintActivationResult}; - use serde_json::{self, json}; -use std::collections::HashSet; -use std::iter::FromIterator; const IRIS_TESTNET_RPCS: &[&str] = &["http://34.80.202.172:26657"]; const IRIS_TICKER: &str = "IRIS-TEST"; diff --git a/mm2src/mm2_main/tests/mm2_tests/tendermint_tests.rs b/mm2src/mm2_main/tests/mm2_tests/tendermint_tests.rs index 3892e85c23..ac1fe642cf 100644 --- a/mm2src/mm2_main/tests/mm2_tests/tendermint_tests.rs +++ b/mm2src/mm2_main/tests/mm2_tests/tendermint_tests.rs @@ -640,9 +640,9 @@ fn test_passive_coin_and_force_disable() { } mod swap { - use super::*; + use std::convert::TryFrom; + use std::{env, thread}; - use crate::integration_tests_common::enable_electrum; use common::executor::Timer; use common::log; use instant::Duration; @@ -650,8 +650,9 @@ mod swap { use mm2_test_helpers::for_tests::{check_my_swap_status, check_recent_swaps, check_stats_swap_status, enable_eth_coin, rick_conf, tbnb_conf, usdc_ibc_iris_testnet_conf, RICK_ELECTRUM_ADDRS}; - use std::convert::TryFrom; - use std::{env, thread}; + + use super::*; + use crate::integration_tests_common::enable_electrum; const BOB_PASSPHRASE: &str = "iris test seed"; const ALICE_PASSPHRASE: &str = "iris test2 seed"; diff --git a/mm2src/mm2_main/tests/mm2_tests/z_coin_tests.rs b/mm2src/mm2_main/tests/mm2_tests/z_coin_tests.rs index 7d9d1e45b8..fd180c9c98 100644 --- a/mm2src/mm2_main/tests/mm2_tests/z_coin_tests.rs +++ b/mm2src/mm2_main/tests/mm2_tests/z_coin_tests.rs @@ -1,4 +1,10 @@ -use crate::integration_tests_common::*; +use std::collections::HashSet; +use std::iter::FromIterator; +use std::num::NonZeroUsize; +use std::str::FromStr; +use std::thread; +use std::time::Duration; + use common::executor::Timer; use common::{block_on, log, now_ms, now_sec, wait_until_ms}; use mm2_number::BigDecimal; @@ -10,12 +16,8 @@ use mm2_test_helpers::for_tests::{disable_coin, init_withdraw, pirate_conf, rick use mm2_test_helpers::structs::{EnableCoinBalance, InitTaskResult, RpcV2Response, TransactionDetails, WithdrawStatus, ZcoinHistoryRes}; use serde_json::{self as json, json, Value as Json}; -use std::collections::HashSet; -use std::iter::FromIterator; -use std::num::NonZeroUsize; -use std::str::FromStr; -use std::thread; -use std::time::Duration; + +use crate::integration_tests_common::*; const ZOMBIE_TEST_BIP39_ACTIVATION_SEED: &str = "course flock lucky cereal hamster novel team never metal bean behind cute cruel matrix symptom fault harsh fashion impact prison glove then tree chef"; const ZOMBIE_TEST_BALANCE_SEED: &str = "zombie test seed"; diff --git a/mm2src/mm2_metamask/src/eip_1193_provider.rs b/mm2src/mm2_metamask/src/eip_1193_provider.rs index 2ccba26641..ecd5c4ee32 100644 --- a/mm2src/mm2_metamask/src/eip_1193_provider.rs +++ b/mm2src/mm2_metamask/src/eip_1193_provider.rs @@ -1,3 +1,6 @@ +use std::fmt; +use std::sync::Arc; + use common::executor::{spawn_local_abortable, AbortOnDropHandle}; use common::log::error; use futures::channel::{mpsc, oneshot}; @@ -6,8 +9,6 @@ use futures::StreamExt; use jsonrpc_core::Call; use serde::de::DeserializeOwned; use serde_json::Value as Json; -use std::fmt; -use std::sync::Arc; use web3::helpers::build_request; use web3::transports::eip_1193::{Eip1193, Provider as RawProvider}; use web3::{Error, RequestId, Result, Transport}; diff --git a/mm2src/mm2_metamask/src/metamask.rs b/mm2src/mm2_metamask/src/metamask.rs index 9fd135eee5..4fb427d509 100644 --- a/mm2src/mm2_metamask/src/metamask.rs +++ b/mm2src/mm2_metamask/src/metamask.rs @@ -1,5 +1,3 @@ -use crate::eip_1193_provider::Eip1193Provider; -use crate::metamask_error::{MetamaskError, MetamaskResult}; use futures::lock::{Mutex as AsyncMutex, MutexGuard as AsyncMutexGuard}; use itertools::Itertools; use lazy_static::lazy_static; @@ -11,6 +9,9 @@ use web3::helpers::CallFuture; use web3::types::H256; use web3::Transport; +use crate::eip_1193_provider::Eip1193Provider; +use crate::metamask_error::{MetamaskError, MetamaskResult}; + lazy_static! { /// This mutex is used to limit the number of concurrent requests to one. /// It's required to avoid switching ETH chain ID during the request. diff --git a/mm2src/mm2_metrics/src/lib.rs b/mm2src/mm2_metrics/src/lib.rs index 84aad52799..0dd0d91382 100644 --- a/mm2src/mm2_metrics/src/lib.rs +++ b/mm2src/mm2_metrics/src/lib.rs @@ -4,18 +4,18 @@ #[macro_use] pub mod mm_metrics; pub mod recorder; -pub use metrics; -#[cfg(not(target_arch = "wasm32"))] -pub use mm_metrics::prometheus; +use std::collections::HashMap; +use std::sync::{Arc, Weak}; use common::{executor::SpawnFuture, log::LogWeak}; use derive_more::Display; +pub use metrics; use mm2_err_handle::prelude::MmError; +#[cfg(not(target_arch = "wasm32"))] +pub use mm_metrics::prometheus; use mm_metrics::Metrics; use recorder::{MmRecorder, TryRecorder}; use serde_json::Value as Json; -use std::collections::HashMap; -use std::sync::{Arc, Weak}; pub type MmMetricsResult = Result>; diff --git a/mm2src/mm2_metrics/src/mm_metrics.rs b/mm2src/mm2_metrics/src/mm_metrics.rs index c64feb09d7..a9a6607a5b 100644 --- a/mm2src/mm2_metrics/src/mm_metrics.rs +++ b/mm2src/mm2_metrics/src/mm_metrics.rs @@ -1,3 +1,6 @@ +use std::sync::{atomic::Ordering, Arc}; +use std::{collections::HashMap, slice::Iter}; + use common::executor::Timer; #[cfg(not(target_arch = "wasm32"))] use common::log::error; use common::log::{LogArc, LogWeak}; @@ -5,8 +8,6 @@ use itertools::Itertools; use metrics::{Key, Label}; use mm2_err_handle::prelude::*; use serde_json::Value; -use std::sync::{atomic::Ordering, Arc}; -use std::{collections::HashMap, slice::Iter}; use crate::{common::log::Tag, MetricsOps, MmMetricsError, MmMetricsResult, MmRecorder, SpawnFuture}; @@ -254,16 +255,17 @@ impl MmHistogram { #[cfg(not(target_arch = "wasm32"))] pub mod prometheus { - use crate::{MetricsArc, MetricsWeak}; + use std::convert::Infallible; + use std::net::SocketAddr; - use super::*; use futures::future::{Future, FutureExt}; use hyper::http::{self, header, Request, Response, StatusCode}; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Server}; use mm2_err_handle::prelude::MmError; - use std::convert::Infallible; - use std::net::SocketAddr; + + use super::*; + use crate::{MetricsArc, MetricsWeak}; #[derive(Clone)] pub struct PrometheusCredentials { @@ -380,13 +382,13 @@ pub mod prometheus { #[cfg(test)] mod test { use std::time::Duration; - - use crate::{MetricsArc, MetricsOps}; + use std::time::Instant; use common::{block_on, executor::{abortable_queue::AbortableQueue, Timer}, log::{LogArc, LogState}}; - use std::time::Instant; + + use crate::{MetricsArc, MetricsOps}; #[test] fn test_collect_json() { diff --git a/mm2src/mm2_metrics/src/recorder.rs b/mm2src/mm2_metrics/src/recorder.rs index 45d55a67ac..a5b56116b4 100644 --- a/mm2src/mm2_metrics/src/recorder.rs +++ b/mm2src/mm2_metrics/src/recorder.rs @@ -1,11 +1,12 @@ -use crate::{mm_metrics::MmHistogram, MetricType, MetricsJson}; +use std::sync::{atomic::Ordering, Arc}; +use std::{collections::HashMap, slice::Iter}; use metrics::{Counter, Gauge, Histogram, Key, KeyName, Label, Recorder, Unit}; #[cfg(not(target_arch = "wasm32"))] use metrics_exporter_prometheus::formatting::{key_to_parts, write_metric_line, write_type_line}; use metrics_util::registry::{GenerationalAtomicStorage, GenerationalStorage, Registry}; -use std::sync::{atomic::Ordering, Arc}; -use std::{collections::HashMap, slice::Iter}; + +use crate::{mm_metrics::MmHistogram, MetricType, MetricsJson}; pub struct Snapshot { pub counters: HashMap, u64>>, diff --git a/mm2src/mm2_net/src/grpc_web.rs b/mm2src/mm2_net/src/grpc_web.rs index 43ba449502..ba8d011ec0 100644 --- a/mm2src/mm2_net/src/grpc_web.rs +++ b/mm2src/mm2_net/src/grpc_web.rs @@ -1,13 +1,14 @@ -/// The small module implementing gRPC-WEB support -/// Implementation was taken from https://github.com/hyperium/tonic/blob/ddab65ede90f503360b7adb0d7afe6d5b7bb8b02/examples/src/grpc-web/client.rs -/// with minor refactoring -use crate::transport::SlurpError; use bytes::{Buf, BufMut, Bytes, BytesMut}; use common::{cfg_native, cfg_wasm32}; use http::header::{ACCEPT, CONTENT_TYPE}; use mm2_err_handle::prelude::*; use prost::DecodeError; +/// The small module implementing gRPC-WEB support +/// Implementation was taken from https://github.com/hyperium/tonic/blob/ddab65ede90f503360b7adb0d7afe6d5b7bb8b02/examples/src/grpc-web/client.rs +/// with minor refactoring +use crate::transport::SlurpError; + cfg_native! { use common::APPLICATION_GRPC_WEB; use crate::transport::slurp_req; diff --git a/mm2src/mm2_net/src/ip_addr.rs b/mm2src/mm2_net/src/ip_addr.rs index 5b46f54891..5180962d03 100644 --- a/mm2src/mm2_net/src/ip_addr.rs +++ b/mm2src/mm2_net/src/ip_addr.rs @@ -1,14 +1,16 @@ -use crate::transport::slurp_url; +use std::fs; +use std::io::Read; +use std::net::{IpAddr, Ipv4Addr}; +use std::path::Path; + use common::log; use gstuff::try_s; use gstuff::{ERR, ERRL}; use mm2_core::mm_ctx::MmArc; use rand::rngs::SmallRng; use rand::{Rng, SeedableRng}; -use std::fs; -use std::io::Read; -use std::net::{IpAddr, Ipv4Addr}; -use std::path::Path; + +use crate::transport::slurp_url; const IP_PROVIDERS: [&str; 2] = ["http://checkip.amazonaws.com/", "http://api.ipify.org"]; diff --git a/mm2src/mm2_net/src/native_http.rs b/mm2src/mm2_net/src/native_http.rs index 9a79611835..f613a072ba 100644 --- a/mm2src/mm2_net/src/native_http.rs +++ b/mm2src/mm2_net/src/native_http.rs @@ -12,16 +12,15 @@ //! use async_trait::async_trait; +use common::wio::{drive03, HYPER}; +use common::APPLICATION_JSON; use futures::channel::oneshot::Canceled; use http::{header, HeaderValue, Request}; use hyper::client::connect::Connect; use hyper::client::ResponseFuture; use hyper::{Body, Client}; -use serde_json::Value as Json; - -use common::wio::{drive03, HYPER}; -use common::APPLICATION_JSON; use mm2_err_handle::prelude::*; +use serde_json::Value as Json; use super::transport::{SlurpError, SlurpResult, SlurpResultJson}; @@ -233,9 +232,10 @@ impl From for SlurpError { #[cfg(test)] mod tests { - use crate::native_http::slurp_url; use common::block_on; + use crate::native_http::slurp_url; + #[test] fn test_slurp_req() { let (status, headers, body) = block_on(slurp_url("https://httpbin.org/get")).unwrap(); diff --git a/mm2src/mm2_net/src/native_tls/acceptor.rs b/mm2src/mm2_net/src/native_tls/acceptor.rs index cd5c86db84..df96e147e4 100644 --- a/mm2src/mm2_net/src/native_tls/acceptor.rs +++ b/mm2src/mm2_net/src/native_tls/acceptor.rs @@ -1,16 +1,18 @@ -use crate::native_tls::builder::{AcceptorBuilder, WantsTlsConfig}; use core::task::{Context, Poll}; -use futures_util::ready; -use hyper::server::{accept::Accept, - conn::{AddrIncoming, AddrStream}}; -use rustls::ServerConfig; use std::future::Future; use std::io; use std::net::SocketAddr; use std::pin::Pin; use std::sync::Arc; + +use futures_util::ready; +use hyper::server::{accept::Accept, + conn::{AddrIncoming, AddrStream}}; +use rustls::ServerConfig; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; +use crate::native_tls::builder::{AcceptorBuilder, WantsTlsConfig}; + enum State { Handshaking(tokio_rustls::Accept), Streaming(tokio_rustls::server::TlsStream), diff --git a/mm2src/mm2_net/src/native_tls/builder.rs b/mm2src/mm2_net/src/native_tls/builder.rs index 415a998b45..ef488ec480 100644 --- a/mm2src/mm2_net/src/native_tls/builder.rs +++ b/mm2src/mm2_net/src/native_tls/builder.rs @@ -1,7 +1,9 @@ -use crate::native_tls::TlsAcceptor; +use std::sync::Arc; + use hyper::server::conn::AddrIncoming; use rustls::ServerConfig; -use std::sync::Arc; + +use crate::native_tls::TlsAcceptor; /// Builder for [`TlsAcceptor`] pub struct AcceptorBuilder(State); diff --git a/mm2src/mm2_net/src/network_event.rs b/mm2src/mm2_net/src/network_event.rs index 35ce5de40d..d71053b2e2 100644 --- a/mm2src/mm2_net/src/network_event.rs +++ b/mm2src/mm2_net/src/network_event.rs @@ -1,4 +1,3 @@ -use crate::p2p::P2PContext; use async_trait::async_trait; use common::{executor::{SpawnFuture, Timer}, log::info}; @@ -8,6 +7,8 @@ use mm2_event_stream::{Event, EventStreamConfiguration}; use mm2_libp2p::behaviours::atomicdex; use serde_json::json; +use crate::p2p::P2PContext; + pub struct NetworkEvent { ctx: MmArc, } diff --git a/mm2src/mm2_net/src/p2p.rs b/mm2src/mm2_net/src/p2p.rs index d76cd550bd..504020498e 100644 --- a/mm2src/mm2_net/src/p2p.rs +++ b/mm2src/mm2_net/src/p2p.rs @@ -1,7 +1,8 @@ +use std::sync::Arc; + use mm2_core::mm_ctx::MmArc; use mm2_libp2p::behaviours::atomicdex::AdexCmdTx; use parking_lot::Mutex; -use std::sync::Arc; pub struct P2PContext { /// Using Mutex helps to prevent cloning which can actually result to channel being unbounded in case of using 1 tx clone per 1 message. diff --git a/mm2src/mm2_net/src/sse_handler.rs b/mm2src/mm2_net/src/sse_handler.rs index f57018ca04..113cfe3bea 100644 --- a/mm2src/mm2_net/src/sse_handler.rs +++ b/mm2src/mm2_net/src/sse_handler.rs @@ -1,7 +1,8 @@ +use std::convert::Infallible; + use hyper::{body::Bytes, Body, Request, Response}; use mm2_core::mm_ctx::MmArc; use serde_json::json; -use std::convert::Infallible; pub const SSE_ENDPOINT: &str = "/event-stream"; diff --git a/mm2src/mm2_net/src/transport.rs b/mm2src/mm2_net/src/transport.rs index 2ba04b65e1..adf1868708 100644 --- a/mm2src/mm2_net/src/transport.rs +++ b/mm2src/mm2_net/src/transport.rs @@ -8,7 +8,6 @@ use serde_json::{Error, Value as Json}; #[cfg(not(target_arch = "wasm32"))] pub use crate::native_http::{slurp_post_json, slurp_req, slurp_req_body, slurp_url, slurp_url_with_headers}; - #[cfg(target_arch = "wasm32")] pub use crate::wasm_http::{slurp_post_json, slurp_url, slurp_url_with_headers}; diff --git a/mm2src/mm2_net/src/wasm_http.rs b/mm2src/mm2_net/src/wasm_http.rs index 3767c2f40c..cd7a723c4b 100644 --- a/mm2src/mm2_net/src/wasm_http.rs +++ b/mm2src/mm2_net/src/wasm_http.rs @@ -1,4 +1,5 @@ -use crate::transport::{SlurpError, SlurpResult}; +use std::collections::HashMap; + use common::executor::spawn_local; use common::{stringify_js_error, APPLICATION_JSON}; use futures::channel::oneshot; @@ -6,12 +7,13 @@ use http::header::CONTENT_TYPE; use http::{HeaderMap, StatusCode}; use js_sys::Uint8Array; use mm2_err_handle::prelude::*; -use std::collections::HashMap; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::JsFuture; use web_sys::{Request, RequestInit, RequestMode, Response as JsResponse}; +use crate::transport::{SlurpError, SlurpResult}; + /// The result containing either a pair of (HTTP status code, body) or a stringified error. pub type FetchResult = Result<(StatusCode, T), MmError>; @@ -283,9 +285,10 @@ impl RequestBody { } mod tests { - use super::*; use wasm_bindgen_test::*; + use super::*; + wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] diff --git a/mm2src/mm2_net/src/wasm_ws.rs b/mm2src/mm2_net/src/wasm_ws.rs index 900e08b53a..56751442b7 100644 --- a/mm2src/mm2_net/src/wasm_ws.rs +++ b/mm2src/mm2_net/src/wasm_ws.rs @@ -1,3 +1,9 @@ +use std::convert::Infallible; +use std::future::Future; +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context, Poll}; + use async_trait::async_trait; use common::executor::SpawnFuture; use common::log::{debug, error}; @@ -9,11 +15,6 @@ use mm2_err_handle::prelude::*; use mm2_state_machine::prelude::*; use mm2_state_machine::state_machine::{ChangeStateExt, LastState, State, StateMachineTrait, StateResult}; use serde_json::{self as json, Value as Json}; -use std::convert::Infallible; -use std::future::Future; -use std::pin::Pin; -use std::sync::Arc; -use std::task::{Context, Poll}; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{CloseEvent, DomException, MessageEvent, WebSocket}; @@ -659,16 +660,18 @@ where } mod tests { - use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use common::custom_futures::timeout::FutureTimerExt; use common::executor::abortable_queue::AbortableQueue; use common::log::{debug, wasm_log::register_wasm_log}; use common::{WasmUnwrapErrExt, WasmUnwrapExt}; use lazy_static::lazy_static; use serde_json::json; - use std::sync::atomic::{AtomicUsize, Ordering}; use wasm_bindgen_test::*; + use super::*; + wasm_bindgen_test_configure!(run_in_browser); lazy_static! { diff --git a/mm2src/mm2_number/src/big_int_str.rs b/mm2src/mm2_number/src/big_int_str.rs index d0855cfbbf..89f40aa6f5 100644 --- a/mm2src/mm2_number/src/big_int_str.rs +++ b/mm2src/mm2_number/src/big_int_str.rs @@ -1,6 +1,7 @@ +use std::fmt; + use num_bigint::BigInt; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; -use std::fmt; /// BigInt wrapper de/serializable from/to string representation #[derive(Clone, Eq, PartialEq)] @@ -54,9 +55,10 @@ impl<'de> Deserialize<'de> for BigIntStr { #[cfg(test)] mod big_int_str_tests { - use super::*; use serde_json::{self as json}; + use super::*; + #[test] fn test_bigint_str_serialize() { let num = BigIntStr(1023.into()); diff --git a/mm2src/mm2_number/src/bigdecimal_custom.rs b/mm2src/mm2_number/src/bigdecimal_custom.rs index a63f00a4ab..896c209214 100644 --- a/mm2src/mm2_number/src/bigdecimal_custom.rs +++ b/mm2src/mm2_number/src/bigdecimal_custom.rs @@ -1,6 +1,7 @@ +use std::ops::Div; + use bigdecimal::BigDecimal; use bigdecimal::Zero; -use std::ops::Div; pub trait CheckedDivision { fn checked_div(self, other: BigDecimal) -> Option; diff --git a/mm2src/mm2_number/src/fraction.rs b/mm2src/mm2_number/src/fraction.rs index ae936adae5..a9855f7d90 100644 --- a/mm2src/mm2_number/src/fraction.rs +++ b/mm2src/mm2_number/src/fraction.rs @@ -1,11 +1,12 @@ -use crate::big_int_str::BigIntStr; -use crate::from_dec_to_ratio; use bigdecimal::BigDecimal; use num_bigint::BigInt; use num_rational::BigRational; use serde::Serialize; use serde::{de, Deserialize, Deserializer}; +use crate::big_int_str::BigIntStr; +use crate::from_dec_to_ratio; + /// Rational number representation de/serializable in human readable form /// Should simplify the visual perception and parsing in code #[derive(Clone, Debug, Eq, PartialEq, Serialize)] diff --git a/mm2src/mm2_number/src/lib.rs b/mm2src/mm2_number/src/lib.rs index 6d1d20f1ca..0110fb255e 100644 --- a/mm2src/mm2_number/src/lib.rs +++ b/mm2src/mm2_number/src/lib.rs @@ -4,16 +4,14 @@ mod fraction; mod mm_number; mod mm_number_multi_repr; +pub use bigdecimal; +pub use bigdecimal::BigDecimal; pub use fraction::Fraction; pub use mm_number::MmNumber; pub use mm_number_multi_repr::MmNumberMultiRepr; - -pub use bigdecimal; pub use num_bigint; -pub use num_rational; - -pub use bigdecimal::BigDecimal; pub use num_bigint::{BigInt, BigUint}; +pub use num_rational; pub use num_rational::BigRational; pub use paste::paste; diff --git a/mm2src/mm2_number/src/mm_number.rs b/mm2src/mm2_number/src/mm_number.rs index 3934f02391..b3ff747297 100644 --- a/mm2src/mm2_number/src/mm_number.rs +++ b/mm2src/mm2_number/src/mm_number.rs @@ -1,7 +1,7 @@ -use crate::fraction::Fraction; -use crate::{from_dec_to_ratio, from_ratio_to_dec}; -use bigdecimal::BigDecimal; use core::ops::{Add, AddAssign, Div, Mul, Sub}; +use std::str::FromStr; + +use bigdecimal::BigDecimal; use num_bigint::BigInt; use num_rational::BigRational; use num_traits::CheckedDiv; @@ -9,7 +9,9 @@ use num_traits::Zero; use serde::Serialize; use serde::{de, Deserialize, Deserializer}; use serde_json::value::RawValue; -use std::str::FromStr; + +use crate::fraction::Fraction; +use crate::{from_dec_to_ratio, from_ratio_to_dec}; /// Construct a `$name` detailed number that have decimal, fraction and rational representations. /// The macro takes the `$name` name of the structure and the `$base_name` that is used to generate three different fields: @@ -249,10 +251,12 @@ impl From<&'static str> for MmNumber { #[cfg(test)] mod tests { - use super::*; - use serde_json::{self as json, json}; use std::str::FromStr; + use serde_json::{self as json, json}; + + use super::*; + #[test] fn test_from_dec_to_ratio() { let number: BigDecimal = "11.00000000000000000000000000000000000000".parse().unwrap(); diff --git a/mm2src/mm2_number/src/mm_number_multi_repr.rs b/mm2src/mm2_number/src/mm_number_multi_repr.rs index 501a7626ba..71eaee2b00 100644 --- a/mm2src/mm2_number/src/mm_number_multi_repr.rs +++ b/mm2src/mm2_number/src/mm_number_multi_repr.rs @@ -1,10 +1,11 @@ -use crate::fraction::Fraction; -use crate::from_ratio_to_dec; -use crate::mm_number::MmNumber; use bigdecimal::BigDecimal; use num_rational::BigRational; use serde::Serialize; +use crate::fraction::Fraction; +use crate::from_ratio_to_dec; +use crate::mm_number::MmNumber; + /// MmNumber representation in all available forms. #[derive(Clone, Debug, Serialize)] pub struct MmNumberMultiRepr { diff --git a/mm2src/mm2_p2p/src/behaviours/atomicdex.rs b/mm2src/mm2_p2p/src/behaviours/atomicdex.rs index c895466515..73f3a51bcf 100644 --- a/mm2src/mm2_p2p/src/behaviours/atomicdex.rs +++ b/mm2src/mm2_p2p/src/behaviours/atomicdex.rs @@ -1,3 +1,10 @@ +use std::collections::hash_map::DefaultHasher; +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::iter; +use std::net::IpAddr; +use std::task::{Context, Poll}; + use common::executor::SpawnFuture; use derive_more::Display; use futures::channel::mpsc::{channel, Receiver, Sender}; @@ -10,6 +17,9 @@ use instant::Duration; use libp2p::core::transport::Boxed as BoxedTransport; use libp2p::core::ConnectedPoint; use libp2p::floodsub::{Floodsub, FloodsubEvent, Topic as FloodsubTopic}; +pub use libp2p::gossipsub::{Behaviour as Gossipsub, IdentTopic, MessageAuthenticity, MessageId, Topic, TopicHash}; +pub use libp2p::gossipsub::{ConfigBuilder as GossipsubConfigBuilder, Event as GossipsubEvent, + Message as GossipsubMessage}; use libp2p::gossipsub::{PublishError, SubscriptionError, ValidationMode}; use libp2p::multiaddr::Protocol; use libp2p::request_response::ResponseChannel; @@ -19,12 +29,6 @@ use libp2p::{Multiaddr, Transport}; use log::{debug, error, info}; use rand::seq::SliceRandom; use rand::Rng; -use std::collections::hash_map::DefaultHasher; -use std::collections::HashMap; -use std::hash::{Hash, Hasher}; -use std::iter; -use std::net::IpAddr; -use std::task::{Context, Poll}; use super::peers_exchange::{PeerAddresses, PeersExchange, PeersExchangeRequest, PeersExchangeResponse}; use super::ping::AdexPing; @@ -35,10 +39,6 @@ use crate::relay_address::{RelayAddress, RelayAddressError}; use crate::swarm_runtime::SwarmRuntime; use crate::{NetworkInfo, NetworkPorts, RequestResponseBehaviourEvent}; -pub use libp2p::gossipsub::{Behaviour as Gossipsub, IdentTopic, MessageAuthenticity, MessageId, Topic, TopicHash}; -pub use libp2p::gossipsub::{ConfigBuilder as GossipsubConfigBuilder, Event as GossipsubEvent, - Message as GossipsubMessage}; - pub type AdexCmdTx = Sender; pub type AdexEventRx = Receiver; diff --git a/mm2src/mm2_p2p/src/behaviours/mod.rs b/mm2src/mm2_p2p/src/behaviours/mod.rs index dd78d7ed65..059891c2b0 100644 --- a/mm2src/mm2_p2p/src/behaviours/mod.rs +++ b/mm2src/mm2_p2p/src/behaviours/mod.rs @@ -7,17 +7,18 @@ pub(crate) mod request_response; #[cfg(test)] mod tests { + use std::collections::{HashMap, HashSet}; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + use std::sync::Arc; + #[cfg(not(windows))] use std::sync::Mutex; + use std::time::Duration; + use async_std::task::spawn; use common::executor::abortable_queue::AbortableQueue; use futures::channel::{mpsc, oneshot}; use futures::{SinkExt, StreamExt}; use lazy_static::lazy_static; use libp2p::{Multiaddr, PeerId}; - use std::collections::{HashMap, HashSet}; - use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; - use std::sync::Arc; - #[cfg(not(windows))] use std::sync::Mutex; - use std::time::Duration; use crate::behaviours::peers_exchange::{PeerIdSerde, PeersExchange}; use crate::{spawn_gossipsub, AdexBehaviourCmd, AdexBehaviourEvent, AdexResponse, AdexResponseChannel, NetworkInfo, diff --git a/mm2src/mm2_p2p/src/behaviours/peers_exchange.rs b/mm2src/mm2_p2p/src/behaviours/peers_exchange.rs index 38f3b35dc8..41f16fe68b 100644 --- a/mm2src/mm2_p2p/src/behaviours/peers_exchange.rs +++ b/mm2src/mm2_p2p/src/behaviours/peers_exchange.rs @@ -1,3 +1,8 @@ +use std::{collections::{HashMap, HashSet, VecDeque}, + iter, + task::Poll, + time::Duration}; + use futures::StreamExt; use futures_ticker::Ticker; use libp2p::{multiaddr::Protocol, @@ -8,10 +13,6 @@ use libp2p::{multiaddr::Protocol, use log::{info, warn}; use rand::seq::SliceRandom; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use std::{collections::{HashMap, HashSet, VecDeque}, - iter, - task::Poll, - time::Duration}; use super::request_response::Codec; use crate::NetworkInfo; diff --git a/mm2src/mm2_p2p/src/behaviours/ping.rs b/mm2src/mm2_p2p/src/behaviours/ping.rs index 463d740cdb..b3516af886 100644 --- a/mm2src/mm2_p2p/src/behaviours/ping.rs +++ b/mm2src/mm2_p2p/src/behaviours/ping.rs @@ -1,7 +1,8 @@ +use std::{collections::VecDeque, task::Poll}; + use libp2p::ping::{Behaviour, Config}; use libp2p::swarm::{CloseConnection, NetworkBehaviour, PollParameters, ToSwarm}; use log::error; -use std::{collections::VecDeque, task::Poll}; use void::Void; pub struct AdexPing { diff --git a/mm2src/mm2_p2p/src/behaviours/request_response.rs b/mm2src/mm2_p2p/src/behaviours/request_response.rs index b3b949cedb..aca5eb659c 100644 --- a/mm2src/mm2_p2p/src/behaviours/request_response.rs +++ b/mm2src/mm2_p2p/src/behaviours/request_response.rs @@ -1,3 +1,6 @@ +use std::collections::{HashMap, VecDeque}; +use std::io; + use async_trait::async_trait; use futures::channel::{mpsc, oneshot}; use futures::io::{AsyncRead, AsyncWrite}; @@ -15,8 +18,6 @@ use libp2p::{request_response::{Behaviour as RequestResponse, Config as RequestR use log::{error, warn}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; -use std::collections::{HashMap, VecDeque}; -use std::io; use super::atomicdex::MAX_BUFFER_SIZE; use crate::{decode_message, encode_message}; diff --git a/mm2src/mm2_p2p/src/lib.rs b/mm2src/mm2_p2p/src/lib.rs index fd13446f6e..38867b277a 100644 --- a/mm2src/mm2_p2p/src/lib.rs +++ b/mm2src/mm2_p2p/src/lib.rs @@ -6,34 +6,29 @@ mod network; mod relay_address; mod swarm_runtime; -use lazy_static::lazy_static; -use secp256k1::{Message as SecpMessage, PublicKey as Secp256k1Pubkey, Secp256k1, SecretKey, SignOnly, Signature, - VerifyOnly}; -use serde::{de, Deserialize, Serialize, Serializer}; -use sha2::{Digest, Sha256}; - -pub use crate::swarm_runtime::SwarmRuntime; - // atomicdex related re-exports pub use behaviours::atomicdex::{get_gossip_mesh, get_gossip_peer_topics, get_gossip_topic_peers, get_peers_info, get_relay_mesh, spawn_gossipsub, AdexBehaviourCmd, AdexBehaviourError, AdexBehaviourEvent, AdexCmdTx, AdexEventRx, AdexResponse, AdexResponseChannel, GossipsubEvent, GossipsubMessage, MessageId, NodeType, TopicHash, WssCerts}; - // peers-exchange re-exports pub use behaviours::peers_exchange::PeerAddresses; - // request-response related re-exports pub use behaviours::request_response::RequestResponseBehaviourEvent; - +use lazy_static::lazy_static; // libp2p related re-exports pub use libp2p::identity::DecodingError; pub use libp2p::identity::{secp256k1::PublicKey as Libp2pSecpPublic, PublicKey as Libp2pPublic}; pub use libp2p::{Multiaddr, PeerId}; - // relay-address related re-exports pub use relay_address::RelayAddress; pub use relay_address::RelayAddressError; +use secp256k1::{Message as SecpMessage, PublicKey as Secp256k1Pubkey, Secp256k1, SecretKey, SignOnly, Signature, + VerifyOnly}; +use serde::{de, Deserialize, Serialize, Serializer}; +use sha2::{Digest, Sha256}; + +pub use crate::swarm_runtime::SwarmRuntime; lazy_static! { static ref SECP_VERIFY: Secp256k1 = Secp256k1::verification_only(); diff --git a/mm2src/mm2_p2p/src/network.rs b/mm2src/mm2_p2p/src/network.rs index 364cee72cf..86c4608b50 100644 --- a/mm2src/mm2_p2p/src/network.rs +++ b/mm2src/mm2_p2p/src/network.rs @@ -1,6 +1,7 @@ -use crate::relay_address::RelayAddress; use libp2p::PeerId; +use crate::relay_address::RelayAddress; + pub const NETID_8762: u16 = 8762; #[cfg_attr(target_arch = "wasm32", allow(dead_code))] diff --git a/mm2src/mm2_p2p/src/relay_address.rs b/mm2src/mm2_p2p/src/relay_address.rs index a568ea9722..3b0ae7faa0 100644 --- a/mm2src/mm2_p2p/src/relay_address.rs +++ b/mm2src/mm2_p2p/src/relay_address.rs @@ -1,9 +1,11 @@ -use crate::{NetworkInfo, NetworkPorts}; +use std::str::FromStr; + use derive_more::Display; use lazy_static::lazy_static; use libp2p::Multiaddr; use serde::{de, Deserialize, Deserializer, Serialize}; -use std::str::FromStr; + +use crate::{NetworkInfo, NetworkPorts}; #[derive(Clone, Debug, Display, Serialize)] pub enum RelayAddressError { diff --git a/mm2src/mm2_p2p/src/swarm_runtime.rs b/mm2src/mm2_p2p/src/swarm_runtime.rs index cd83c0181f..2d5ea51abd 100644 --- a/mm2src/mm2_p2p/src/swarm_runtime.rs +++ b/mm2src/mm2_p2p/src/swarm_runtime.rs @@ -1,8 +1,9 @@ +use std::pin::Pin; +use std::sync::Arc; + use common::executor::{BoxFutureSpawner, SpawnFuture}; use futures::Future; use libp2p::swarm::Executor; -use std::pin::Pin; -use std::sync::Arc; #[derive(Clone)] pub struct SwarmRuntime { diff --git a/mm2src/mm2_rpc/src/data/legacy.rs b/mm2src/mm2_rpc/src/data/legacy.rs index c16a328847..f99aec1e9d 100644 --- a/mm2src/mm2_rpc/src/data/legacy.rs +++ b/mm2src/mm2_rpc/src/data/legacy.rs @@ -3,18 +3,18 @@ #[path = "legacy/utility.rs"] mod utility; #[path = "legacy/wallet.rs"] mod wallet; +use std::ops::Deref; + pub use activation::{eth::GasStationPricePolicy, utxo::{ElectrumProtocol, UtxoMergeParams}, CoinInitResponse, EnabledCoin, GetEnabledResponse}; +use common::serde_derive::{Deserialize, Serialize}; pub use orders::{AggregatedOrderbookEntry, MatchBy, OrderConfirmationsSettings, OrderType, OrderbookRequest, OrderbookResponse, RpcOrderbookEntry, SellBuyRequest, SellBuyResponse, TakerAction, TakerRequestForRpc}; pub use utility::{MmVersionResponse, Status}; pub use wallet::BalanceResponse; -use common::serde_derive::{Deserialize, Serialize}; -use std::ops::Deref; - #[derive(Serialize, Deserialize)] pub struct Mm2RpcResult { pub result: T, diff --git a/mm2src/mm2_rpc/src/data/legacy/orders.rs b/mm2src/mm2_rpc/src/data/legacy/orders.rs index 8f50966da9..a18cb4f50e 100644 --- a/mm2src/mm2_rpc/src/data/legacy/orders.rs +++ b/mm2src/mm2_rpc/src/data/legacy/orders.rs @@ -1,10 +1,10 @@ -use rpc::v1::types::H256 as H256Json; -use serde::{Deserialize, Serialize}; use std::collections::HashSet; -use uuid::Uuid; use common::true_f; use mm2_number::{construct_detailed, BigDecimal, BigRational, Fraction, MmNumber}; +use rpc::v1::types::H256 as H256Json; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; #[derive(Deserialize, Serialize, Debug)] pub struct SellBuyRequest { diff --git a/mm2src/mm2_rpc/src/data/legacy/wallet.rs b/mm2src/mm2_rpc/src/data/legacy/wallet.rs index ddcb5c2354..78e13bcccb 100644 --- a/mm2src/mm2_rpc/src/data/legacy/wallet.rs +++ b/mm2src/mm2_rpc/src/data/legacy/wallet.rs @@ -1,6 +1,5 @@ -use serde::{Deserialize, Serialize}; - use mm2_number::BigDecimal; +use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] pub struct BalanceResponse { diff --git a/mm2src/mm2_rpc/src/wasm_rpc.rs b/mm2src/mm2_rpc/src/wasm_rpc.rs index cda70a84d5..74b8cd8b0f 100644 --- a/mm2src/mm2_rpc/src/wasm_rpc.rs +++ b/mm2src/mm2_rpc/src/wasm_rpc.rs @@ -1,10 +1,11 @@ +use std::pin::Pin; +use std::task::{Context, Poll}; + use futures::channel::{mpsc, oneshot}; use futures::lock::Mutex as AsyncMutex; use futures::Stream; use gstuff::{ERR, ERRL}; use serde_json::Value as Json; -use std::pin::Pin; -use std::task::{Context, Poll}; const CHANNEL_BUF_SIZE: usize = 1024; diff --git a/mm2src/mm2_state_machine/src/state_machine.rs b/mm2src/mm2_state_machine/src/state_machine.rs index 63ce6a96a3..3e1b1a7dbf 100644 --- a/mm2src/mm2_state_machine/src/state_machine.rs +++ b/mm2src/mm2_state_machine/src/state_machine.rs @@ -2,9 +2,10 @@ //! //! See the usage examples in the `tests` module. +use async_trait::async_trait; + use crate::prelude::*; use crate::NotSame; -use async_trait::async_trait; /// A trait that state machine implementations should implement. #[async_trait] @@ -152,13 +153,15 @@ impl ErrorGuard { #[cfg(test)] mod tests { - use super::*; + use std::collections::HashMap; + use std::convert::Infallible; + use common::block_on; use common::executor::spawn; use futures::channel::mpsc; use futures::{SinkExt, StreamExt}; - use std::collections::HashMap; - use std::convert::Infallible; + + use super::*; type UserId = usize; type Login = String; diff --git a/mm2src/mm2_state_machine/src/storable_state_machine.rs b/mm2src/mm2_state_machine/src/storable_state_machine.rs index c3238f5904..1556ab6dbe 100644 --- a/mm2src/mm2_state_machine/src/storable_state_machine.rs +++ b/mm2src/mm2_state_machine/src/storable_state_machine.rs @@ -1,6 +1,7 @@ +use async_trait::async_trait; + use crate::prelude::*; use crate::state_machine::{ChangeGuard, ErrorGuard}; -use async_trait::async_trait; /// A trait representing the initial state of a state machine. pub trait InitialState { @@ -257,11 +258,13 @@ impl> ChangeInitialSt #[cfg(test)] mod tests { - use super::*; - use common::block_on; use std::collections::HashMap; use std::convert::Infallible; + use common::block_on; + + use super::*; + struct StorageTest { events_unfinished: HashMap>, events_finished: HashMap>, diff --git a/mm2src/mm2_test_helpers/src/for_tests.rs b/mm2src/mm2_test_helpers/src/for_tests.rs index cb3abed0ba..7d2e9a9f45 100644 --- a/mm2src/mm2_test_helpers/src/for_tests.rs +++ b/mm2src/mm2_test_helpers/src/for_tests.rs @@ -1,7 +1,14 @@ //! Helpers used in the unit and integration tests. -use crate::electrums::qtum_electrums; -use crate::structs::*; +use std::collections::HashMap; +use std::convert::TryFrom; +use std::env; +#[cfg(not(target_arch = "wasm32"))] use std::io::Write; +use std::net::IpAddr; +use std::num::NonZeroUsize; +use std::process::Child; +use std::sync::Mutex; + use common::custom_futures::repeatable::{Ready, Retry}; use common::executor::Timer; use common::log::debug; @@ -18,16 +25,11 @@ use mm2_rpc::data::legacy::{BalanceResponse, ElectrumProtocol}; use rand::Rng; use serde::{Deserialize, Serialize}; use serde_json::{self as json, json, Value as Json}; -use std::collections::HashMap; -use std::convert::TryFrom; -use std::env; -#[cfg(not(target_arch = "wasm32"))] use std::io::Write; -use std::net::IpAddr; -use std::num::NonZeroUsize; -use std::process::Child; -use std::sync::Mutex; use uuid::Uuid; +use crate::electrums::qtum_electrums; +use crate::structs::*; + cfg_native! { use common::block_on; use common::log::dashboard_path; @@ -845,9 +847,10 @@ pub fn mm_ctx_with_custom_db() -> MmArc { MmCtxBuilder::new().with_test_db_names #[cfg(not(target_arch = "wasm32"))] pub fn mm_ctx_with_custom_db() -> MmArc { - use db_common::sqlite::rusqlite::Connection; use std::sync::Arc; + use db_common::sqlite::rusqlite::Connection; + let ctx = MmCtxBuilder::new().into_mm_arc(); let connection = Connection::open_in_memory().unwrap(); diff --git a/mm2src/mm2_test_helpers/src/structs.rs b/mm2src/mm2_test_helpers/src/structs.rs index bd9f3e3975..b8d469583f 100644 --- a/mm2src/mm2_test_helpers/src/structs.rs +++ b/mm2src/mm2_test_helpers/src/structs.rs @@ -4,15 +4,16 @@ //! backwards compatibility //! Use `#[serde(deny_unknown_fields)]` for all structs for tests to fail in case of adding new fields to the response +use std::collections::{HashMap, HashSet}; +use std::fmt; +use std::num::NonZeroUsize; + use http::{HeaderMap, StatusCode}; use mm2_number::{BigDecimal, BigRational, Fraction, MmNumber}; use mm2_rpc::data::legacy::{MatchBy, OrderConfirmationsSettings, OrderType, RpcOrderbookEntry, TakerAction}; use rpc::v1::types::H256 as H256Json; use serde::de::DeserializeOwned; use serde_json::Value as Json; -use std::collections::{HashMap, HashSet}; -use std::fmt; -use std::num::NonZeroUsize; use uuid::Uuid; #[derive(Debug, Deserialize)] @@ -987,9 +988,10 @@ pub struct GetLockedAmountResponse { } pub mod gui_storage { - use mm2_number::BigDecimal; use std::collections::BTreeSet; + use mm2_number::BigDecimal; + #[derive(Debug, Deserialize, PartialEq)] #[serde(tag = "type")] #[serde(rename_all = "lowercase")] diff --git a/mm2src/rpc_task/src/handle.rs b/mm2src/rpc_task/src/handle.rs index 02657569c3..e1e6111fda 100644 --- a/mm2src/rpc_task/src/handle.rs +++ b/mm2src/rpc_task/src/handle.rs @@ -1,11 +1,13 @@ -use crate::manager::{RpcTaskManager, RpcTaskManagerWeak}; -use crate::{RpcTask, RpcTaskError, RpcTaskResult, TaskId, TaskStatus}; +use std::sync::MutexGuard; +use std::time::Duration; + use common::custom_futures::timeout::FutureTimerExt; use common::log::LogOnError; use futures::channel::oneshot; use mm2_err_handle::prelude::*; -use std::sync::MutexGuard; -use std::time::Duration; + +use crate::manager::{RpcTaskManager, RpcTaskManagerWeak}; +use crate::{RpcTask, RpcTaskError, RpcTaskResult, TaskId, TaskStatus}; type TaskManagerLock<'a, Task> = MutexGuard<'a, RpcTaskManager>; diff --git a/mm2src/rpc_task/src/lib.rs b/mm2src/rpc_task/src/lib.rs index b18fa15047..47f5a45677 100644 --- a/mm2src/rpc_task/src/lib.rs +++ b/mm2src/rpc_task/src/lib.rs @@ -1,10 +1,11 @@ +use std::sync::atomic::AtomicU64; +use std::time::Duration; + use common::custom_futures::timeout::TimeoutError; use derive_more::Display; use futures::channel::oneshot; use mm2_err_handle::prelude::*; use serde::Serialize; -use std::sync::atomic::AtomicU64; -use std::time::Duration; #[macro_use] extern crate ser_error_derive; #[macro_use] extern crate serde_derive; diff --git a/mm2src/rpc_task/src/manager.rs b/mm2src/rpc_task/src/manager.rs index 207c1ffba6..d2719516be 100644 --- a/mm2src/rpc_task/src/manager.rs +++ b/mm2src/rpc_task/src/manager.rs @@ -1,15 +1,17 @@ -use crate::task::RpcTaskTypes; -use crate::{AtomicTaskId, RpcTask, RpcTaskError, RpcTaskHandle, RpcTaskResult, RpcTaskStatus, RpcTaskStatusAlias, - TaskAbortHandle, TaskAbortHandler, TaskId, TaskStatus, TaskStatusError, UserActionSender}; +use std::collections::hash_map::Entry; +use std::collections::HashMap; +use std::sync::atomic::Ordering; +use std::sync::{Arc, Mutex, Weak}; + use common::executor::SpawnFuture; use common::log::{debug, info}; use futures::channel::oneshot; use futures::future::{select, Either}; use mm2_err_handle::prelude::*; -use std::collections::hash_map::Entry; -use std::collections::HashMap; -use std::sync::atomic::Ordering; -use std::sync::{Arc, Mutex, Weak}; + +use crate::task::RpcTaskTypes; +use crate::{AtomicTaskId, RpcTask, RpcTaskError, RpcTaskHandle, RpcTaskResult, RpcTaskStatus, RpcTaskStatusAlias, + TaskAbortHandle, TaskAbortHandler, TaskId, TaskStatus, TaskStatusError, UserActionSender}; macro_rules! unexpected_task_status { ($task_id:expr, actual = $actual:ident, expected = $expected:ident) => { diff --git a/mm2src/rpc_task/src/rpc_common.rs b/mm2src/rpc_task/src/rpc_common.rs index 6a43d51b49..1ed57a30c7 100644 --- a/mm2src/rpc_task/src/rpc_common.rs +++ b/mm2src/rpc_task/src/rpc_common.rs @@ -1,7 +1,8 @@ -use super::{RpcTaskError, TaskId}; use common::{true_f, HttpStatusCode, StatusCode}; use derive_more::Display; +use super::{RpcTaskError, TaskId}; + /// In most cases, the RPC task status request may fail with either [`RpcTaskStatusError::NoSuchTask`] or [`RpcTaskStatusError::Internal`]. /// Please do not add new error variants unless they are used in most cases. #[derive(Display, Serialize, SerializeErrorType)] diff --git a/mm2src/rpc_task/src/task.rs b/mm2src/rpc_task/src/task.rs index 860257515f..7e1d369882 100644 --- a/mm2src/rpc_task/src/task.rs +++ b/mm2src/rpc_task/src/task.rs @@ -1,8 +1,9 @@ -use crate::handle::RpcTaskHandle; use async_trait::async_trait; use mm2_err_handle::prelude::*; use serde::Serialize; +use crate::handle::RpcTaskHandle; + pub trait RpcTaskTypes { type Item: Serialize + Clone + Send + Sync + 'static; type Error: SerMmErrorType + Clone + Send + Sync + 'static; diff --git a/mm2src/trezor/src/client.rs b/mm2src/trezor/src/client.rs index 3e06023ad5..d04de978ba 100644 --- a/mm2src/trezor/src/client.rs +++ b/mm2src/trezor/src/client.rs @@ -1,5 +1,11 @@ //! This file is inspired by https://github.com/tezedge/tezedge-client/blob/master/trezor_api/src/client.rs +use std::sync::Arc; + +use common::now_ms; +use futures::lock::{Mutex as AsyncMutex, MutexGuard as AsyncMutexGuard}; +use mm2_err_handle::prelude::*; + use crate::device_info::TrezorDeviceInfo; use crate::error::OperationFailure; use crate::proto::messages::MessageType; @@ -10,10 +16,6 @@ use crate::response::TrezorResponse; use crate::result_handler::ResultHandler; use crate::transport::Transport; use crate::{TrezorError, TrezorResult}; -use common::now_ms; -use futures::lock::{Mutex as AsyncMutex, MutexGuard as AsyncMutexGuard}; -use mm2_err_handle::prelude::*; -use std::sync::Arc; #[derive(Clone)] pub struct TrezorClient { diff --git a/mm2src/trezor/src/error.rs b/mm2src/trezor/src/error.rs index 60397e55a1..ca336a30dc 100644 --- a/mm2src/trezor/src/error.rs +++ b/mm2src/trezor/src/error.rs @@ -1,10 +1,11 @@ -use crate::proto::messages::MessageType; -use crate::proto::messages_common::{failure::FailureType, Failure}; -use crate::user_interaction::TrezorUserInteraction; use derive_more::Display; use mm2_err_handle::prelude::*; use prost::{DecodeError, EncodeError}; +use crate::proto::messages::MessageType; +use crate::proto::messages_common::{failure::FailureType, Failure}; +use crate::user_interaction::TrezorUserInteraction; + pub type TrezorResult = Result>; #[cfg(all(not(target_arch = "wasm32"), not(target_os = "ios")))] diff --git a/mm2src/trezor/src/proto/mod.rs b/mm2src/trezor/src/proto/mod.rs index ab80efff8f..da93737cfd 100644 --- a/mm2src/trezor/src/proto/mod.rs +++ b/mm2src/trezor/src/proto/mod.rs @@ -8,11 +8,10 @@ pub mod messages_bitcoin; pub mod messages_common; pub mod messages_management; -/// This is needed by generated protobuf modules. -pub(crate) use messages_common as common; - use messages::MessageType; use messages_bitcoin::*; +/// This is needed by generated protobuf modules. +pub(crate) use messages_common as common; use messages_common::*; use messages_management::*; diff --git a/mm2src/trezor/src/response.rs b/mm2src/trezor/src/response.rs index 0fda4c1c16..5723d501be 100644 --- a/mm2src/trezor/src/response.rs +++ b/mm2src/trezor/src/response.rs @@ -1,15 +1,16 @@ -use crate::client::TrezorSession; -use crate::proto::messages_common as proto_common; -use crate::result_handler::ResultHandler; -use crate::user_interaction::TrezorUserInteraction; -use crate::{TrezorError, TrezorResult}; +use std::fmt; + use async_trait::async_trait; use mm2_err_handle::prelude::*; -use std::fmt; +use crate::client::TrezorSession; +use crate::proto::messages_common as proto_common; pub use crate::proto::messages_common::button_request::ButtonRequestType; pub use crate::proto::messages_common::pin_matrix_request::PinMatrixRequestType; use crate::response_processor::{ProcessTrezorResponse, TrezorProcessingError, TrezorRequestProcessor}; +use crate::result_handler::ResultHandler; +use crate::user_interaction::TrezorUserInteraction; +use crate::{TrezorError, TrezorResult}; /// The different types of user interactions the Trezor device can request. #[derive(PartialEq, Eq, Clone, Debug)] diff --git a/mm2src/trezor/src/response_processor.rs b/mm2src/trezor/src/response_processor.rs index 5ad235ad83..4325df50fa 100644 --- a/mm2src/trezor/src/response_processor.rs +++ b/mm2src/trezor/src/response_processor.rs @@ -1,9 +1,10 @@ -use crate::user_interaction::TrezorPassphraseResponse; -use crate::{TrezorError, TrezorPinMatrix3x3Response}; use async_trait::async_trait; use derive_more::Display; use mm2_err_handle::prelude::*; +use crate::user_interaction::TrezorPassphraseResponse; +use crate::{TrezorError, TrezorPinMatrix3x3Response}; + #[derive(Display)] pub enum TrezorProcessingError { TrezorError(TrezorError), diff --git a/mm2src/trezor/src/result_handler.rs b/mm2src/trezor/src/result_handler.rs index d23e9541b4..1aacd7be17 100644 --- a/mm2src/trezor/src/result_handler.rs +++ b/mm2src/trezor/src/result_handler.rs @@ -1,9 +1,10 @@ //! This file is inspired by https://github.com/tezedge/tezedge-client/blob/master/trezor_api/src/client.rs +use mm2_err_handle::prelude::*; + use crate::proto::messages::MessageType; use crate::proto::{ProtoMessage, TrezorMessage}; use crate::{TrezorError, TrezorResult}; -use mm2_err_handle::prelude::*; /// Function to be passed to the [`TrezorClient::call`] method /// to process the Trezor response message into a general-purpose type. diff --git a/mm2src/trezor/src/transport/mod.rs b/mm2src/trezor/src/transport/mod.rs index 985c4c871f..2c1e3d1e20 100644 --- a/mm2src/trezor/src/transport/mod.rs +++ b/mm2src/trezor/src/transport/mod.rs @@ -1,8 +1,9 @@ -use crate::proto::ProtoMessage; -use crate::TrezorResult; use async_trait::async_trait; use rand::RngCore; +use crate::proto::ProtoMessage; +use crate::TrezorResult; + mod protocol; #[cfg(all(not(target_arch = "wasm32"), not(target_os = "ios")))] pub mod usb; diff --git a/mm2src/trezor/src/transport/protocol.rs b/mm2src/trezor/src/transport/protocol.rs index 6c553e5d76..f441de0c4c 100644 --- a/mm2src/trezor/src/transport/protocol.rs +++ b/mm2src/trezor/src/transport/protocol.rs @@ -1,12 +1,13 @@ //! This file is inspired by https://github.com/tezedge/tezedge-client/blob/master/trezor_api/src/transport/protocol.rs -use crate::proto::messages::MessageType; -use crate::proto::ProtoMessage; -use crate::{TrezorError, TrezorResult}; use async_trait::async_trait; use byteorder::{BigEndian, ByteOrder}; use mm2_err_handle::prelude::*; +use crate::proto::messages::MessageType; +use crate::proto::ProtoMessage; +use crate::{TrezorError, TrezorResult}; + const CHUNK_LEN: u32 = 64; const CHUNK_HEADER_LEN: usize = 9; diff --git a/mm2src/trezor/src/transport/usb.rs b/mm2src/trezor/src/transport/usb.rs index 69440c9858..7de2bd79be 100644 --- a/mm2src/trezor/src/transport/usb.rs +++ b/mm2src/trezor/src/transport/usb.rs @@ -1,13 +1,14 @@ -use crate::proto::ProtoMessage; -use crate::transport::protocol::{Link, Protocol, ProtocolV1}; -use crate::transport::{Transport, TREZOR_DEVICES}; -use crate::TrezorResult; +use std::time::Duration; + use async_trait::async_trait; +pub use hw_common::transport::libusb::UsbDeviceInfo; use hw_common::transport::libusb::{GetDevicesFilters, UsbAvailableDevice as UsbAvailableDeviceImpl, UsbContext, UsbDevice}; -use std::time::Duration; -pub use hw_common::transport::libusb::UsbDeviceInfo; +use crate::proto::ProtoMessage; +use crate::transport::protocol::{Link, Protocol, ProtocolV1}; +use crate::transport::{Transport, TREZOR_DEVICES}; +use crate::TrezorResult; // TODO these timeouts should be optional and depend on the context of use. const READ_TIMEOUT: Duration = Duration::from_secs(600); diff --git a/mm2src/trezor/src/transport/webusb.rs b/mm2src/trezor/src/transport/webusb.rs index 6c438cea74..32eea04738 100644 --- a/mm2src/trezor/src/transport/webusb.rs +++ b/mm2src/trezor/src/transport/webusb.rs @@ -1,13 +1,13 @@ -use crate::proto::ProtoMessage; -use crate::transport::protocol::{Link, Protocol, ProtocolV1}; -use crate::transport::{Transport, TrezorDevice, TREZOR_DEVICES}; -use crate::{TrezorError, TrezorResult}; use async_trait::async_trait; use common::log::warn; +pub use hw_common::transport::webusb_driver::WebUsbDeviceInfo; use hw_common::transport::webusb_driver::{DeviceFilter, WebUsbDevice, WebUsbWrapper}; use mm2_err_handle::prelude::*; -pub use hw_common::transport::webusb_driver::WebUsbDeviceInfo; +use crate::proto::ProtoMessage; +use crate::transport::protocol::{Link, Protocol, ProtocolV1}; +use crate::transport::{Transport, TrezorDevice, TREZOR_DEVICES}; +use crate::{TrezorError, TrezorResult}; const T1HID_VENDOR: u16 = 0x534c; const CONFIGURATION_ID: u8 = 1; diff --git a/mm2src/trezor/src/trezor_rpc_task.rs b/mm2src/trezor/src/trezor_rpc_task.rs index a84c7dd4a1..059859bd74 100644 --- a/mm2src/trezor/src/trezor_rpc_task.rs +++ b/mm2src/trezor/src/trezor_rpc_task.rs @@ -1,13 +1,14 @@ -use crate::response_processor::{TrezorProcessingError, TrezorRequestProcessor}; -use crate::user_interaction::TrezorPassphraseResponse; -use crate::TrezorPinMatrix3x3Response; -use async_trait::async_trait; -use mm2_err_handle::prelude::*; use std::convert::TryInto; use std::time::Duration; +use async_trait::async_trait; +use mm2_err_handle::prelude::*; pub use rpc_task::{RpcTask, RpcTaskError, RpcTaskHandle}; +use crate::response_processor::{TrezorProcessingError, TrezorRequestProcessor}; +use crate::user_interaction::TrezorPassphraseResponse; +use crate::TrezorPinMatrix3x3Response; + const DEFAULT_USER_ACTION_TIMEOUT: Duration = Duration::from_secs(300); pub trait TryIntoUserAction: diff --git a/mm2src/trezor/src/utxo/prev_tx.rs b/mm2src/trezor/src/utxo/prev_tx.rs index 74c0fe99bb..d41e4506e3 100644 --- a/mm2src/trezor/src/utxo/prev_tx.rs +++ b/mm2src/trezor/src/utxo/prev_tx.rs @@ -1,7 +1,8 @@ +use mm2_err_handle::prelude::*; + use crate::proto::messages_bitcoin as proto_bitcoin; use crate::utxo::{ScriptPubkey, Signature}; use crate::{TrezorError, TrezorResult}; -use mm2_err_handle::prelude::*; /// Missing fields: /// * decred_tree - only for Decred diff --git a/mm2src/trezor/src/utxo/sign_utxo.rs b/mm2src/trezor/src/utxo/sign_utxo.rs index 9c3a452b24..bd550f7e64 100644 --- a/mm2src/trezor/src/utxo/sign_utxo.rs +++ b/mm2src/trezor/src/utxo/sign_utxo.rs @@ -1,10 +1,11 @@ +use common::log::{debug, info}; +use mm2_err_handle::prelude::*; + use crate::proto::messages_bitcoin as proto_bitcoin; use crate::result_handler::ResultHandler; use crate::utxo::unsigned_tx::UnsignedUtxoTx; use crate::utxo::Signature; use crate::{TrezorError, TrezorResponse, TrezorResult, TrezorSession}; -use common::log::{debug, info}; -use mm2_err_handle::prelude::*; const NO_DETAILS_ERROR: &str = "'TxRequest::details' is expected to be set"; const NO_REQUEST_INDEX_ERROR: &str = "'TxRequestDetailsType::request_index' is expected to be set"; diff --git a/mm2src/trezor/src/utxo/unsigned_tx.rs b/mm2src/trezor/src/utxo/unsigned_tx.rs index 2573a3d2bc..b9a1b922c5 100644 --- a/mm2src/trezor/src/utxo/unsigned_tx.rs +++ b/mm2src/trezor/src/utxo/unsigned_tx.rs @@ -1,8 +1,9 @@ +use hw_common::primitives::DerivationPath; +use mm2_err_handle::prelude::*; + use crate::proto::messages_bitcoin as proto_bitcoin; use crate::utxo::prev_tx::PrevTx; use crate::{serialize_derivation_path, TrezorError, TrezorResult}; -use hw_common::primitives::DerivationPath; -use mm2_err_handle::prelude::*; /// https://github.com/trezor/trezor-common/blob/master/protob/messages-bitcoin.proto#L16 #[derive(Clone, Copy)] diff --git a/mm2src/trezor/src/utxo/utxo_command.rs b/mm2src/trezor/src/utxo/utxo_command.rs index f513e831e7..2530b830e5 100644 --- a/mm2src/trezor/src/utxo/utxo_command.rs +++ b/mm2src/trezor/src/utxo/utxo_command.rs @@ -1,8 +1,9 @@ +use hw_common::primitives::{DerivationPath, EcdsaCurve, XPub}; + use crate::client::TrezorSession; use crate::proto::messages_bitcoin as proto_bitcoin; use crate::result_handler::ResultHandler; use crate::{ecdsa_curve_to_string, serialize_derivation_path, TrezorResponse, TrezorResult}; -use hw_common::primitives::{DerivationPath, EcdsaCurve, XPub}; pub const IGNORE_XPUB_MAGIC: bool = true;