diff --git a/accounting/src/delta/combine.rs b/accounting/src/delta/combine.rs index 95ea834220..a3728075cc 100644 --- a/accounting/src/delta/combine.rs +++ b/accounting/src/delta/combine.rs @@ -13,9 +13,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -use common::primitives::{amount::SignedAmount, Amount}; +use common::primitives::{Amount, amount::SignedAmount}; -use crate::{error::Error, DataDelta}; +use crate::{DataDelta, error::Error}; /// Combine data with an element of `DeltaDataCollection`. /// An element can be either a Delta or a result of delta undo. @@ -66,7 +66,7 @@ pub mod test { use crate::DataDelta; use super::*; - use common::primitives::amount::{signed::SignedIntType, UnsignedIntType}; + use common::primitives::amount::{UnsignedIntType, signed::SignedIntType}; use rstest::rstest; diff --git a/accounting/src/delta/delta_amount_collection.rs b/accounting/src/delta/delta_amount_collection.rs index a3971ca029..c5c826bf7d 100644 --- a/accounting/src/delta/delta_amount_collection.rs +++ b/accounting/src/delta/delta_amount_collection.rs @@ -15,7 +15,7 @@ use std::{collections::BTreeMap, ops::Neg}; -use common::primitives::{amount::SignedAmount, Amount}; +use common::primitives::{Amount, amount::SignedAmount}; use serialization::{Decode, Encode}; diff --git a/accounting/src/delta/delta_data_collection/mod.rs b/accounting/src/delta/delta_data_collection/mod.rs index 0adbc4a7ae..f8b2d4f7b5 100644 --- a/accounting/src/delta/delta_data_collection/mod.rs +++ b/accounting/src/delta/delta_data_collection/mod.rs @@ -16,7 +16,7 @@ pub mod undo; use self::undo::*; -use std::collections::{btree_map::Entry, BTreeMap}; +use std::collections::{BTreeMap, btree_map::Entry}; use serialization::{Decode, Encode}; diff --git a/accounting/src/delta/tests.rs b/accounting/src/delta/tests.rs index 3497c22cbc..a292073643 100644 --- a/accounting/src/delta/tests.rs +++ b/accounting/src/delta/tests.rs @@ -13,7 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{combine_data_with_delta, DataDelta, DeltaDataCollection}; +use crate::{DataDelta, DeltaDataCollection, combine_data_with_delta}; use rstest::rstest; diff --git a/accounting/src/lib.rs b/accounting/src/lib.rs index caa72a0991..28733ff778 100644 --- a/accounting/src/lib.rs +++ b/accounting/src/lib.rs @@ -23,8 +23,8 @@ pub use crate::{ combine::{combine_amount_delta, combine_data_with_delta}, delta_amount_collection::DeltaAmountCollection, delta_data_collection::{ - undo::{DataDeltaUndo, DeltaDataUndoCollection}, DataDelta, DeltaDataCollection, GetDataResult, + undo::{DataDeltaUndo, DeltaDataUndoCollection}, }, }, error::Error, diff --git a/api-server/api-server-common/src/storage/impls/in_memory/mod.rs b/api-server/api-server-common/src/storage/impls/in_memory/mod.rs index 859e0bfaff..8ae2770e46 100644 --- a/api-server/api-server-common/src/storage/impls/in_memory/mod.rs +++ b/api-server/api-server-common/src/storage/impls/in_memory/mod.rs @@ -27,19 +27,19 @@ use itertools::Itertools as _; use common::{ address::Address, chain::{ - block::timestamp::BlockTimestamp, - tokens::{NftIssuance, TokenId}, Block, ChainConfig, DelegationId, Destination, Genesis, OrderId, PoolId, Transaction, UtxoOutPoint, + block::timestamp::BlockTimestamp, + tokens::{NftIssuance, TokenId}, }, - primitives::{id::WithId, Amount, BlockHeight, CoinOrTokenId, Id, Idable}, + primitives::{Amount, BlockHeight, CoinOrTokenId, Id, Idable, id::WithId}, }; use crate::storage::storage_api::{ - block_aux_data::{BlockAuxData, BlockWithExtraData}, AmountWithDecimals, ApiServerStorageError, BlockInfo, CoinOrTokenStatistic, Delegation, FungibleTokenData, LockedUtxo, NftWithOwner, Order, PoolBlockStats, PoolDataWithExtraInfo, TokenTransaction, TransactionInfo, TransactionWithBlockInfo, Utxo, UtxoLock, UtxoWithExtraInfo, + block_aux_data::{BlockAuxData, BlockWithExtraData}, }; use super::CURRENT_STORAGE_VERSION; diff --git a/api-server/api-server-common/src/storage/impls/in_memory/transactional/read.rs b/api-server/api-server-common/src/storage/impls/in_memory/transactional/read.rs index 4032a5525f..546f7e1951 100644 --- a/api-server/api-server-common/src/storage/impls/in_memory/transactional/read.rs +++ b/api-server/api-server-common/src/storage/impls/in_memory/transactional/read.rs @@ -17,17 +17,17 @@ use std::collections::BTreeMap; use common::{ chain::{ - block::timestamp::BlockTimestamp, tokens::TokenId, Block, DelegationId, Destination, - OrderId, PoolId, Transaction, UtxoOutPoint, + Block, DelegationId, Destination, OrderId, PoolId, Transaction, UtxoOutPoint, + block::timestamp::BlockTimestamp, tokens::TokenId, }, primitives::{Amount, BlockHeight, CoinOrTokenId, Id}, }; use crate::storage::storage_api::{ - block_aux_data::BlockAuxData, AmountWithDecimals, ApiServerStorageError, ApiServerStorageRead, - BlockInfo, CoinOrTokenStatistic, Delegation, FungibleTokenData, NftWithOwner, Order, - PoolBlockStats, PoolDataWithExtraInfo, TokenTransaction, TransactionInfo, - TransactionWithBlockInfo, Utxo, UtxoWithExtraInfo, + AmountWithDecimals, ApiServerStorageError, ApiServerStorageRead, BlockInfo, + CoinOrTokenStatistic, Delegation, FungibleTokenData, NftWithOwner, Order, PoolBlockStats, + PoolDataWithExtraInfo, TokenTransaction, TransactionInfo, TransactionWithBlockInfo, Utxo, + UtxoWithExtraInfo, block_aux_data::BlockAuxData, }; use super::ApiServerInMemoryStorageTransactionalRo; diff --git a/api-server/api-server-common/src/storage/impls/in_memory/transactional/write.rs b/api-server/api-server-common/src/storage/impls/in_memory/transactional/write.rs index 7f7fbff4ea..5039ae013d 100644 --- a/api-server/api-server-common/src/storage/impls/in_memory/transactional/write.rs +++ b/api-server/api-server-common/src/storage/impls/in_memory/transactional/write.rs @@ -16,18 +16,18 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::storage::storage_api::{ - block_aux_data::{BlockAuxData, BlockWithExtraData}, AmountWithDecimals, ApiServerStorageError, ApiServerStorageRead, ApiServerStorageWrite, BlockInfo, CoinOrTokenStatistic, Delegation, FungibleTokenData, LockedUtxo, NftWithOwner, Order, PoolBlockStats, PoolDataWithExtraInfo, TokenTransaction, TransactionInfo, TransactionWithBlockInfo, Utxo, UtxoWithExtraInfo, + block_aux_data::{BlockAuxData, BlockWithExtraData}, }; use common::{ address::Address, chain::{ + Block, ChainConfig, DelegationId, Destination, OrderId, PoolId, Transaction, UtxoOutPoint, block::timestamp::BlockTimestamp, tokens::{NftIssuance, TokenId}, - Block, ChainConfig, DelegationId, Destination, OrderId, PoolId, Transaction, UtxoOutPoint, }, primitives::{Amount, BlockHeight, CoinOrTokenId, Id}, }; diff --git a/api-server/api-server-common/src/storage/impls/postgres/mod.rs b/api-server/api-server-common/src/storage/impls/postgres/mod.rs index 56278baada..a8cb06bd8f 100644 --- a/api-server/api-server-common/src/storage/impls/postgres/mod.rs +++ b/api-server/api-server-common/src/storage/impls/postgres/mod.rs @@ -20,9 +20,9 @@ mod queries; use std::str::FromStr; use std::sync::Arc; +use bb8_postgres::PostgresConnectionManager; use bb8_postgres::bb8::Pool; use bb8_postgres::bb8::PooledConnection; -use bb8_postgres::PostgresConnectionManager; use common::chain::ChainConfig; use tokio_postgres::NoTls; diff --git a/api-server/api-server-common/src/storage/impls/postgres/queries.rs b/api-server/api-server-common/src/storage/impls/postgres/queries.rs index 46403358c6..1247279429 100644 --- a/api-server/api-server-common/src/storage/impls/postgres/queries.rs +++ b/api-server/api-server-common/src/storage/impls/postgres/queries.rs @@ -18,16 +18,16 @@ use std::{ str::FromStr, }; -use bb8_postgres::{bb8::PooledConnection, PostgresConnectionManager}; +use bb8_postgres::{PostgresConnectionManager, bb8::PooledConnection}; use serialization::{DecodeAll, Encode}; use common::{ address::Address, chain::{ - block::timestamp::BlockTimestamp, - tokens::{NftIssuance, TokenId}, AccountNonce, Block, ChainConfig, DelegationId, Destination, GenBlock, OrderId, PoolId, Transaction, UtxoOutPoint, + block::timestamp::BlockTimestamp, + tokens::{NftIssuance, TokenId}, }, primitives::{Amount, BlockHeight, CoinOrTokenId, Id}, }; @@ -36,10 +36,10 @@ use tokio_postgres::NoTls; use crate::storage::{ impls::CURRENT_STORAGE_VERSION, storage_api::{ - block_aux_data::{BlockAuxData, BlockWithExtraData}, AmountWithDecimals, ApiServerStorageError, BlockInfo, CoinOrTokenStatistic, Delegation, FungibleTokenData, LockedUtxo, NftWithOwner, Order, PoolBlockStats, PoolDataWithExtraInfo, TokenTransaction, TransactionInfo, TransactionWithBlockInfo, Utxo, UtxoWithExtraInfo, + block_aux_data::{BlockAuxData, BlockWithExtraData}, }, }; diff --git a/api-server/api-server-common/src/storage/impls/postgres/transactional/mod.rs b/api-server/api-server-common/src/storage/impls/postgres/transactional/mod.rs index acde72fac8..9eac582f35 100644 --- a/api-server/api-server-common/src/storage/impls/postgres/transactional/mod.rs +++ b/api-server/api-server-common/src/storage/impls/postgres/transactional/mod.rs @@ -18,7 +18,7 @@ pub mod write; use std::sync::Arc; -use bb8_postgres::{bb8::PooledConnection, PostgresConnectionManager}; +use bb8_postgres::{PostgresConnectionManager, bb8::PooledConnection}; use common::{ chain::{Block, ChainConfig, PoolId, Transaction}, primitives::{BlockHeight, Id}, @@ -26,11 +26,11 @@ use common::{ use tokio_postgres::NoTls; use crate::storage::storage_api::{ - block_aux_data::BlockAuxData, ApiServerStorage, ApiServerStorageError, ApiServerTransactionRo, - ApiServerTransactionRw, BlockInfo, PoolDataWithExtraInfo, TransactionInfo, Transactional, + ApiServerStorage, ApiServerStorageError, ApiServerTransactionRo, ApiServerTransactionRw, + BlockInfo, PoolDataWithExtraInfo, TransactionInfo, Transactional, block_aux_data::BlockAuxData, }; -use super::{queries::QueryFromConnection, TransactionalApiServerPostgresStorage}; +use super::{TransactionalApiServerPostgresStorage, queries::QueryFromConnection}; const CONN_ERR: &str = "CRITICAL: failed to get postgres tx connection. Invariant broken."; diff --git a/api-server/api-server-common/src/storage/impls/postgres/transactional/read.rs b/api-server/api-server-common/src/storage/impls/postgres/transactional/read.rs index d011899639..71000c7390 100644 --- a/api-server/api-server-common/src/storage/impls/postgres/transactional/read.rs +++ b/api-server/api-server-common/src/storage/impls/postgres/transactional/read.rs @@ -15,8 +15,8 @@ use common::{ chain::{ - block::timestamp::BlockTimestamp, tokens::TokenId, DelegationId, Destination, OrderId, - PoolId, + DelegationId, Destination, OrderId, PoolId, block::timestamp::BlockTimestamp, + tokens::TokenId, }, primitives::{Amount, BlockHeight, CoinOrTokenId, Id}, }; @@ -24,10 +24,10 @@ use common::{ use crate::storage::{ impls::postgres::queries::QueryFromConnection, storage_api::{ - block_aux_data::BlockAuxData, AmountWithDecimals, ApiServerStorageError, - ApiServerStorageRead, BlockInfo, CoinOrTokenStatistic, Delegation, FungibleTokenData, - NftWithOwner, Order, PoolBlockStats, PoolDataWithExtraInfo, TokenTransaction, - TransactionInfo, TransactionWithBlockInfo, Utxo, UtxoWithExtraInfo, + AmountWithDecimals, ApiServerStorageError, ApiServerStorageRead, BlockInfo, + CoinOrTokenStatistic, Delegation, FungibleTokenData, NftWithOwner, Order, PoolBlockStats, + PoolDataWithExtraInfo, TokenTransaction, TransactionInfo, TransactionWithBlockInfo, Utxo, + UtxoWithExtraInfo, block_aux_data::BlockAuxData, }, }; use std::collections::BTreeMap; diff --git a/api-server/api-server-common/src/storage/impls/postgres/transactional/write.rs b/api-server/api-server-common/src/storage/impls/postgres/transactional/write.rs index bfca788fc4..6429c5c208 100644 --- a/api-server/api-server-common/src/storage/impls/postgres/transactional/write.rs +++ b/api-server/api-server-common/src/storage/impls/postgres/transactional/write.rs @@ -18,9 +18,9 @@ use std::collections::{BTreeMap, BTreeSet}; use common::{ address::Address, chain::{ + Block, ChainConfig, DelegationId, Destination, OrderId, PoolId, Transaction, UtxoOutPoint, block::timestamp::BlockTimestamp, tokens::{NftIssuance, TokenId}, - Block, ChainConfig, DelegationId, Destination, OrderId, PoolId, Transaction, UtxoOutPoint, }, primitives::{Amount, BlockHeight, CoinOrTokenId, Id}, }; @@ -28,11 +28,11 @@ use common::{ use crate::storage::{ impls::postgres::queries::QueryFromConnection, storage_api::{ - block_aux_data::{BlockAuxData, BlockWithExtraData}, AmountWithDecimals, ApiServerStorageError, ApiServerStorageRead, ApiServerStorageWrite, BlockInfo, CoinOrTokenStatistic, Delegation, FungibleTokenData, LockedUtxo, NftWithOwner, Order, PoolBlockStats, PoolDataWithExtraInfo, TokenTransaction, TransactionInfo, TransactionWithBlockInfo, Utxo, UtxoWithExtraInfo, + block_aux_data::{BlockAuxData, BlockWithExtraData}, }, }; diff --git a/api-server/api-server-common/src/storage/storage_api/block_aux_data.rs b/api-server/api-server-common/src/storage/storage_api/block_aux_data.rs index 992258fa66..f79ff688d4 100644 --- a/api-server/api-server-common/src/storage/storage_api/block_aux_data.rs +++ b/api-server/api-server-common/src/storage/storage_api/block_aux_data.rs @@ -14,7 +14,7 @@ // limitations under the License. use common::{ - chain::{block::timestamp::BlockTimestamp, Block, GenBlock}, + chain::{Block, GenBlock, block::timestamp::BlockTimestamp}, primitives::{BlockHeight, Id}, }; use serialization::{Decode, Encode}; diff --git a/api-server/api-server-common/src/storage/storage_api/mod.rs b/api-server/api-server-common/src/storage/storage_api/mod.rs index fe4fdd895d..54c409e7fe 100644 --- a/api-server/api-server-common/src/storage/storage_api/mod.rs +++ b/api-server/api-server-common/src/storage/storage_api/mod.rs @@ -22,16 +22,16 @@ use std::{ use common::{ address::Address, chain::{ + AccountNonce, Block, ChainConfig, DelegationId, Destination, IdCreationError, OrderId, + PoolId, SignedTransaction, Transaction, TxOutput, UtxoOutPoint, block::timestamp::BlockTimestamp, timelock::OutputTimeLock, tokens::{ IsTokenFreezable, IsTokenFrozen, IsTokenUnfreezable, NftIssuance, RPCFungibleTokenInfo, TokenId, TokenTotalSupply, }, - AccountNonce, Block, ChainConfig, DelegationId, Destination, IdCreationError, OrderId, - PoolId, SignedTransaction, Transaction, TxOutput, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight, CoinOrTokenId, Id}, + primitives::{Amount, BlockHeight, CoinOrTokenId, Id, per_thousand::PerThousand}, }; use crypto::vrf::VRFPublicKey; use pos_accounting::{Error as PosError, PoolData}; @@ -94,7 +94,7 @@ impl FromStr for CoinOrTokenStatistic { _ => { return Err(ApiServerStorageError::DeserializationError(format!( "invalid coin or token statistic type: {s}" - ))) + ))); } }; @@ -716,10 +716,10 @@ pub trait ApiServerStorageRead: Sync { ) -> Result, ApiServerStorageError>; async fn get_last_transaction_global_index(&self) - -> Result, ApiServerStorageError>; + -> Result, ApiServerStorageError>; async fn get_utxo(&self, outpoint: UtxoOutPoint) - -> Result, ApiServerStorageError>; + -> Result, ApiServerStorageError>; async fn get_address_available_utxos( &self, diff --git a/api-server/scanner-daemon/src/main.rs b/api-server/scanner-daemon/src/main.rs index 4107d9b4b8..fbec4a3372 100644 --- a/api-server/scanner-daemon/src/main.rs +++ b/api-server/scanner-daemon/src/main.rs @@ -17,14 +17,14 @@ use std::sync::Arc; use api_blockchain_scanner_lib::blockchain_state::BlockchainState; use api_server_common::storage::{ - impls::{postgres::TransactionalApiServerPostgresStorage, CURRENT_STORAGE_VERSION}, + impls::{CURRENT_STORAGE_VERSION, postgres::TransactionalApiServerPostgresStorage}, storage_api::{ ApiServerStorage, ApiServerStorageError, ApiServerStorageRead, ApiServerStorageWrite, ApiServerTransactionRw, }, }; use clap::Parser; -use common::chain::{config::ChainType, ChainConfig}; +use common::chain::{ChainConfig, config::ChainType}; use config::ApiServerScannerArgs; use node_comm::{make_rpc_client, rpc_client::NodeRpcClient}; use rpc::RpcAuthData; @@ -174,7 +174,7 @@ async fn main() -> Result<(), ApiServerScannerError> { _ => { return Err(ApiServerScannerError::InvalidConfig( "Invalid RPC cookie/username/password combination".to_owned(), - )) + )); } }; diff --git a/api-server/scanner-lib/src/blockchain_state/mod.rs b/api-server/scanner-lib/src/blockchain_state/mod.rs index 0fc2873d15..c5146296a3 100644 --- a/api-server/scanner-lib/src/blockchain_state/mod.rs +++ b/api-server/scanner-lib/src/blockchain_state/mod.rs @@ -19,13 +19,13 @@ use std::{ sync::Arc, }; -use futures::{stream::FuturesOrdered, TryStreamExt}; +use futures::{TryStreamExt, stream::FuturesOrdered}; use api_server_common::storage::storage_api::{ - block_aux_data::{BlockAuxData, BlockWithExtraData}, ApiServerStorage, ApiServerStorageError, ApiServerStorageRead, ApiServerStorageWrite, ApiServerTransactionRw, CoinOrTokenStatistic, Delegation, FungibleTokenData, LockedUtxo, Order, PoolDataWithExtraInfo, TransactionInfo, TxAdditionalInfo, Utxo, UtxoLock, + block_aux_data::{BlockAuxData, BlockWithExtraData}, }; use chainstate::{ calculate_median_time_past_from_blocktimestamps, @@ -34,21 +34,21 @@ use chainstate::{ use common::{ address::Address, chain::{ - block::{timestamp::BlockTimestamp, ConsensusData}, + AccountCommand, AccountNonce, AccountSpending, Block, DelegationId, Destination, GenBlock, + Genesis, OrderAccountCommand, OrderId, PoolId, SignedTransaction, Transaction, TxInput, + TxOutput, UtxoOutPoint, + block::{ConsensusData, timestamp::BlockTimestamp}, config::ChainConfig, make_delegation_id, make_order_id, make_token_id, output_value::OutputValue, signature::inputsig::{ - authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, InputWitness, + authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, }, - tokens::{get_referenced_token_ids_ignore_issuance, IsTokenFrozen, TokenId, TokenIssuance}, + tokens::{IsTokenFrozen, TokenId, TokenIssuance, get_referenced_token_ids_ignore_issuance}, transaction::OutPointSourceId, - AccountCommand, AccountNonce, AccountSpending, Block, DelegationId, Destination, GenBlock, - Genesis, OrderAccountCommand, OrderId, PoolId, SignedTransaction, Transaction, TxInput, - TxOutput, UtxoOutPoint, }, - primitives::{id::WithId, Amount, BlockHeight, CoinOrTokenId, Fee, Id, Idable, H256}, + primitives::{Amount, BlockHeight, CoinOrTokenId, Fee, H256, Id, Idable, id::WithId}, }; use orders_accounting::OrderData; use pos_accounting::{PoSAccountingView, PoolData}; diff --git a/api-server/scanner-lib/src/sync/tests/mod.rs b/api-server/scanner-lib/src/sync/tests/mod.rs index c61afebbe2..d8345f2463 100644 --- a/api-server/scanner-lib/src/sync/tests/mod.rs +++ b/api-server/scanner-lib/src/sync/tests/mod.rs @@ -37,19 +37,22 @@ use chainstate_test_framework::{TestFramework, TransactionBuilder}; use common::{ address::Address, chain::{ + AccountCommand, AccountNonce, CoinUnit, Destination, OrderAccountCommand, OrderData, + OrderId, OutPointSourceId, PoolId, SignedTransaction, Transaction, TxInput, TxOutput, + UtxoOutPoint, htlc::{HashedTimelockContract, HtlcSecret}, make_delegation_id, make_order_id, make_token_id, output_value::OutputValue, signature::inputsig::authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, signature::{ inputsig::{ - authorize_pubkey_spend::sign_public_key_spending, - standard_signature::StandardInputSignature, InputWitness, + InputWitness, authorize_pubkey_spend::sign_public_key_spending, + standard_signature::StandardInputSignature, }, sighash::{ input_commitments::{ - make_sighash_input_commitments_for_transaction_inputs_at_height, OrderInfo, - PoolInfo, SighashInputCommitment, TrivialUtxoProvider, + OrderInfo, PoolInfo, SighashInputCommitment, TrivialUtxoProvider, + make_sighash_input_commitments_for_transaction_inputs_at_height, }, sighashtype::SigHashType, signature_hash, @@ -58,11 +61,8 @@ use common::{ stakelock::StakePoolData, timelock::OutputTimeLock, tokens::{IsTokenUnfreezable, TokenIssuance}, - AccountCommand, AccountNonce, CoinUnit, Destination, OrderAccountCommand, OrderData, - OrderId, OutPointSourceId, PoolId, SignedTransaction, Transaction, TxInput, TxOutput, - UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, CoinOrTokenId, Idable, H256}, + primitives::{Amount, CoinOrTokenId, H256, Idable, per_thousand::PerThousand}, }; use crypto::{ key::{KeyKind, PrivateKey}, @@ -70,9 +70,9 @@ use crypto::{ }; use logging::log; use mempool::FeeRate; -use randomness::{seq::IteratorRandom, CryptoRng, RngExt as _}; +use randomness::{CryptoRng, RngExt as _, seq::IteratorRandom}; use serialization::Encode; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use crate::blockchain_state::BlockchainState; @@ -1428,7 +1428,9 @@ async fn token_transactions_storage_check(#[case] seed: Seed) { ); let tx_authority_id = tx_authority.transaction().get_id(); - eprintln!("{tx_mint_id:?}, {tx_freeze_id:?}, {tx_unfreeze_id:?}, {tx_metadata_id:?}, {tx_authority_id}"); + eprintln!( + "{tx_mint_id:?}, {tx_freeze_id:?}, {tx_unfreeze_id:?}, {tx_metadata_id:?}, {tx_authority_id}" + ); // Process Block 3 with all management commands tf.progress_time_seconds_since_epoch(target_block_time.as_secs()); let best_block_id = tf.best_block_id(); diff --git a/api-server/scanner-lib/src/sync/tests/simulation.rs b/api-server/scanner-lib/src/sync/tests/simulation.rs index a920031304..4e971052e7 100644 --- a/api-server/scanner-lib/src/sync/tests/simulation.rs +++ b/api-server/scanner-lib/src/sync/tests/simulation.rs @@ -29,21 +29,21 @@ use api_server_common::storage::{ }, }; -use chainstate::{chainstate_interface::ChainstateInterface, BlockSource, ChainstateConfig}; +use chainstate::{BlockSource, ChainstateConfig, chainstate_interface::ChainstateInterface}; use chainstate_test_framework::TestFramework; use common::{ chain::{ + AccountCommand, AccountNonce, AccountSpending, AccountType, ChainConfig, + ChainstateUpgradeBuilder, ConsensusUpgrade, DelegationId, Destination, GenBlockId, + NetUpgrades, OrderId, OutPointSourceId, PoSChainConfigBuilder, PoolId, + TokenIdGenerationVersion, Transaction, TxInput, TxOutput, UtxoOutPoint, block::timestamp::BlockTimestamp, config::create_unit_test_config, make_delegation_id, make_order_id, make_token_id, output_value::{OutputValue, RpcOutputValue}, tokens::{IsTokenFrozen, NftIssuance, RPCNonFungibleTokenMetadata, RPCTokenInfo, TokenId}, - AccountCommand, AccountNonce, AccountSpending, AccountType, ChainConfig, - ChainstateUpgradeBuilder, ConsensusUpgrade, DelegationId, Destination, GenBlockId, - NetUpgrades, OrderId, OutPointSourceId, PoSChainConfigBuilder, PoolId, - TokenIdGenerationVersion, Transaction, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{Amount, BlockCount, BlockHeight, CoinOrTokenId, Idable, H256}, + primitives::{Amount, BlockCount, BlockHeight, CoinOrTokenId, H256, Idable}, }; use constraints_value_accumulator::{AccumulatedFee, ConstrainedValueAccumulator}; use crypto::{ @@ -54,7 +54,7 @@ use orders_accounting::{OrderData, OrdersAccountingOperations, OrdersAccountingV use pos_accounting::PoSAccountingView; use randomness::RngExt as _; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use tokens_accounting::TokensAccountingView; struct PoSAccountingAdapterToCheckFees<'a> { diff --git a/api-server/stack-test-suite/tests/in_memory.rs b/api-server/stack-test-suite/tests/in_memory.rs index 814daf0658..a6bdb6d73e 100644 --- a/api-server/stack-test-suite/tests/in_memory.rs +++ b/api-server/stack-test-suite/tests/in_memory.rs @@ -16,9 +16,9 @@ mod v2; use api_server_common::storage::impls::in_memory::transactional::TransactionalApiServerInMemoryStorage; -use api_web_server::{api::web_server, ApiServerWebServerState, CachedValues, TxSubmitClient}; +use api_web_server::{ApiServerWebServerState, CachedValues, TxSubmitClient, api::web_server}; use common::{ - chain::{config::create_unit_test_config, SignedTransaction}, + chain::{SignedTransaction, config::create_unit_test_config}, primitives::time::get_time, }; use mempool::FeeRate; diff --git a/api-server/stack-test-suite/tests/v2/address.rs b/api-server/stack-test-suite/tests/v2/address.rs index 941c13ae5b..c2bb4c2531 100644 --- a/api-server/stack-test-suite/tests/v2/address.rs +++ b/api-server/stack-test-suite/tests/v2/address.rs @@ -15,7 +15,7 @@ use std::{borrow::Cow, sync::RwLock}; -use api_web_server::{api::json_helpers::amount_to_json, CachedValues}; +use api_web_server::{CachedValues, api::json_helpers::amount_to_json}; use common::primitives::time::get_time; use crate::DummyRPC; @@ -133,13 +133,14 @@ async fn multiple_outputs_to_single_address(#[case] seed: Seed) { .unwrap(), ); - let mut chainstate_block_ids = vec![*tf - .make_block_builder() - .add_transaction(transaction.clone()) - .build_and_process(&mut rng) - .unwrap() - .unwrap() - .block_id()]; + let mut chainstate_block_ids = vec![ + *tf.make_block_builder() + .add_transaction(transaction.clone()) + .build_and_process(&mut rng) + .unwrap() + .unwrap() + .block_id(), + ]; // Generate two outputs for a single transaction @@ -375,13 +376,14 @@ async fn test_unlocking_for_locked_utxos(#[case] seed: Seed) { .unwrap(), ); - let mut chainstate_block_ids = vec![*tf - .make_block_builder() - .add_transaction(transaction.clone()) - .build_and_process(&mut rng) - .unwrap() - .unwrap() - .block_id()]; + let mut chainstate_block_ids = vec![ + *tf.make_block_builder() + .add_transaction(transaction.clone()) + .build_and_process(&mut rng) + .unwrap() + .unwrap() + .block_id(), + ]; // Generate two outputs for a single transaction @@ -625,13 +627,14 @@ async fn ok(#[case] seed: Seed) { .unwrap(), ); - let mut chainstate_block_ids = vec![*tf - .make_block_builder() - .add_transaction(transaction.clone()) - .build_and_process(&mut rng) - .unwrap() - .unwrap() - .block_id()]; + let mut chainstate_block_ids = vec![ + *tf.make_block_builder() + .add_transaction(transaction.clone()) + .build_and_process(&mut rng) + .unwrap() + .unwrap() + .block_id(), + ]; for _ in 0..rng.random_range(1..100) { let random_coin_amount = rng.random_range(1..10); diff --git a/api-server/stack-test-suite/tests/v2/address_all_utxos.rs b/api-server/stack-test-suite/tests/v2/address_all_utxos.rs index e4416ad95e..8f7f2fc1bc 100644 --- a/api-server/stack-test-suite/tests/v2/address_all_utxos.rs +++ b/api-server/stack-test-suite/tests/v2/address_all_utxos.rs @@ -15,7 +15,7 @@ use std::{borrow::Cow, collections::BTreeMap, sync::RwLock}; -use api_web_server::{api::json_helpers::utxo_outpoint_to_json, CachedValues}; +use api_web_server::{CachedValues, api::json_helpers::utxo_outpoint_to_json}; use common::{chain::UtxoOutPoint, primitives::time::get_time}; use crate::DummyRPC; @@ -132,13 +132,14 @@ async fn multiple_utxos_to_single_address(#[case] seed: Seed) { .unwrap(), ); - let mut chainstate_block_ids = vec![*tf - .make_block_builder() - .add_transaction(transaction.clone()) - .build_and_process(&mut rng) - .unwrap() - .unwrap() - .block_id()]; + let mut chainstate_block_ids = vec![ + *tf.make_block_builder() + .add_transaction(transaction.clone()) + .build_and_process(&mut rng) + .unwrap() + .unwrap() + .block_id(), + ]; // Generate two outputs for a single transaction @@ -382,13 +383,14 @@ async fn ok(#[case] seed: Seed) { .unwrap(), ); - let mut chainstate_block_ids = vec![*tf - .make_block_builder() - .add_transaction(transaction.clone()) - .build_and_process(&mut rng) - .unwrap() - .unwrap() - .block_id()]; + let mut chainstate_block_ids = vec![ + *tf.make_block_builder() + .add_transaction(transaction.clone()) + .build_and_process(&mut rng) + .unwrap() + .unwrap() + .block_id(), + ]; for _ in 0..rng.random_range(1..2) { let random_coin_amount = rng.random_range(1..10); diff --git a/api-server/stack-test-suite/tests/v2/address_delegations.rs b/api-server/stack-test-suite/tests/v2/address_delegations.rs index 64d0e20d39..4400334f0b 100644 --- a/api-server/stack-test-suite/tests/v2/address_delegations.rs +++ b/api-server/stack-test-suite/tests/v2/address_delegations.rs @@ -15,7 +15,7 @@ use std::sync::RwLock; -use api_web_server::{api::json_helpers::amount_to_json, CachedValues}; +use api_web_server::{CachedValues, api::json_helpers::amount_to_json}; use common::{ chain::{AccountNonce, UtxoOutPoint}, primitives::time::get_time, diff --git a/api-server/stack-test-suite/tests/v2/address_spendable_utxos.rs b/api-server/stack-test-suite/tests/v2/address_spendable_utxos.rs index 70c08324b1..1b571bf4b9 100644 --- a/api-server/stack-test-suite/tests/v2/address_spendable_utxos.rs +++ b/api-server/stack-test-suite/tests/v2/address_spendable_utxos.rs @@ -15,7 +15,7 @@ use std::{borrow::Cow, collections::BTreeMap, sync::RwLock}; -use api_web_server::{api::json_helpers::utxo_outpoint_to_json, CachedValues}; +use api_web_server::{CachedValues, api::json_helpers::utxo_outpoint_to_json}; use common::{chain::UtxoOutPoint, primitives::time::get_time}; use crate::DummyRPC; @@ -135,13 +135,14 @@ async fn multiple_utxos_to_single_address(#[case] seed: Seed) { .unwrap(), ); - let mut chainstate_block_ids = vec![*tf - .make_block_builder() - .add_transaction(transaction.clone()) - .build_and_process(&mut rng) - .unwrap() - .unwrap() - .block_id()]; + let mut chainstate_block_ids = vec![ + *tf.make_block_builder() + .add_transaction(transaction.clone()) + .build_and_process(&mut rng) + .unwrap() + .unwrap() + .block_id(), + ]; // Generate two outputs for a single transaction @@ -384,13 +385,14 @@ async fn ok(#[case] seed: Seed) { .unwrap(), ); - let mut chainstate_block_ids = vec![*tf - .make_block_builder() - .add_transaction(transaction.clone()) - .build_and_process(&mut rng) - .unwrap() - .unwrap() - .block_id()]; + let mut chainstate_block_ids = vec![ + *tf.make_block_builder() + .add_transaction(transaction.clone()) + .build_and_process(&mut rng) + .unwrap() + .unwrap() + .block_id(), + ]; for _ in 0..rng.random_range(1..100) { let random_coin_amount = rng.random_range(1..10); diff --git a/api-server/stack-test-suite/tests/v2/address_token_authority.rs b/api-server/stack-test-suite/tests/v2/address_token_authority.rs index 421c1bce56..5779997bbc 100644 --- a/api-server/stack-test-suite/tests/v2/address_token_authority.rs +++ b/api-server/stack-test-suite/tests/v2/address_token_authority.rs @@ -16,9 +16,8 @@ use std::borrow::Cow; use common::chain::{ - make_token_id, + AccountNonce, make_token_id, tokens::{IsTokenFreezable, TokenIssuance, TokenIssuanceV1, TokenTotalSupply}, - AccountNonce, }; use crate::DummyRPC; diff --git a/api-server/stack-test-suite/tests/v2/block.rs b/api-server/stack-test-suite/tests/v2/block.rs index c842318fa5..8c8f4bf494 100644 --- a/api-server/stack-test-suite/tests/v2/block.rs +++ b/api-server/stack-test-suite/tests/v2/block.rs @@ -15,15 +15,15 @@ use api_server_common::storage::storage_api::{ApiServerStorageRead, TxAdditionalInfo}; use common::{ - chain::{stakelock::StakePoolData, CoinUnit, GenBlock, PoolId}, - primitives::{per_thousand::PerThousand, time::get_time, H256}, + chain::{CoinUnit, GenBlock, PoolId, stakelock::StakePoolData}, + primitives::{H256, per_thousand::PerThousand, time::get_time}, }; use crypto::vrf::{VRFKeyKind, VRFPrivateKey}; use std::{collections::BTreeMap, sync::RwLock}; use api_web_server::{ - api::json_helpers::{block_header_to_json, tx_to_json, txoutput_to_json}, CachedValues, + api::json_helpers::{block_header_to_json, tx_to_json, txoutput_to_json}, }; use crate::DummyRPC; diff --git a/api-server/stack-test-suite/tests/v2/block_header.rs b/api-server/stack-test-suite/tests/v2/block_header.rs index 347018b404..c537d2022a 100644 --- a/api-server/stack-test-suite/tests/v2/block_header.rs +++ b/api-server/stack-test-suite/tests/v2/block_header.rs @@ -13,10 +13,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -use api_web_server::{api::json_helpers::block_header_to_json, CachedValues}; +use api_web_server::{CachedValues, api::json_helpers::block_header_to_json}; use common::{ - chain::{stakelock::StakePoolData, CoinUnit, PoolId}, - primitives::{per_thousand::PerThousand, time::get_time, H256}, + chain::{CoinUnit, PoolId, stakelock::StakePoolData}, + primitives::{H256, per_thousand::PerThousand, time::get_time}, }; use crypto::vrf::{VRFKeyKind, VRFPrivateKey}; use std::sync::RwLock; diff --git a/api-server/stack-test-suite/tests/v2/block_reward.rs b/api-server/stack-test-suite/tests/v2/block_reward.rs index a554ca4045..0319988902 100644 --- a/api-server/stack-test-suite/tests/v2/block_reward.rs +++ b/api-server/stack-test-suite/tests/v2/block_reward.rs @@ -15,7 +15,7 @@ use std::sync::RwLock; -use api_web_server::{api::json_helpers::txoutput_to_json, CachedValues}; +use api_web_server::{CachedValues, api::json_helpers::txoutput_to_json}; use common::primitives::time::get_time; use crate::DummyRPC; diff --git a/api-server/stack-test-suite/tests/v2/helpers.rs b/api-server/stack-test-suite/tests/v2/helpers.rs index 5a994ba5aa..79bf949843 100644 --- a/api-server/stack-test-suite/tests/v2/helpers.rs +++ b/api-server/stack-test-suite/tests/v2/helpers.rs @@ -13,18 +13,17 @@ // See the License for the specific language governing permissions and // limitations under the License. -use chainstate_test_framework::{empty_witness, TestFramework, TransactionBuilder}; +use chainstate_test_framework::{TestFramework, TransactionBuilder, empty_witness}; use common::{ address::pubkeyhash::PublicKeyHash, chain::{ - make_delegation_id, make_token_id, + AccountCommand, AccountNonce, Block, DelegationId, Destination, OutPointSourceId, PoolId, + TxInput, TxOutput, UtxoOutPoint, make_delegation_id, make_token_id, output_value::OutputValue, stakelock::StakePoolData, tokens::{TokenId, TokenIssuance, TokenTotalSupply}, - AccountCommand, AccountNonce, Block, DelegationId, Destination, OutPointSourceId, PoolId, - TxInput, TxOutput, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight, Idable}, + primitives::{Amount, BlockHeight, Idable, per_thousand::PerThousand}, }; use crypto::{ key::{KeyKind, PrivateKey}, diff --git a/api-server/stack-test-suite/tests/v2/htlc.rs b/api-server/stack-test-suite/tests/v2/htlc.rs index 20978836d9..3fb71f6557 100644 --- a/api-server/stack-test-suite/tests/v2/htlc.rs +++ b/api-server/stack-test-suite/tests/v2/htlc.rs @@ -16,6 +16,7 @@ use std::borrow::Cow; use common::chain::{ + ChainConfig, classic_multisig::ClassicMultisigChallenge, htlc::HtlcSecret, htlc::{HashedTimelockContract, HtlcSecretHash}, @@ -29,7 +30,6 @@ use common::chain::{ }, sighash::signature_hash, }, - ChainConfig, }; use crypto::key::PublicKey; use serialization::Encode; diff --git a/api-server/stack-test-suite/tests/v2/mod.rs b/api-server/stack-test-suite/tests/v2/mod.rs index 5bc6671019..94cbb711d0 100644 --- a/api-server/stack-test-suite/tests/v2/mod.rs +++ b/api-server/stack-test-suite/tests/v2/mod.rs @@ -43,7 +43,7 @@ mod transaction_output; mod transaction_submit; mod transactions; -use crate::{spawn_webserver, DummyRPC}; +use crate::{DummyRPC, spawn_webserver}; use api_blockchain_scanner_lib::{ blockchain_state::BlockchainState, sync::local_state::LocalBlockchainState, }; @@ -52,27 +52,27 @@ use api_server_common::storage::{ storage_api::{ApiServerStorageWrite, ApiServerTransactionRw, Transactional}, }; use api_web_server::{ + ApiServerWebServerState, CachedValues, api::{ - json_helpers::{txoutput_to_json, TokenDecimals}, + json_helpers::{TokenDecimals, txoutput_to_json}, web_server, }, - ApiServerWebServerState, CachedValues, }; use chainstate::BlockSource; use chainstate_test_framework::{TestFramework, TransactionBuilder}; use common::{ - address::{pubkeyhash::PublicKeyHash, Address}, + address::{Address, pubkeyhash::PublicKeyHash}, chain::{ + Destination, OutPointSourceId, SignedTransaction, Transaction, TxInput, TxOutput, config::create_unit_test_config, output_value::OutputValue, signature::{ - inputsig::{standard_signature::StandardInputSignature, InputWitness}, + inputsig::{InputWitness, standard_signature::StandardInputSignature}, sighash::{input_commitments::SighashInputCommitment, sighashtype::SigHashType}, }, transaction::output::timelock::OutputTimeLock, - Destination, OutPointSourceId, SignedTransaction, Transaction, TxInput, TxOutput, }, - primitives::{time::get_time, Amount, BlockHeight, Id, Idable}, + primitives::{Amount, BlockHeight, Id, Idable, time::get_time}, }; use crypto::key::{KeyKind, PrivateKey}; use hex::ToHex; @@ -82,7 +82,7 @@ use std::{ collections::BTreeMap, sync::{Arc, RwLock}, }; -use test_utils::random::{make_seedable_rng, RngExt as _, Seed}; +use test_utils::random::{RngExt as _, Seed, make_seedable_rng}; #[ctor::ctor] fn init() { diff --git a/api-server/stack-test-suite/tests/v2/orders.rs b/api-server/stack-test-suite/tests/v2/orders.rs index 05e1df2a67..07aa083224 100644 --- a/api-server/stack-test-suite/tests/v2/orders.rs +++ b/api-server/stack-test-suite/tests/v2/orders.rs @@ -14,8 +14,8 @@ // limitations under the License. use common::chain::{ - make_order_id, AccountCommand, AccountNonce, ChainstateUpgradeBuilder, OrderAccountCommand, - OrderData, OrdersVersion, + AccountCommand, AccountNonce, ChainstateUpgradeBuilder, OrderAccountCommand, OrderData, + OrdersVersion, make_order_id, }; use super::*; diff --git a/api-server/stack-test-suite/tests/v2/pool_block_stats.rs b/api-server/stack-test-suite/tests/v2/pool_block_stats.rs index 9725595626..88564552ed 100644 --- a/api-server/stack-test-suite/tests/v2/pool_block_stats.rs +++ b/api-server/stack-test-suite/tests/v2/pool_block_stats.rs @@ -14,8 +14,8 @@ // limitations under the License. use common::{ - chain::{config::create_regtest, stakelock::StakePoolData, CoinUnit, PoolId}, - primitives::{per_thousand::PerThousand, H256}, + chain::{CoinUnit, PoolId, config::create_regtest, stakelock::StakePoolData}, + primitives::{H256, per_thousand::PerThousand}, }; use crypto::vrf::{VRFKeyKind, VRFPrivateKey}; diff --git a/api-server/stack-test-suite/tests/v2/statistics.rs b/api-server/stack-test-suite/tests/v2/statistics.rs index 8d96aeb268..8932ec3cc9 100644 --- a/api-server/stack-test-suite/tests/v2/statistics.rs +++ b/api-server/stack-test-suite/tests/v2/statistics.rs @@ -18,10 +18,10 @@ use std::borrow::Cow; use api_web_server::api::json_helpers::amount_to_json; use common::{ chain::{ + AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, UtxoOutPoint, config::emission_schedule::DEFAULT_INITIAL_MINT, make_token_id, tokens::{IsTokenFreezable, TokenId, TokenIssuance, TokenIssuanceV1, TokenTotalSupply}, - AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, UtxoOutPoint, }, primitives::H256, }; diff --git a/api-server/stack-test-suite/tests/v2/token.rs b/api-server/stack-test-suite/tests/v2/token.rs index 96b9222661..8cf4322685 100644 --- a/api-server/stack-test-suite/tests/v2/token.rs +++ b/api-server/stack-test-suite/tests/v2/token.rs @@ -17,12 +17,11 @@ use api_server_common::storage::storage_api::FungibleTokenData; use api_web_server::api::json_helpers::{amount_to_json, to_json_string}; use common::{ chain::{ - make_token_id, + AccountNonce, make_token_id, tokens::{ IsTokenFreezable, IsTokenFrozen, TokenId, TokenIssuance, TokenIssuanceV1, TokenTotalSupply, }, - AccountNonce, }, primitives::H256, }; diff --git a/api-server/stack-test-suite/tests/v2/token_transactions.rs b/api-server/stack-test-suite/tests/v2/token_transactions.rs index 1db3a2bdac..a6e4831208 100644 --- a/api-server/stack-test-suite/tests/v2/token_transactions.rs +++ b/api-server/stack-test-suite/tests/v2/token_transactions.rs @@ -17,11 +17,11 @@ use serde_json::Value; use chainstate_test_framework::empty_witness; use common::{ - chain::{tokens::TokenId, AccountCommand, AccountNonce, UtxoOutPoint}, + chain::{AccountCommand, AccountNonce, UtxoOutPoint, tokens::TokenId}, primitives::H256, }; -use crate::v2::helpers::{issue_and_mint_tokens_from_genesis, IssueAndMintTokensResult}; +use crate::v2::helpers::{IssueAndMintTokensResult, issue_and_mint_tokens_from_genesis}; use super::*; diff --git a/api-server/stack-test-suite/tests/v2/transaction.rs b/api-server/stack-test-suite/tests/v2/transaction.rs index 4f477cd0e6..d8467e6e9e 100644 --- a/api-server/stack-test-suite/tests/v2/transaction.rs +++ b/api-server/stack-test-suite/tests/v2/transaction.rs @@ -444,9 +444,8 @@ async fn ok(#[case] seed: Seed) { async fn mint_tokens(#[case] seed: Seed) { use chainstate_test_framework::empty_witness; use common::chain::{ - make_token_id, + AccountCommand, AccountNonce, UtxoOutPoint, make_token_id, tokens::{TokenIssuance, TokenTotalSupply}, - AccountCommand, AccountNonce, UtxoOutPoint, }; let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); diff --git a/api-server/stack-test-suite/tests/v2/transactions.rs b/api-server/stack-test-suite/tests/v2/transactions.rs index 621e444650..38d5767477 100644 --- a/api-server/stack-test-suite/tests/v2/transactions.rs +++ b/api-server/stack-test-suite/tests/v2/transactions.rs @@ -16,7 +16,7 @@ use serde_json::Value; use api_server_common::storage::storage_api::{ - block_aux_data::BlockAuxData, TransactionInfo, TxAdditionalInfo, + TransactionInfo, TxAdditionalInfo, block_aux_data::BlockAuxData, }; use api_web_server::api::json_helpers::to_tx_json_with_block_info; diff --git a/api-server/storage-test-suite/src/basic.rs b/api-server/storage-test-suite/src/basic.rs index 1d427430b0..664b813a8a 100644 --- a/api-server/storage-test-suite/src/basic.rs +++ b/api-server/storage-test-suite/src/basic.rs @@ -23,11 +23,11 @@ use pos_accounting::PoolData; use api_server_common::storage::{ impls::CURRENT_STORAGE_VERSION, storage_api::{ - block_aux_data::{BlockAuxData, BlockWithExtraData}, ApiServerStorage, ApiServerStorageError, ApiServerStorageRead, ApiServerStorageWrite, ApiServerTransactionRw, BlockInfo, CoinOrTokenStatistic, Delegation, FungibleTokenData, LockedUtxo, Order, PoolDataWithExtraInfo, TokenTransaction, TransactionInfo, Transactional, TxAdditionalInfo, Utxo, UtxoLock, UtxoWithExtraInfo, + block_aux_data::{BlockAuxData, BlockWithExtraData}, }, }; use crypto::{ @@ -36,26 +36,26 @@ use crypto::{ }; use randomness::{CryptoRng, RngExt as _}; -use chainstate_test_framework::{empty_witness, TestFramework, TransactionBuilder}; +use chainstate_test_framework::{TestFramework, TransactionBuilder, empty_witness}; use common::{ - address::{pubkeyhash::PublicKeyHash, Address}, + address::{Address, pubkeyhash::PublicKeyHash}, chain::{ + AccountNonce, Block, DelegationId, Destination, OrderId, OutPointSourceId, PoolId, + SignedTransaction, Transaction, TxInput, TxOutput, UtxoOutPoint, block::timestamp::BlockTimestamp, config::create_unit_test_config, output_value::OutputValue, tokens::{ IsTokenFreezable, IsTokenFrozen, NftIssuance, NftIssuanceV0, TokenId, TokenTotalSupply, }, - AccountNonce, Block, DelegationId, Destination, OrderId, OutPointSourceId, PoolId, - SignedTransaction, Transaction, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight, CoinOrTokenId, Id, Idable, H256}, + primitives::{Amount, BlockHeight, CoinOrTokenId, H256, Id, Idable, per_thousand::PerThousand}, }; use futures::Future; use libtest_mimic::Failed; use test_utils::{ assert_matches, - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, }; pub async fn initialization Fut>( @@ -1333,11 +1333,7 @@ where let id1 = DelegationId::random_using(&mut rng); let id2 = DelegationId::random_using(&mut rng); - if id1 < id2 { - (id1, id2) - } else { - (id2, id1) - } + if id1 < id2 { (id1, id2) } else { (id2, id1) } }; let random_block_height = BlockHeight::new(rng.random_range(500..1000) as u64); diff --git a/api-server/storage-test-suite/src/podman.rs b/api-server/storage-test-suite/src/podman.rs index 4600bfe875..e597d63f01 100644 --- a/api-server/storage-test-suite/src/podman.rs +++ b/api-server/storage-test-suite/src/podman.rs @@ -13,7 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use randomness::{make_pseudo_rng, RngExt as _}; +use randomness::{RngExt as _, make_pseudo_rng}; pub enum Container { PostgresFromDockerHub, diff --git a/api-server/storage-test-suite/tests/in_memory.rs b/api-server/storage-test-suite/tests/in_memory.rs index 203b40ff96..1c1307a4ec 100644 --- a/api-server/storage-test-suite/tests/in_memory.rs +++ b/api-server/storage-test-suite/tests/in_memory.rs @@ -19,7 +19,7 @@ use api_server_common::storage::{ impls::in_memory::transactional::TransactionalApiServerInMemoryStorage, storage_api::ApiServerStorage, }; -use common::chain::{config::create_unit_test_config, ChainConfig}; +use common::chain::{ChainConfig, config::create_unit_test_config}; #[must_use] #[allow(clippy::unused_async)] diff --git a/api-server/storage-test-suite/tests/postgres.rs b/api-server/storage-test-suite/tests/postgres.rs index 917eaad6f5..f13fdff370 100644 --- a/api-server/storage-test-suite/tests/postgres.rs +++ b/api-server/storage-test-suite/tests/postgres.rs @@ -21,7 +21,7 @@ use api_server_backend_test_suite::podman::{Container, Podman}; use api_server_common::storage::{ impls::postgres::TransactionalApiServerPostgresStorage, storage_api::ApiServerStorage, }; -use common::chain::{config::create_unit_test_config, ChainConfig}; +use common::chain::{ChainConfig, config::create_unit_test_config}; use containers::with_container::ApiServerStorageWithContainer; #[must_use] diff --git a/api-server/web-server/src/api/json_helpers.rs b/api-server/web-server/src/api/json_helpers.rs index 5c5f5fee46..12a5280903 100644 --- a/api-server/web-server/src/api/json_helpers.rs +++ b/api-server/web-server/src/api/json_helpers.rs @@ -16,23 +16,23 @@ use std::{collections::BTreeMap, ops::Sub}; use api_server_common::storage::storage_api::{ - block_aux_data::BlockAuxData, NftWithOwner, Order, TransactionInfo, TxAdditionalInfo, + NftWithOwner, Order, TransactionInfo, TxAdditionalInfo, block_aux_data::BlockAuxData, }; use common::{ + Uint256, address::Address, chain::{ + AccountCommand, AccountSpending, Block, ChainConfig, Destination, OrderAccountCommand, + OrderId, OutPointSourceId, PoolId, SignedTransaction, TxInput, TxOutput, UtxoOutPoint, block::ConsensusData, output_value::OutputValue, signature::inputsig::{ - authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, InputWitness, + authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, }, tokens::{IsTokenUnfreezable, NftIssuance, TokenId, TokenTotalSupply}, - AccountCommand, AccountSpending, Block, ChainConfig, Destination, OrderAccountCommand, - OrderId, OutPointSourceId, PoolId, SignedTransaction, TxInput, TxOutput, UtxoOutPoint, }, primitives::{Amount, BlockHeight, CoinOrTokenId, Idable}, - Uint256, }; use hex::ToHex; use serde_json::json; diff --git a/api-server/web-server/src/api/mod.rs b/api-server/web-server/src/api/mod.rs index ecc35d5349..348ef808f6 100644 --- a/api-server/web-server/src/api/mod.rs +++ b/api-server/web-server/src/api/mod.rs @@ -18,7 +18,7 @@ pub mod v2; use std::sync::Arc; -use axum::{http::Method, response::IntoResponse, routing::get, Json, Router}; +use axum::{Json, Router, http::Method, response::IntoResponse, routing::get}; use serde_json::json; use tokio::net::TcpListener; use tower_http::cors::{AllowMethods, Any, CorsLayer}; @@ -26,9 +26,8 @@ use tower_http::cors::{AllowMethods, Any, CorsLayer}; use api_server_common::storage::storage_api::ApiServerStorage; use crate::{ - api, + ApiServerWebServerState, TxSubmitClient, api, error::{ApiServerWebServerClientError, ApiServerWebServerError}, - ApiServerWebServerState, TxSubmitClient, }; #[allow(clippy::unused_async)] diff --git a/api-server/web-server/src/api/v2.rs b/api-server/web-server/src/api/v2.rs index a17d6b1fc8..e6e5c0f62f 100644 --- a/api-server/web-server/src/api/v2.rs +++ b/api-server/web-server/src/api/v2.rs @@ -14,35 +14,35 @@ // limitations under the License. use crate::{ + TxSubmitClient, api::json_helpers::{ - self, amount_to_json, block_header_to_json, pool_data_to_json, to_tx_json_with_block_info, - tx_to_json, txoutput_to_json, utxo_outpoint_to_json, TokenDecimals, + self, TokenDecimals, amount_to_json, block_header_to_json, pool_data_to_json, + to_tx_json_with_block_info, tx_to_json, txoutput_to_json, utxo_outpoint_to_json, }, error::{ ApiServerWebServerClientError, ApiServerWebServerError, ApiServerWebServerForbiddenError, ApiServerWebServerNotFoundError, ApiServerWebServerServerError, }, - TxSubmitClient, }; use api_server_common::storage::storage_api::{ - block_aux_data::BlockAuxData, AmountWithDecimals, ApiServerStorage, ApiServerStorageRead, - BlockInfo, CoinOrTokenStatistic, Order, TransactionInfo, + AmountWithDecimals, ApiServerStorage, ApiServerStorageRead, BlockInfo, CoinOrTokenStatistic, + Order, TransactionInfo, block_aux_data::BlockAuxData, }; use axum::{ + Json, Router, extract::{DefaultBodyLimit, Path, Query, State}, response::IntoResponse, routing::{get, post}, - Json, Router, }; use common::{ address::Address, chain::{ - block::timestamp::BlockTimestamp, - tokens::{IsTokenFreezable, IsTokenFrozen, IsTokenUnfreezable, TokenId}, Block, ChainConfig, Destination, OutPointSourceId, SignedTransaction, Transaction, UtxoOutPoint, + block::timestamp::BlockTimestamp, + tokens::{IsTokenFreezable, IsTokenFrozen, IsTokenUnfreezable, TokenId}, }, - primitives::{Amount, BlockHeight, CoinOrTokenId, Id, Idable, H256}, + primitives::{Amount, BlockHeight, CoinOrTokenId, H256, Id, Idable}, }; use hex::ToHex; use serde::Deserialize; @@ -221,13 +221,15 @@ pub async fn block_reward( ) -> Result { let block = get_block(&block_id, &state).await?.block; - Ok(Json(json!(block - .block - .block_reward() - .outputs() - .iter() - .map(|out| txoutput_to_json(out, &state.chain_config, &TokenDecimals::Single(None))) - .collect::>()))) + Ok(Json(json!( + block + .block + .block_reward() + .outputs() + .iter() + .map(|out| txoutput_to_json(out, &state.chain_config, &TokenDecimals::Single(None))) + .collect::>() + ))) } pub async fn block_transaction_ids( @@ -625,7 +627,7 @@ pub async fn transaction_merkle_path( (None, _) => { return Err(ApiServerWebServerError::NotFound( ApiServerWebServerNotFoundError::TransactionNotPartOfBlock, - )) + )); } }; diff --git a/api-server/web-server/src/error.rs b/api-server/web-server/src/error.rs index f70d72b099..e91a65fe3a 100644 --- a/api-server/web-server/src/error.rs +++ b/api-server/web-server/src/error.rs @@ -15,9 +15,9 @@ use api_server_common::storage::storage_api::ApiServerStorageError; use axum::{ + Json, http::StatusCode, response::{IntoResponse, Response}, - Json, }; use serde::Serialize; use serde_json::json; diff --git a/api-server/web-server/src/main.rs b/api-server/web-server/src/main.rs index 4a8d848121..f89e625520 100644 --- a/api-server/web-server/src/main.rs +++ b/api-server/web-server/src/main.rs @@ -19,8 +19,8 @@ mod error; use api_server_common::storage::impls::postgres::TransactionalApiServerPostgresStorage; use api_web_server::{ - api::web_server, config::ApiServerWebServerConfig, ApiServerWebServerState, CachedValues, - TxSubmitClient, + ApiServerWebServerState, CachedValues, TxSubmitClient, api::web_server, + config::ApiServerWebServerConfig, }; use clap::Parser; use common::{ @@ -78,7 +78,7 @@ async fn main() -> Result<(), ApiServerWebServerInitError> { _ => { return Err(ApiServerWebServerInitError::InvalidConfig( "Invalid RPC cookie/username/password combination".to_owned(), - )) + )); } }; let default_rpc_bind_address = diff --git a/blockprod/src/detail/job_manager/jobs_container.rs b/blockprod/src/detail/job_manager/jobs_container.rs index e2ea20da06..28b1c31ca9 100644 --- a/blockprod/src/detail/job_manager/jobs_container.rs +++ b/blockprod/src/detail/job_manager/jobs_container.rs @@ -13,11 +13,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::{btree_map::Entry, BTreeMap}; +use std::collections::{BTreeMap, btree_map::Entry}; use crate::detail::CustomId; use common::{ - chain::{block::timestamp::BlockTimestamp, GenBlock}, + chain::{GenBlock, block::timestamp::BlockTimestamp}, primitives::Id, }; use logging::log; diff --git a/blockprod/src/detail/job_manager/mod.rs b/blockprod/src/detail/job_manager/mod.rs index df71be0c47..2c29a568ac 100644 --- a/blockprod/src/detail/job_manager/mod.rs +++ b/blockprod/src/detail/job_manager/mod.rs @@ -19,13 +19,13 @@ use std::sync::Arc; use async_trait::async_trait; use tokio::sync::{ - mpsc::{self, unbounded_channel, UnboundedReceiver, UnboundedSender}, + mpsc::{self, UnboundedReceiver, UnboundedSender, unbounded_channel}, oneshot, }; use chainstate::{ChainstateEvent, ChainstateHandle}; use common::{ - chain::{block::timestamp::BlockTimestamp, GenBlock}, + chain::{GenBlock, block::timestamp::BlockTimestamp}, primitives::Id, }; use logging::log; diff --git a/blockprod/src/detail/mod.rs b/blockprod/src/detail/mod.rs index 52125c6180..7cb60be775 100644 --- a/blockprod/src/detail/mod.rs +++ b/blockprod/src/detail/mod.rs @@ -19,34 +19,34 @@ pub mod utils; use std::{ cmp, - sync::{mpsc, Arc}, + sync::{Arc, mpsc}, }; use tokio::sync::oneshot; -use chainstate::{chainstate_interface::ChainstateInterface, ChainstateHandle}; -use chainstate_types::{pos_randomness::PoSRandomness, GenBlockIndex}; +use chainstate::{ChainstateHandle, chainstate_interface::ChainstateInterface}; +use chainstate_types::{GenBlockIndex, pos_randomness::PoSRandomness}; use common::{ chain::{ + Block, ChainConfig, PoolId, RequiredConsensus, SignedTransaction, Transaction, block::{ - block_body::BlockBody, signed_block_header::SignedBlockHeader, - timestamp::BlockTimestamp, BlockCreationError, BlockHeader, BlockReward, ConsensusData, + BlockCreationError, BlockHeader, BlockReward, ConsensusData, block_body::BlockBody, + signed_block_header::SignedBlockHeader, timestamp::BlockTimestamp, }, - Block, ChainConfig, PoolId, RequiredConsensus, SignedTransaction, Transaction, }, primitives::{BlockHeight, Id}, time_getter::TimeGetter, }; use consensus::{ + ConsensusCreationError, ConsensusPoSError, ConsensusPoWError, FinalizeBlockInputData, + GenerateBlockInputData, PoSFinalizeBlockInputData, PoSGenerateBlockInputData, generate_consensus_data_and_reward_ignore_consensus, generate_pos_consensus_data_and_reward, - generate_pow_consensus_data_and_reward, ConsensusCreationError, ConsensusPoSError, - ConsensusPoWError, FinalizeBlockInputData, GenerateBlockInputData, PoSFinalizeBlockInputData, - PoSGenerateBlockInputData, + generate_pow_consensus_data_and_reward, }; use crypto::ephemeral_e2e::{self, EndToEndPrivateKey}; -use mempool::{tx_accumulator::PackingStrategy, MempoolHandle}; +use mempool::{MempoolHandle, tx_accumulator::PackingStrategy}; use p2p::P2pHandle; -use randomness::{make_true_rng, Rng, RngExt as _}; +use randomness::{Rng, RngExt as _, make_true_rng}; use serialization::{Decode, Encode}; use ::utils::{ @@ -55,12 +55,12 @@ use ::utils::{ }; use crate::{ + BlockProductionError, config::BlockProdConfig, detail::{ job_manager::{JobKey, JobManagerHandle, JobManagerImpl}, utils::collect_transactions, }, - BlockProductionError, }; use self::{ diff --git a/blockprod/src/detail/tests.rs b/blockprod/src/detail/tests.rs index 90666a2e6d..fe0f8d41fc 100644 --- a/blockprod/src/detail/tests.rs +++ b/blockprod/src/detail/tests.rs @@ -25,20 +25,20 @@ use tokio::{ use chainstate::{ChainstateError, ChainstateHandle, GenBlockIndex, PropertyQueryError}; use chainstate_test_framework::TransactionBuilder; use common::{ + Uint256, chain::{ + CoinUnit, ConsensusUpgrade, Destination, Genesis, NetUpgrades, OutPointSourceId, PoolId, + RequiredConsensus, TxOutput, block::timestamp::BlockTimestamp, - config::{create_unit_test_config, Builder, ChainType}, + config::{Builder, ChainType, create_unit_test_config}, output_value::OutputValue, signature::inputsig::InputWitness, stakelock::StakePoolData, timelock::OutputTimeLock, transaction::TxInput, - CoinUnit, ConsensusUpgrade, Destination, Genesis, NetUpgrades, OutPointSourceId, PoolId, - RequiredConsensus, TxOutput, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight, Id, Idable, H256}, + primitives::{Amount, BlockHeight, H256, Id, Idable, per_thousand::PerThousand}, time_getter::TimeGetter, - Uint256, }; use consensus::{ ConsensusCreationError, ConsensusPoSError, ConsensusPoWError, PoSGenerateBlockInputData, @@ -49,32 +49,31 @@ use crypto::{ vrf::{VRFKeyKind, VRFPrivateKey}, }; use mempool::{ + TxOptions, error::{BlockConstructionError, TxValidationError}, tx_accumulator::{DefaultTxAccumulator, PackingStrategy}, tx_origin::LocalTxOrigin, - TxOptions, }; use mocks::{MockChainstateInterface, MockMempoolInterface}; use randomness::RngExt as _; use subsystem::error::ResponseError; use test_utils::{ mock_time_getter::mocked_time_getter_seconds, - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, }; use utils::once_destructor::OnceDestructor; use crate::{ + BlockProduction, BlockProductionError, JobKey, detail::{ - collect_transactions, - job_manager::{tests::MockJobManager, JobManagerError, JobManagerImpl}, - CustomId, GenerateBlockInputData, + CustomId, GenerateBlockInputData, collect_transactions, + job_manager::{JobManagerError, JobManagerImpl, tests::MockJobManager}, }, prepare_thread_pool, test_blockprod_config, tests::{ assert_process_block, build_chain_config_for_pos, make_genesis_timestamp, setup_blockprod_test, setup_pos, setup_pos_with_genesis_timestamp, }, - BlockProduction, BlockProductionError, JobKey, }; mod collect_transactions { diff --git a/blockprod/src/detail/timestamp_searcher/mod.rs b/blockprod/src/detail/timestamp_searcher/mod.rs index d5768db62e..afacdeaafd 100644 --- a/blockprod/src/detail/timestamp_searcher/mod.rs +++ b/blockprod/src/detail/timestamp_searcher/mod.rs @@ -21,18 +21,18 @@ use std::{ use rayon::prelude::*; use chainstate::{ - chainstate_interface::ChainstateInterface, BlockIndex, ChainstateHandle, NonZeroPoolBalances, + BlockIndex, ChainstateHandle, NonZeroPoolBalances, chainstate_interface::ChainstateInterface, }; use chainstate_types::pos_randomness::PoSRandomness; use common::{ - chain::{block::timestamp::BlockTimestamp, config::EpochIndex, PoSConsensusVersion, PoolId}, - primitives::{Amount, BlockHeight, Compact}, Uint256, + chain::{PoSConsensusVersion, PoolId, block::timestamp::BlockTimestamp, config::EpochIndex}, + primitives::{Amount, BlockHeight, Compact}, }; use consensus::{ + ConsensusCreationError, ConsensusPoSError, PoSTimestampSearchInputData, calc_pos_hash_from_prv_key, calculate_target_required_from_block_index, check_pos_hash, - compact_target_to_target, ConsensusCreationError, ConsensusPoSError, - PoSTimestampSearchInputData, + compact_target_to_target, }; use crypto::vrf::{VRFPrivateKey, VRFPublicKey}; use logging::log; @@ -41,12 +41,12 @@ use serialization::{Decode, Encode}; use utils::{ensure, once_destructor::OnceDestructor, tokio_spawn_blocking}; use crate::{ + BlockProductionError, detail::utils::{ get_best_block_index, get_block_id_from_height, get_existing_block_index, get_existing_gen_block_index, get_pool_balances_at_heights, get_sealed_epoch_randomness, make_ancestor_getter, pos_data_from_header, pos_status_from_height, timestamp_add_secs, }, - BlockProductionError, }; #[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)] @@ -401,11 +401,7 @@ fn find_timestamps_for_staking_impl( .reduce( || Ok::<_, BlockProductionError>(()), |res1, res2| { - if res1.is_err() { - res1 - } else { - res2 - } + if res1.is_err() { res1 } else { res2 } }, )? }; diff --git a/blockprod/src/detail/timestamp_searcher/tests.rs b/blockprod/src/detail/timestamp_searcher/tests.rs index bac97a13a2..cf1da29d69 100644 --- a/blockprod/src/detail/timestamp_searcher/tests.rs +++ b/blockprod/src/detail/timestamp_searcher/tests.rs @@ -15,29 +15,30 @@ use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use logging::{init_logging, log}; use randomness::{CryptoRng, RngExt as _}; -use crate::{detail::timestamp_searcher::SearchDataForHeight, TimestampSearchData}; +use crate::{TimestampSearchData, detail::timestamp_searcher::SearchDataForHeight}; mod collect_search_data { use std::num::NonZeroU64; use chainstate::{ChainstateConfig, NonZeroPoolBalances}; use chainstate_test_framework::{ + PoSBlockBuilder, TestFramework, TransactionBuilder, UtxoForSpending, create_custom_genesis_with_stake_pool, create_stake_pool_data_with_all_reward_to_staker, - empty_witness, PoSBlockBuilder, TestFramework, TransactionBuilder, UtxoForSpending, + empty_witness, }; use chainstate_types::pos_randomness::PoSRandomness; use common::{ chain::{ - self, config::ChainType, make_delegation_id, output_value::OutputValue, CoinUnit, - ConsensusUpgrade, Destination, NetUpgrades, OutPointSourceId, PoSChainConfigBuilder, - PoSConsensusVersion, PoolId, TxOutput, UtxoOutPoint, + self, CoinUnit, ConsensusUpgrade, Destination, NetUpgrades, OutPointSourceId, + PoSChainConfigBuilder, PoSConsensusVersion, PoolId, TxOutput, UtxoOutPoint, + config::ChainType, make_delegation_id, output_value::OutputValue, }, - primitives::{Amount, BlockCount, BlockHeight, Idable, H256}, + primitives::{Amount, BlockCount, BlockHeight, H256, Idable}, }; use consensus::calculate_target_required_from_block_index; use crypto::{ @@ -91,7 +92,9 @@ mod collect_search_data { make_block_builder(&mut tf).build_and_process(&mut rng).unwrap(); } - log::debug!("pool_creation_height = {pool_creation_height}, delegation_height = {delegation_height}"); + log::debug!( + "pool_creation_height = {pool_creation_height}, delegation_height = {delegation_height}" + ); let seconds_to_check = 1000; @@ -505,9 +508,9 @@ mod search { use chainstate::NonZeroPoolBalances; use chainstate_types::pos_randomness::PoSRandomness; use common::{ + Uint256, chain::PoSConsensusVersion, primitives::{Amount, H256}, - Uint256, }; use consensus::PoSTimestampSearchInputData; use crypto::vrf::{VRFKeyKind, VRFPrivateKey}; diff --git a/blockprod/src/detail/utils.rs b/blockprod/src/detail/utils.rs index 731a51ea7c..7c21e73f9f 100644 --- a/blockprod/src/detail/utils.rs +++ b/blockprod/src/detail/utils.rs @@ -14,24 +14,24 @@ // limitations under the License. use chainstate::{ - chainstate_interface::ChainstateInterface, BlockIndex, GenBlockIndex, NonZeroPoolBalances, + BlockIndex, GenBlockIndex, NonZeroPoolBalances, chainstate_interface::ChainstateInterface, }; -use chainstate_types::{pos_randomness::PoSRandomness, EpochData}; +use chainstate_types::{EpochData, pos_randomness::PoSRandomness}; use common::{ chain::{ + Block, ChainConfig, GenBlock, PoSStatus, PoolId, RequiredConsensus, SignedTransaction, + Transaction, block::{ + BlockHeader, ConsensusData, consensus_data::PoSData, timestamp::{BlockTimestamp, BlockTimestampInternalType}, - BlockHeader, ConsensusData, }, - Block, ChainConfig, GenBlock, PoSStatus, PoolId, RequiredConsensus, SignedTransaction, - Transaction, }, primitives::{Amount, BlockHeight, Id, Idable}, }; use mempool::{ - tx_accumulator::{DefaultTxAccumulator, PackingStrategy, TransactionAccumulator}, MempoolHandle, + tx_accumulator::{DefaultTxAccumulator, PackingStrategy, TransactionAccumulator}, }; use crate::BlockProductionError; diff --git a/blockprod/src/interface/blockprod_interface.rs b/blockprod/src/interface/blockprod_interface.rs index aaead5306b..80f292b220 100644 --- a/blockprod/src/interface/blockprod_interface.rs +++ b/blockprod/src/interface/blockprod_interface.rs @@ -13,7 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{detail::job_manager::JobKey, BlockProductionError, TimestampSearchData}; +use crate::{BlockProductionError, TimestampSearchData, detail::job_manager::JobKey}; use common::{ chain::{Block, PoolId, SignedTransaction, Transaction}, primitives::{BlockHeight, Id}, diff --git a/blockprod/src/interface/blockprod_interface_impl.rs b/blockprod/src/interface/blockprod_interface_impl.rs index f128e2b7bd..4f0cd125c6 100644 --- a/blockprod/src/interface/blockprod_interface_impl.rs +++ b/blockprod/src/interface/blockprod_interface_impl.rs @@ -14,8 +14,8 @@ // limitations under the License. use crate::{ - detail::{job_manager::JobKey, BlockProduction}, BlockProductionError, TimestampSearchData, + detail::{BlockProduction, job_manager::JobKey}, }; use common::{ chain::{Block, PoolId, SignedTransaction, Transaction}, diff --git a/blockprod/src/lib.rs b/blockprod/src/lib.rs index 3e243a59c5..36e9e185e1 100644 --- a/blockprod/src/lib.rs +++ b/blockprod/src/lib.rs @@ -23,8 +23,8 @@ use std::sync::Arc; use chainstate::ChainstateHandle; use common::{ chain::{ - block::{timestamp::BlockTimestamp, BlockCreationError}, ChainConfig, GenBlock, PoolId, Transaction, + block::{BlockCreationError, timestamp::BlockTimestamp}, }, primitives::{BlockHeight, Id}, time_getter::TimeGetter, @@ -33,15 +33,15 @@ use config::BlockProdConfig; use consensus::ConsensusCreationError; use crypto::ephemeral_e2e; use detail::{ - job_manager::{JobKey, JobManagerError}, BlockProduction, + job_manager::{JobKey, JobManagerError}, }; use interface::blockprod_interface::BlockProductionInterface; -use mempool::{tx_accumulator::TxAccumulatorError, MempoolHandle}; +use mempool::{MempoolHandle, tx_accumulator::TxAccumulatorError}; use p2p::P2pHandle; use subsystem::error::CallError; -pub use detail::timestamp_searcher::{find_timestamps_for_staking, TimestampSearchData}; +pub use detail::timestamp_searcher::{TimestampSearchData, find_timestamps_for_staking}; #[derive(thiserror::Error, Debug, PartialEq, Eq)] pub enum BlockProductionError { @@ -160,18 +160,17 @@ mod tests { }; use chainstate_storage::inmemory::Store; use common::{ + Uint256, Uint512, chain::{ - self, + self, Block, ConsensusUpgrade, Destination, Genesis, NetUpgrades, + PoSChainConfigBuilder, TxOutput, block::timestamp::BlockTimestamp, - config::{create_unit_test_config, ChainConfig, ChainType}, + config::{ChainConfig, ChainType, create_unit_test_config}, pos_initial_difficulty, stakelock::StakePoolData, - Block, ConsensusUpgrade, Destination, Genesis, NetUpgrades, PoSChainConfigBuilder, - TxOutput, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight, Idable, H256}, + primitives::{Amount, BlockHeight, H256, Idable, per_thousand::PerThousand}, time_getter::TimeGetter, - Uint256, Uint512, }; use consensus::{calculate_effective_pool_balance, compact_target_to_target}; use crypto::{ diff --git a/blockprod/src/rpc.rs b/blockprod/src/rpc.rs index 268cbf5b19..ade16663b5 100644 --- a/blockprod/src/rpc.rs +++ b/blockprod/src/rpc.rs @@ -25,7 +25,7 @@ use mempool::tx_accumulator::PackingStrategy; use rpc::RpcResult; use serialization::hex_encoded::HexEncoded; -use crate::{detail::job_manager::JobKey, TimestampSearchData}; +use crate::{TimestampSearchData, detail::job_manager::JobKey}; #[rpc::describe] #[rpc::rpc(server, client, namespace = "blockprod")] diff --git a/chainstate/constraints-value-accumulator/src/constraints_accumulator.rs b/chainstate/constraints-value-accumulator/src/constraints_accumulator.rs index e204a0c809..dace67c6bf 100644 --- a/chainstate/constraints-value-accumulator/src/constraints_accumulator.rs +++ b/chainstate/constraints-value-accumulator/src/constraints_accumulator.rs @@ -17,8 +17,8 @@ use std::{collections::BTreeMap, num::NonZeroU64}; use common::{ chain::{ - output_value::OutputValue, timelock::OutputTimeLock, AccountCommand, AccountSpending, - AccountType, ChainConfig, OrderAccountCommand, OrderId, TxInput, TxOutput, UtxoOutPoint, + AccountCommand, AccountSpending, AccountType, ChainConfig, OrderAccountCommand, OrderId, + TxInput, TxOutput, UtxoOutPoint, output_value::OutputValue, timelock::OutputTimeLock, }, primitives::{Amount, BlockHeight, CoinOrTokenId, Fee, Subsidy}, }; @@ -27,7 +27,7 @@ use pos_accounting::{PoSAccountingOperations, PoSAccountingUndo, PoSAccountingVi use tokens_accounting::{TokensAccountingOperations, TokensAccountingView}; use utils::ensure; -use super::{accumulated_fee::AccumulatedFee, insert_or_increase, Error}; +use super::{Error, accumulated_fee::AccumulatedFee, insert_or_increase}; /// `ConstrainedValueAccumulator` helps avoiding messy inputs/outputs combinations analysis by /// providing a set of properties that should be satisfied. For example instead of checking that diff --git a/chainstate/constraints-value-accumulator/src/tests/constraints_tests.rs b/chainstate/constraints-value-accumulator/src/tests/constraints_tests.rs index da7dfa781f..c3a2755f52 100644 --- a/chainstate/constraints-value-accumulator/src/tests/constraints_tests.rs +++ b/chainstate/constraints-value-accumulator/src/tests/constraints_tests.rs @@ -17,18 +17,18 @@ use std::collections::BTreeMap; use common::{ chain::{ + AccountCommand, AccountNonce, AccountSpending, ConsensusUpgrade, DelegationId, Destination, + NetUpgrades, OutPointSourceId, PoSChainConfigBuilder, PoolId, TxInput, TxOutput, + UtxoOutPoint, config::ChainType, htlc::{HashedTimelockContract, HtlcSecret}, output_value::OutputValue, stakelock::StakePoolData, timelock::OutputTimeLock, tokens::{NftIssuance, TokenId, TokenIssuance}, - AccountCommand, AccountNonce, AccountSpending, ConsensusUpgrade, DelegationId, Destination, - NetUpgrades, OutPointSourceId, PoSChainConfigBuilder, PoolId, TxInput, TxOutput, - UtxoOutPoint, }, primitives::{ - per_thousand::PerThousand, Amount, BlockCount, BlockHeight, CoinOrTokenId, Fee, Id, H256, + Amount, BlockCount, BlockHeight, CoinOrTokenId, Fee, H256, Id, per_thousand::PerThousand, }, }; use crypto::vrf::{VRFKeyKind, VRFPrivateKey}; @@ -37,7 +37,7 @@ use pos_accounting::{DelegationData, InMemoryPoSAccounting, PoSAccountingDB, Poo use randomness::{CryptoRng, RngExt as _}; use rstest::rstest; use test_utils::{ - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, token_utils::random_nft_issuance, }; diff --git a/chainstate/constraints-value-accumulator/src/tests/homomorphism.rs b/chainstate/constraints-value-accumulator/src/tests/homomorphism.rs index 991cc74c45..e39828fa00 100644 --- a/chainstate/constraints-value-accumulator/src/tests/homomorphism.rs +++ b/chainstate/constraints-value-accumulator/src/tests/homomorphism.rs @@ -15,17 +15,17 @@ use common::{ chain::{ - config::ChainType, output_value::OutputValue, stakelock::StakePoolData, - timelock::OutputTimeLock, AccountNonce, AccountSpending, DelegationId, Destination, - NetUpgrades, OutPointSourceId, PoolId, Transaction, TxInput, TxOutput, + AccountNonce, AccountSpending, DelegationId, Destination, NetUpgrades, OutPointSourceId, + PoolId, Transaction, TxInput, TxOutput, config::ChainType, output_value::OutputValue, + stakelock::StakePoolData, timelock::OutputTimeLock, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight, Fee, Id, H256}, + primitives::{Amount, BlockHeight, Fee, H256, Id, per_thousand::PerThousand}, }; use crypto::vrf::{VRFKeyKind, VRFPrivateKey}; use randomness::{CryptoRng, RngExt as _}; use rstest::rstest; use test_utils::{ - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, split_value, }; diff --git a/chainstate/constraints-value-accumulator/src/tests/orders_constraints.rs b/chainstate/constraints-value-accumulator/src/tests/orders_constraints.rs index 919f669149..eb739aab48 100644 --- a/chainstate/constraints-value-accumulator/src/tests/orders_constraints.rs +++ b/chainstate/constraints-value-accumulator/src/tests/orders_constraints.rs @@ -19,18 +19,18 @@ use rstest::rstest; use common::{ chain::{ + AccountCommand, AccountNonce, ChainstateUpgradeBuilder, Destination, OrderAccountCommand, + OrderData, OrderId, OrdersVersion, OutPointSourceId, TxInput, TxOutput, UtxoOutPoint, config::{create_unit_test_config, create_unit_test_config_builder}, output_value::OutputValue, tokens::TokenId, - AccountCommand, AccountNonce, ChainstateUpgradeBuilder, Destination, OrderAccountCommand, - OrderData, OrderId, OrdersVersion, OutPointSourceId, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{Amount, BlockHeight, CoinOrTokenId, Fee, Id, H256}, + primitives::{Amount, BlockHeight, CoinOrTokenId, Fee, H256, Id}, }; use orders_accounting::{InMemoryOrdersAccounting, OrdersAccountingDB}; use pos_accounting::{InMemoryPoSAccounting, PoSAccountingDB}; use randomness::RngExt as _; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use crate::{ConstrainedValueAccumulator, Error}; diff --git a/chainstate/db-dumper/src/dumper/main.rs b/chainstate/db-dumper/src/dumper/main.rs index 2d1e8a9c53..2f2ba8bff6 100644 --- a/chainstate/db-dumper/src/dumper/main.rs +++ b/chainstate/db-dumper/src/dumper/main.rs @@ -19,7 +19,7 @@ use utils::default_data_dir::default_data_dir_for_chain; use chainstate_db_dumper_lib::{dump_blocks_to_file, parse_block_output_fields_list}; -use crate::options::{default_fields, Options}; +use crate::options::{Options, default_fields}; mod options; diff --git a/chainstate/db-dumper/src/dumper_lib/dump_blocks.rs b/chainstate/db-dumper/src/dumper_lib/dump_blocks.rs index 694f43edd3..6de0dee824 100644 --- a/chainstate/db-dumper/src/dumper_lib/dump_blocks.rs +++ b/chainstate/db-dumper/src/dumper_lib/dump_blocks.rs @@ -18,23 +18,23 @@ use std::{ sync::Arc, }; -use chainstate::{chainstate_interface::ChainstateInterface, BlockIndex}; +use chainstate::{BlockIndex, chainstate_interface::ChainstateInterface}; use chainstate_types::{BlockStatus, BlockValidationStage}; use common::{ + Uint256, address::Address, - chain::{self, config::ChainType, ChainConfig, Genesis}, + chain::{self, ChainConfig, Genesis, config::ChainType}, primitives::id::WithId, - Uint256, }; use logging::log; use utils::ensure; use crate::{ + BlockOutputField, Error, utils::{ create_chainstate, get_pos_consensus_data, map_output_write_err, write_comma_if_needed, write_eol, }, - BlockOutputField, Error, }; // Note: this function will fail if the genesis id in the created chain config doesn't diff --git a/chainstate/db-dumper/src/dumper_lib/lib.rs b/chainstate/db-dumper/src/dumper_lib/lib.rs index fc66c5591a..f46ded55a6 100644 --- a/chainstate/db-dumper/src/dumper_lib/lib.rs +++ b/chainstate/db-dumper/src/dumper_lib/lib.rs @@ -23,6 +23,6 @@ mod utils; pub use dump_blocks::{dump_blocks_generic, dump_blocks_to_file}; pub use error::Error; pub use fields::{ - parse_block_output_fields_list, BlockOutputField, DEFAULT_BLOCK_OUTPUT_FIELDS_MAINCHAIN_ONLY, - DEFAULT_BLOCK_OUTPUT_FIELDS_WITH_STALE_CHAINS, + BlockOutputField, DEFAULT_BLOCK_OUTPUT_FIELDS_MAINCHAIN_ONLY, + DEFAULT_BLOCK_OUTPUT_FIELDS_WITH_STALE_CHAINS, parse_block_output_fields_list, }; diff --git a/chainstate/db-dumper/src/dumper_lib/tests/mod.rs b/chainstate/db-dumper/src/dumper_lib/tests/mod.rs index d65dfa7ca0..4bd217095f 100644 --- a/chainstate/db-dumper/src/dumper_lib/tests/mod.rs +++ b/chainstate/db-dumper/src/dumper_lib/tests/mod.rs @@ -21,28 +21,27 @@ use strum::IntoEnumIterator as _; use chainstate::BlockIndex; use chainstate_launcher::ChainConfig; -use chainstate_types::{vrf_tools::construct_transcript, BlockStatus, BlockValidationStage}; +use chainstate_types::{BlockStatus, BlockValidationStage, vrf_tools::construct_transcript}; use common::{ + Uint256, address::Address, chain::{ - self, - block::{consensus_data::PoSData, timestamp::BlockTimestamp, BlockReward, ConsensusData}, - Block, GenBlock, Genesis, PoolId, + self, Block, GenBlock, Genesis, PoolId, + block::{BlockReward, ConsensusData, consensus_data::PoSData, timestamp::BlockTimestamp}, }, - primitives::{BlockHeight, Compact, Id, H256}, - Uint256, + primitives::{BlockHeight, Compact, H256, Id}, }; use crypto::vrf::{VRFKeyKind, VRFPrivateKey, VRFReturn}; use mocks::MockChainstateInterface; use test_utils::{ random::{ - make_seedable_rng, randomness::SliceRandom, CryptoRng, IteratorRandom as _, RngExt as _, - Seed, + CryptoRng, IteratorRandom as _, RngExt as _, Seed, make_seedable_rng, + randomness::SliceRandom, }, random_ascii_alphanumeric_string, }; -use crate::{dump_blocks::BlockStatusOutput, dump_blocks_generic, BlockOutputField}; +use crate::{BlockOutputField, dump_blocks::BlockStatusOutput, dump_blocks_generic}; #[ctor::ctor] fn init() { diff --git a/chainstate/db-dumper/src/dumper_lib/utils.rs b/chainstate/db-dumper/src/dumper_lib/utils.rs index 5d2f0e7b67..07ee708a50 100644 --- a/chainstate/db-dumper/src/dumper_lib/utils.rs +++ b/chainstate/db-dumper/src/dumper_lib/utils.rs @@ -21,8 +21,8 @@ use chainstate::{ use chainstate_launcher::check_storage_compatibility; use chainstate_storage::Transactional as _; use common::chain::{ - block::{consensus_data::PoSData, ConsensusData}, ChainConfig, + block::{ConsensusData, consensus_data::PoSData}, }; use logging::log; use storage_lmdb::resize_callback::MapResizeCallback; diff --git a/chainstate/launcher/src/lib.rs b/chainstate/launcher/src/lib.rs index 0cf05224c7..345cb52e5c 100644 --- a/chainstate/launcher/src/lib.rs +++ b/chainstate/launcher/src/lib.rs @@ -29,8 +29,8 @@ use utils::set_flag::SetFlag; // Some useful reexports pub use chainstate::{ - chainstate_interface::ChainstateInterface, ChainstateConfig, ChainstateError as Error, - ChainstateSubsystem, DefaultTransactionVerificationStrategy, + ChainstateConfig, ChainstateError as Error, ChainstateSubsystem, + DefaultTransactionVerificationStrategy, chainstate_interface::ChainstateInterface, }; pub use common::chain::ChainConfig; pub use config::{ChainstateLauncherConfig, StorageBackendConfig}; diff --git a/chainstate/src/config.rs b/chainstate/src/config.rs index f13f956eb1..e3ef29c0b7 100644 --- a/chainstate/src/config.rs +++ b/chainstate/src/config.rs @@ -15,7 +15,7 @@ use std::time::Duration; -use common::chain::{config::ChainType, ChainConfig}; +use common::chain::{ChainConfig, config::ChainType}; use utils::make_config_setting; make_config_setting!(MaxDbCommitAttempts, usize, 10); diff --git a/chainstate/src/detail/ban_score.rs b/chainstate/src/detail/ban_score.rs index 56af0be08a..dce7b16e8e 100644 --- a/chainstate/src/detail/ban_score.rs +++ b/chainstate/src/detail/ban_score.rs @@ -19,20 +19,20 @@ use consensus::{ BlockSignatureError, ConsensusPoSError, ConsensusPoWError, ConsensusVerificationError, }; use tx_verifier::{ + CheckTransactionError, timelock_check::OutputMaturityError, transaction_verifier::{ - error::SignatureDestinationGetterError, IOPolicyError, RewardDistributionError, + IOPolicyError, RewardDistributionError, error::SignatureDestinationGetterError, }, - CheckTransactionError, }; use super::{ + BlockSizeError, CheckBlockError, CheckBlockTransactionsError, OrphanCheckError, chainstateref::{EpochSealError, InMemoryReorgError}, transaction_verifier::{ error::{ConnectTransactionError, TokensError}, storage::TransactionVerifierStorageError, }, - BlockSizeError, CheckBlockError, CheckBlockTransactionsError, OrphanCheckError, }; use crate::{BlockError, ChainstateError}; use chainstate_types::GetAncestorError; diff --git a/chainstate/src/detail/block_checking.rs b/chainstate/src/detail/block_checking.rs index 736daf9ca8..d620fc11ca 100644 --- a/chainstate/src/detail/block_checking.rs +++ b/chainstate/src/detail/block_checking.rs @@ -17,7 +17,7 @@ use super::Chainstate; use crate::{BlockError, TransactionVerificationStrategy}; use chainstate_storage::BlockchainStorage; use common::{ - chain::{block::signed_block_header::SignedBlockHeader, Block}, + chain::{Block, block::signed_block_header::SignedBlockHeader}, primitives::id::WithId, }; use utils::tap_log::TapLog; diff --git a/chainstate/src/detail/block_invalidation/best_chain_candidates.rs b/chainstate/src/detail/block_invalidation/best_chain_candidates.rs index e611c2bbb4..51db8010f0 100644 --- a/chainstate/src/detail/block_invalidation/best_chain_candidates.rs +++ b/chainstate/src/detail/block_invalidation/best_chain_candidates.rs @@ -17,13 +17,13 @@ use std::collections::BTreeSet; use thiserror::Error; -use crate::{detail::chainstateref::ChainstateRef, TransactionVerificationStrategy}; +use crate::{TransactionVerificationStrategy, detail::chainstateref::ChainstateRef}; use chainstate_storage::BlockchainStorageRead; use chainstate_types::{BlockIndex, BlockStatus, GenBlockIndex, PropertyQueryError}; use common::{ + Uint256, chain::{Block, GenBlock}, primitives::{BlockHeight, Id}, - Uint256, }; use utils::{log_error, tap_log::TapLog}; diff --git a/chainstate/src/detail/block_invalidation/best_chain_candidates_tests.rs b/chainstate/src/detail/block_invalidation/best_chain_candidates_tests.rs index e3d6d86532..0da02e3182 100644 --- a/chainstate/src/detail/block_invalidation/best_chain_candidates_tests.rs +++ b/chainstate/src/detail/block_invalidation/best_chain_candidates_tests.rs @@ -17,9 +17,9 @@ use std::collections::BTreeSet; use chainstate_types::BlockStatus; use common::{ + Uint256, chain::Block, primitives::{BlockHeight, Id}, - Uint256, }; use super::best_chain_candidates::BestChainCandidates; @@ -49,7 +49,7 @@ fn bad_status() -> BlockStatus { // G----m0-----m1-----m2----m3----m4----m5----m6 #[test] fn the_test() { - use test_framework::{make_block_id, TestChainstate}; + use test_framework::{TestChainstate, make_block_id}; let mut tc = TestChainstate::new(BlockHeight::zero()); let m0 = tc.add_block(make_block_id(0), good_status(), true); diff --git a/chainstate/src/detail/block_invalidation/mod.rs b/chainstate/src/detail/block_invalidation/mod.rs index 177eb46e2d..084e16c5eb 100644 --- a/chainstate/src/detail/block_invalidation/mod.rs +++ b/chainstate/src/detail/block_invalidation/mod.rs @@ -21,17 +21,17 @@ use derive_more::Display; use thiserror::Error; use self::best_chain_candidates::BestChainCandidates; -use super::{chainstateref::ChainstateRef, Chainstate}; +use super::{Chainstate, chainstateref::ChainstateRef}; use crate::{ - detail::chainstateref::ReorgError, BlockError, BlockProcessingErrorClassification, - TransactionVerificationStrategy, + BlockError, BlockProcessingErrorClassification, TransactionVerificationStrategy, + detail::chainstateref::ReorgError, }; use chainstate_storage::{BlockchainStorage, BlockchainStorageRead, BlockchainStorageWrite}; use chainstate_types::{BlockIndex, BlockStatus, GenBlockIndex, PropertyQueryError}; use common::{ + Uint256, chain::{Block, GenBlock}, primitives::{BlockHeight, Id}, - Uint256, }; use logging::log; use utils::{ensure, log_error}; diff --git a/chainstate/src/detail/bootstrap.rs b/chainstate/src/detail/bootstrap.rs index 742399a5c9..2753aa9e60 100644 --- a/chainstate/src/detail/bootstrap.rs +++ b/chainstate/src/detail/bootstrap.rs @@ -21,8 +21,8 @@ use chainstate_storage::BlockchainStorageRead; use chainstate_types::PropertyQueryError; use common::{ chain::{ - config::{ChainType, MagicBytes}, Block, ChainConfig, + config::{ChainType, MagicBytes}, }, primitives::id::WithId, }; @@ -262,7 +262,7 @@ mod tests { use rstest::rstest; use randomness::RngExt as _; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use super::*; diff --git a/chainstate/src/detail/chainstateref/block_info.rs b/chainstate/src/detail/chainstateref/block_info.rs index 3316ddb016..8dc8e51009 100644 --- a/chainstate/src/detail/chainstateref/block_info.rs +++ b/chainstate/src/detail/chainstateref/block_info.rs @@ -16,10 +16,10 @@ use chainstate_types::BlockIndex; use common::{ chain::{ - block::{signed_block_header::SignedBlockHeader, BlockHeader}, Block, + block::{BlockHeader, signed_block_header::SignedBlockHeader}, }, - primitives::{id::WithId, Id, Idable}, + primitives::{Id, Idable, id::WithId}, }; /// A block header together with its (probably pre-computed) id. diff --git a/chainstate/src/detail/chainstateref/consistency_checker.rs b/chainstate/src/detail/chainstateref/consistency_checker.rs index 6dc06c5ffa..47daf7e407 100644 --- a/chainstate/src/detail/chainstateref/consistency_checker.rs +++ b/chainstate/src/detail/chainstateref/consistency_checker.rs @@ -127,8 +127,7 @@ impl<'a, DbTx: BlockchainStorageRead> ConsistencyChecker<'a, DbTx> { // Check that the id stored in the block index matches the supposed id of the block. let block_id_in_block_index = block_index.block_id(); assert_eq!( - block_id, - block_id_in_block_index, + block_id, block_id_in_block_index, "{PANIC_MSG}: block id from BlockIndex {block_id_in_block_index} doesn't match {block_id}" ); diff --git a/chainstate/src/detail/chainstateref/epoch_seal.rs b/chainstate/src/detail/chainstateref/epoch_seal.rs index 70f06b5923..2d94d4a609 100644 --- a/chainstate/src/detail/chainstateref/epoch_seal.rs +++ b/chainstate/src/detail/chainstateref/epoch_seal.rs @@ -15,13 +15,13 @@ use chainstate_storage::BlockchainStorageWrite; use chainstate_types::{ - pos_randomness::{PoSRandomness, PoSRandomnessError}, EpochData, EpochStorageRead, EpochStorageWrite, SealedStorageTag, + pos_randomness::{PoSRandomness, PoSRandomnessError}, }; use common::{ chain::{ - block::{consensus_data::PoSData, ConsensusData}, Block, ChainConfig, PoolId, TxOutput, + block::{ConsensusData, consensus_data::PoSData}, }, primitives::BlockHeight, }; @@ -274,16 +274,16 @@ mod tests { use super::*; use chainstate_storage::mock::MockStoreTxRw; - use chainstate_types::{vrf_tools::construct_transcript, EpochDataCache, TipStorageTag}; + use chainstate_types::{EpochDataCache, TipStorageTag, vrf_tools::construct_transcript}; use common::{ chain::{ - block::{consensus_data::PoSData, timestamp::BlockTimestamp, BlockReward}, + Block, Destination, PoolId, TxOutput, + block::{BlockReward, consensus_data::PoSData, timestamp::BlockTimestamp}, config::{Builder as ConfigBuilder, ChainType, EpochIndex}, get_initial_randomness, stakelock::StakePoolData, - Block, Destination, PoolId, TxOutput, }, - primitives::{per_thousand::PerThousand, Amount, Compact, H256}, + primitives::{Amount, Compact, H256, per_thousand::PerThousand}, }; use crypto::vrf::{VRFKeyKind, VRFPrivateKey}; use mockall::predicate::eq; diff --git a/chainstate/src/detail/chainstateref/in_memory_reorg.rs b/chainstate/src/detail/chainstateref/in_memory_reorg.rs index 107e32c6de..15ac64d9a7 100644 --- a/chainstate/src/detail/chainstateref/in_memory_reorg.rs +++ b/chainstate/src/detail/chainstateref/in_memory_reorg.rs @@ -22,26 +22,25 @@ use chainstate_types::{ }; use common::{ chain::{Block, ChainConfig, GenBlock, GenBlockId}, - primitives::{id::WithId, Id}, + primitives::{Id, id::WithId}, }; use orders_accounting::OrdersAccountingDB; use pos_accounting::PoSAccountingDB; use thiserror::Error; use tokens_accounting::TokensAccountingDB; use tx_verifier::{ - error::ConnectTransactionError, flush_to_storage, - transaction_verifier::TransactionVerifierDelta, TransactionVerifier, - TransactionVerifierStorageError, + TransactionVerifier, TransactionVerifierStorageError, error::ConnectTransactionError, + flush_to_storage, transaction_verifier::TransactionVerifierDelta, }; use utils::{ensure, log_error, tap_log::TapLog}; use utxo::UtxosDB; use crate::{ - ban_score::BanScore, calculate_median_time_past, BlockProcessingErrorClass, - BlockProcessingErrorClassification, TransactionVerificationStrategy, + BlockProcessingErrorClass, BlockProcessingErrorClassification, TransactionVerificationStrategy, + ban_score::BanScore, calculate_median_time_past, }; -use super::{epoch_seal, ChainstateRef, EpochSealError}; +use super::{ChainstateRef, EpochSealError, epoch_seal}; impl<'a, S: BlockchainStorageRead, V: TransactionVerificationStrategy> ChainstateRef<'a, S, V> { /// Disconnect all blocks from mainchain until the first mainchain ancestor of diff --git a/chainstate/src/detail/chainstateref/mod.rs b/chainstate/src/detail/chainstateref/mod.rs index ed5d0c2d18..61f9a80490 100644 --- a/chainstate/src/detail/chainstateref/mod.rs +++ b/chainstate/src/detail/chainstateref/mod.rs @@ -29,26 +29,26 @@ use thiserror::Error; use chainstate_storage::{BlockchainStorageRead, BlockchainStorageWrite, TransactionRw}; use chainstate_types::{ - block_index_ancestor_getter, get_skip_height, BlockIndex, BlockIndexHandle, BlockStatus, - BlockValidationStage, EpochData, EpochDataCache, GenBlockIndex, GetAncestorError, - PropertyQueryError, TipStorageTag, + BlockIndex, BlockIndexHandle, BlockStatus, BlockValidationStage, EpochData, EpochDataCache, + GenBlockIndex, GetAncestorError, PropertyQueryError, TipStorageTag, + block_index_ancestor_getter, get_skip_height, }; use common::{ + Uint256, chain::{ + AccountNonce, AccountType, Block, ChainConfig, GenBlock, GenBlockId, OrderAccountCommand, + PoolId, Transaction, TxInput, TxOutput, UtxoOutPoint, block::{ - signed_block_header::SignedBlockHeader, timestamp::BlockTimestamp, BlockReward, - ConsensusData, + BlockReward, ConsensusData, signed_block_header::SignedBlockHeader, + timestamp::BlockTimestamp, }, config::EpochIndex, tokens::{TokenAuxiliaryData, TokenId}, - AccountNonce, AccountType, Block, ChainConfig, GenBlock, GenBlockId, OrderAccountCommand, - PoolId, Transaction, TxInput, TxOutput, UtxoOutPoint, }, primitives::{ - id::WithId, time::Time, Amount, BlockCount, BlockDistance, BlockHeight, Id, Idable, + Amount, BlockCount, BlockDistance, BlockHeight, Id, Idable, id::WithId, time::Time, }, time_getter::TimeGetter, - Uint256, }; use logging::log; use pos_accounting::{ @@ -66,9 +66,9 @@ use self::{ }; use super::{ + BlockSizeError, CheckBlockError, CheckBlockTransactionsError, median_time::calculate_median_time_past, transaction_verifier::flush::flush_to_storage, - tx_verification_strategy::TransactionVerificationStrategy, BlockSizeError, CheckBlockError, - CheckBlockTransactionsError, + tx_verification_strategy::TransactionVerificationStrategy, }; pub use epoch_seal::EpochSealError; @@ -343,7 +343,7 @@ impl<'a, S: BlockchainStorageRead, V: TransactionVerificationStrategy> Chainstat loop { match (&first_block_index, &second_block_index) { _ if first_block_index.block_id() == second_block_index.block_id() => { - break Ok(first_block_index) + break Ok(first_block_index); } (GenBlockIndex::Block(first_blkidx), GenBlockIndex::Block(second_blkidx)) => { first_block_index = self.get_previous_block_index(first_blkidx)?; diff --git a/chainstate/src/detail/chainstateref/tx_verifier_storage.rs b/chainstate/src/detail/chainstateref/tx_verifier_storage.rs index 2d0559ffaf..30bee2e915 100644 --- a/chainstate/src/detail/chainstateref/tx_verifier_storage.rs +++ b/chainstate/src/detail/chainstateref/tx_verifier_storage.rs @@ -24,12 +24,12 @@ use crate::detail::{ tx_verification_strategy::TransactionVerificationStrategy, }; use chainstate_storage::{BlockchainStorageRead, BlockchainStorageWrite}; -use chainstate_types::{storage_result, GenBlockIndex, TipStorageTag}; +use chainstate_types::{GenBlockIndex, TipStorageTag, storage_result}; use common::{ chain::{ - tokens::{TokenAuxiliaryData, TokenId}, AccountNonce, AccountType, ChainConfig, DelegationId, GenBlock, GenBlockId, OrderId, PoolId, Transaction, + tokens::{TokenAuxiliaryData, TokenId}, }, primitives::{Amount, Id}, }; diff --git a/chainstate/src/detail/error.rs b/chainstate/src/detail/error.rs index 439d1aff47..bed24c3b65 100644 --- a/chainstate/src/detail/error.rs +++ b/chainstate/src/detail/error.rs @@ -28,11 +28,11 @@ use chainstate_storage::ChainstateStorageVersion; use chainstate_types::{GetAncestorError, PropertyQueryError}; use common::{ chain::{ + Block, GenBlock, PoolId, block::{block_body::BlockMerkleTreeError, timestamp::BlockTimestamp}, config::MagicBytes, - Block, GenBlock, PoolId, }, - primitives::{time::Time, Amount, BlockHeight, Id}, + primitives::{Amount, BlockHeight, Id, time::Time}, }; use consensus::ConsensusVerificationError; @@ -91,7 +91,9 @@ pub enum BlockError { #[error("Error querying a property: {0}")] PropertyQueryError(PropertyQueryError), - #[error("Starting from block {0} with current best {1}, failed to find a path of blocks to connect to reorg with error: {2}")] + #[error( + "Starting from block {0} with current best {1}, failed to find a path of blocks to connect to reorg with error: {2}" + )] InvariantErrorFailedToFindNewChainPath(Id, Id, PropertyQueryError), #[error("Invariant error: Attempted to connected block {0} that isn't on the tip")] InvariantErrorInvalidTip(Id), @@ -99,7 +101,9 @@ pub enum BlockError { InvariantErrorAttemptToConnectInvalidBlock(Id), #[error("Disconnected headers")] InvariantErrorDisconnectedHeaders, - #[error("Total pool {pool_id} balance {total_balance:?} is less than the staker's balance {staker_balance:?}; best block height = {best_block_height}")] + #[error( + "Total pool {pool_id} balance {total_balance:?} is less than the staker's balance {staker_balance:?}; best block height = {best_block_height}" + )] InvariantErrorTotalPoolBalanceLessThanStakers { total_balance: Amount, staker_balance: Amount, @@ -143,7 +147,9 @@ pub enum CheckBlockError { }, #[error("Block time ({0:?}) must be equal or higher than the median of its ancestors ({1:?})")] BlockTimeOrderInvalid(BlockTimestamp, BlockTimestamp), - #[error("Block {block_id} time too far into the future (block timestamp = {block_timestamp}, current time = {current_time})")] + #[error( + "Block {block_id} time too far into the future (block timestamp = {block_timestamp}, current time = {current_time})" + )] BlockFromTheFuture { block_id: Id, block_timestamp: BlockTimestamp, diff --git a/chainstate/src/detail/error_classification.rs b/chainstate/src/detail/error_classification.rs index 32e02de130..ecdde43ce8 100644 --- a/chainstate/src/detail/error_classification.rs +++ b/chainstate/src/detail/error_classification.rs @@ -14,32 +14,32 @@ // limitations under the License. use chainstate_types::{ - pos_randomness::PoSRandomnessError, storage_result, GetAncestorError, PropertyQueryError, + GetAncestorError, PropertyQueryError, pos_randomness::PoSRandomnessError, storage_result, }; use common::{ + UintConversionError, chain::{ - block::block_body::BlockMerkleTreeError, signature::DestinationSigError, IdCreationError, + IdCreationError, block::block_body::BlockMerkleTreeError, signature::DestinationSigError, }, - UintConversionError, }; use consensus::{ BlockSignatureError, ConsensusPoSError, ConsensusPoWError, ConsensusVerificationError, EffectivePoolBalanceError, }; use tx_verifier::{ + CheckTransactionError, TransactionVerifierStorageError, error::{ConnectTransactionError, SpendStakeError, TokensError}, timelock_check, - transaction_verifier::{error::SignatureDestinationGetterError, RewardDistributionError}, - CheckTransactionError, TransactionVerifierStorageError, + transaction_verifier::{RewardDistributionError, error::SignatureDestinationGetterError}, }; use utxo::UtxosBlockUndoError; use crate::{BlockError, CheckBlockError, CheckBlockTransactionsError, OrphanCheckError}; use super::{ + BlockSizeError, block_invalidation::BestChainCandidatesError, chainstateref::{EpochSealError, InMemoryReorgError}, - BlockSizeError, }; /// When handling errors during block processing, we need to differentiate between errors that diff --git a/chainstate/src/detail/info.rs b/chainstate/src/detail/info.rs index c526667e6d..581b0b1f6b 100644 --- a/chainstate/src/detail/info.rs +++ b/chainstate/src/detail/info.rs @@ -16,7 +16,7 @@ use serde::{Deserialize, Serialize}; use common::{ - chain::{block::timestamp::BlockTimestamp, GenBlock}, + chain::{GenBlock, block::timestamp::BlockTimestamp}, primitives::{BlockHeight, Id}, }; diff --git a/chainstate/src/detail/median_time.rs b/chainstate/src/detail/median_time.rs index 69e183bd92..4eb488e445 100644 --- a/chainstate/src/detail/median_time.rs +++ b/chainstate/src/detail/median_time.rs @@ -17,7 +17,7 @@ use chainstate_types::BlockIndexHandle; use itertools::Itertools; use common::{ - chain::{block::timestamp::BlockTimestamp, GenBlock}, + chain::{GenBlock, block::timestamp::BlockTimestamp}, primitives::Id, }; @@ -46,8 +46,8 @@ pub fn calculate_median_time_past_from_blocktimestamps = >::TransactionRw; @@ -461,7 +462,7 @@ impl Chainstate attempts_count, db_err, DbCommittingContext::Block(block_id), - )) + )); } Err(BlockIntegrationError::OtherNonValidationError(err)) => { return Err(err); @@ -930,7 +931,9 @@ impl Chainstate /// The error type for integrate_block. #[derive(Error, Debug, PartialEq, Eq, Clone)] enum BlockIntegrationError { - #[error("Reorg error during block integration: {0}; resulting block status is {1}; first bad block id is {2}")] + #[error( + "Reorg error during block integration: {0}; resulting block status is {1}; first bad block id is {2}" + )] ConnectBlockErrorDuringReorg(BlockError, BlockStatus, Id), #[error("Reorg error during block integration: {0}; resulting block status is {1}")] OtherReorgError(BlockError, BlockStatus), diff --git a/chainstate/src/detail/orphan_blocks/orphans_proxy.rs b/chainstate/src/detail/orphan_blocks/orphans_proxy.rs index 93b6182244..8ba91d0cb5 100644 --- a/chainstate/src/detail/orphan_blocks/orphans_proxy.rs +++ b/chainstate/src/detail/orphan_blocks/orphans_proxy.rs @@ -93,10 +93,12 @@ mod tests { fn test_orphans_proxy_control() { let orphans_proxy = OrphansProxy::new(500); assert_eq!(orphans_proxy.call(|o| o.len()).recv().unwrap(), 0); - assert!(!orphans_proxy - .call(|o| o.is_already_an_orphan(&H256::zero().into())) - .recv() - .unwrap()); + assert!( + !orphans_proxy + .call(|o| o.is_already_an_orphan(&H256::zero().into())) + .recv() + .unwrap() + ); assert_eq!( orphans_proxy .call_mut(|o| o.take_all_children_of(&H256::zero().into())) diff --git a/chainstate/src/detail/orphan_blocks/orphans_proxy_impl.rs b/chainstate/src/detail/orphan_blocks/orphans_proxy_impl.rs index 47421f0f85..d77c6ba2e4 100644 --- a/chainstate/src/detail/orphan_blocks/orphans_proxy_impl.rs +++ b/chainstate/src/detail/orphan_blocks/orphans_proxy_impl.rs @@ -15,7 +15,7 @@ use common::{ chain::{Block, GenBlock}, - primitives::{id::WithId, Id}, + primitives::{Id, id::WithId}, }; use super::{OrphanAddError, OrphanBlocksMut, OrphanBlocksRef, OrphansProxy}; diff --git a/chainstate/src/detail/orphan_blocks/orphans_refs.rs b/chainstate/src/detail/orphan_blocks/orphans_refs.rs index b317287354..843e72e735 100644 --- a/chainstate/src/detail/orphan_blocks/orphans_refs.rs +++ b/chainstate/src/detail/orphan_blocks/orphans_refs.rs @@ -16,7 +16,7 @@ use super::OrphanAddError; use common::{ chain::{Block, GenBlock}, - primitives::{id::WithId, Id}, + primitives::{Id, id::WithId}, }; pub trait OrphanBlocksRef { diff --git a/chainstate/src/detail/orphan_blocks/pool.rs b/chainstate/src/detail/orphan_blocks/pool.rs index f10c6882b7..ba165d0998 100644 --- a/chainstate/src/detail/orphan_blocks/pool.rs +++ b/chainstate/src/detail/orphan_blocks/pool.rs @@ -17,7 +17,7 @@ use std::{collections::BTreeMap, rc::Rc}; use common::{ chain::{Block, GenBlock}, - primitives::{id::WithId, Id, Idable}, + primitives::{Id, Idable, id::WithId}, }; use randomness::IndexedRandom as _; @@ -156,7 +156,7 @@ mod tests { use common::{chain::block::Block, primitives::Id}; use randomness::{Rng, RngExt as _}; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use super::*; diff --git a/chainstate/src/detail/orphan_blocks/pool_impl.rs b/chainstate/src/detail/orphan_blocks/pool_impl.rs index 10f7daec61..51a77d37b8 100644 --- a/chainstate/src/detail/orphan_blocks/pool_impl.rs +++ b/chainstate/src/detail/orphan_blocks/pool_impl.rs @@ -15,7 +15,7 @@ use common::{ chain::{Block, GenBlock}, - primitives::{id::WithId, Id}, + primitives::{Id, id::WithId}, }; use super::{OrphanAddError, OrphanBlocksMut, OrphanBlocksPool, OrphanBlocksRef}; diff --git a/chainstate/src/detail/query.rs b/chainstate/src/detail/query.rs index cdba8207be..5ee85a8ec4 100644 --- a/chainstate/src/detail/query.rs +++ b/chainstate/src/detail/query.rs @@ -22,13 +22,13 @@ use chainstate_storage::BlockchainStorageRead; use chainstate_types::{BlockIndex, GenBlockIndex, Locator, PropertyQueryError}; use common::{ chain::{ - block::{signed_block_header::SignedBlockHeader, BlockReward}, + AccountType, Block, Currency, GenBlock, OrderId, RpcOrderInfo, Transaction, TxOutput, + block::{BlockReward, signed_block_header::SignedBlockHeader}, output_value::{OutputValue, RpcOutputValue}, tokens::{ NftIssuance, RPCFungibleTokenInfo, RPCIsTokenFrozen, RPCNonFungibleTokenInfo, RPCTokenInfo, TokenAuxiliaryData, TokenId, }, - AccountType, Block, Currency, GenBlock, OrderId, RpcOrderInfo, Transaction, TxOutput, }, primitives::{Amount, BlockDistance, BlockHeight, Id, Idable}, }; diff --git a/chainstate/src/detail/test.rs b/chainstate/src/detail/test.rs index b59b2f685e..7f01ef8df6 100644 --- a/chainstate/src/detail/test.rs +++ b/chainstate/src/detail/test.rs @@ -19,17 +19,16 @@ use static_assertions::*; use chainstate_storage::inmemory::Store; use common::{ + Uint256, chain::{ - config::{Builder as ChainConfigBuilder, ChainType}, Destination, NetUpgrades, + config::{Builder as ChainConfigBuilder, ChainType}, }, - Uint256, }; use crate::{ - detail::query::locator_tip_distances, + DefaultTransactionVerificationStrategy, detail::query::locator_tip_distances, interface::chainstate_interface_impl::ChainstateInterfaceImpl, - DefaultTransactionVerificationStrategy, }; use super::*; diff --git a/chainstate/src/detail/tx_verification_strategy/default_strategy.rs b/chainstate/src/detail/tx_verification_strategy/default_strategy.rs index 3c3da64f65..bf3103f934 100644 --- a/chainstate/src/detail/tx_verification_strategy/default_strategy.rs +++ b/chainstate/src/detail/tx_verification_strategy/default_strategy.rs @@ -17,19 +17,19 @@ use super::TransactionVerificationStrategy; use crate::TransactionVerifierMakerFn; use chainstate_types::BlockIndex; use common::{ - chain::{block::timestamp::BlockTimestamp, Block, ChainConfig}, - primitives::{id::WithId, Idable}, + chain::{Block, ChainConfig, block::timestamp::BlockTimestamp}, + primitives::{Idable, id::WithId}, }; use constraints_value_accumulator::AccumulatedFee; use orders_accounting::OrdersAccountingView; use pos_accounting::PoSAccountingView; use tokens_accounting::TokensAccountingView; use tx_verifier::{ + TransactionSource, transaction_verifier::{ - error::ConnectTransactionError, storage::TransactionVerifierStorageRef, - TransactionSourceForConnect, TransactionVerifier, + TransactionSourceForConnect, TransactionVerifier, error::ConnectTransactionError, + storage::TransactionVerifierStorageRef, }, - TransactionSource, }; use utils::{shallow_clone::ShallowClone, tap_log::TapLog}; use utxo::UtxosView; diff --git a/chainstate/src/detail/tx_verification_strategy/mod.rs b/chainstate/src/detail/tx_verification_strategy/mod.rs index c793a9dcfb..4d0a1a3fef 100644 --- a/chainstate/src/detail/tx_verification_strategy/mod.rs +++ b/chainstate/src/detail/tx_verification_strategy/mod.rs @@ -18,7 +18,7 @@ pub use default_strategy::DefaultTransactionVerificationStrategy; use chainstate_types::BlockIndex; use common::{ - chain::{block::timestamp::BlockTimestamp, Block, ChainConfig}, + chain::{Block, ChainConfig, block::timestamp::BlockTimestamp}, primitives::id::WithId, }; use orders_accounting::OrdersAccountingView; @@ -27,8 +27,8 @@ use tokens_accounting::TokensAccountingView; use tx_verifier::{ error::ConnectTransactionError, transaction_verifier::{ - storage::{TransactionVerifierStorageError, TransactionVerifierStorageRef}, TransactionVerifier, + storage::{TransactionVerifierStorageError, TransactionVerifierStorageRef}, }, }; use utils::shallow_clone::ShallowClone; diff --git a/chainstate/src/interface/chainstate_interface.rs b/chainstate/src/interface/chainstate_interface.rs index 88393c931b..82153ea0be 100644 --- a/chainstate/src/interface/chainstate_interface.rs +++ b/chainstate/src/interface/chainstate_interface.rs @@ -20,19 +20,19 @@ use std::{ }; use crate::{ - detail::BlockSource, ChainInfo, ChainstateConfig, ChainstateError, ChainstateEvent, - NonZeroPoolBalances, + ChainInfo, ChainstateConfig, ChainstateError, ChainstateEvent, NonZeroPoolBalances, + detail::BlockSource, }; use chainstate_types::{BlockIndex, EpochData, GenBlockIndex, Locator}; use common::{ chain::{ + AccountNonce, AccountType, ChainConfig, Currency, DelegationId, OrderId, PoolId, + RpcOrderInfo, Transaction, TxInput, UtxoOutPoint, block::{ - signed_block_header::SignedBlockHeader, timestamp::BlockTimestamp, Block, BlockReward, - GenBlock, + Block, BlockReward, GenBlock, signed_block_header::SignedBlockHeader, + timestamp::BlockTimestamp, }, tokens::{RPCTokenInfo, TokenAuxiliaryData, TokenId}, - AccountNonce, AccountType, ChainConfig, Currency, DelegationId, OrderId, PoolId, - RpcOrderInfo, Transaction, TxInput, UtxoOutPoint, }, primitives::{Amount, BlockHeight, Id}, }; @@ -236,7 +236,7 @@ pub trait ChainstateInterface: Send + Sync { id: &TokenId, ) -> Result, ChainstateError>; fn get_token_circulating_supply(&self, id: &TokenId) - -> Result, ChainstateError>; + -> Result, ChainstateError>; fn get_order_data(&self, id: &OrderId) -> Result, ChainstateError>; fn get_order_ask_balance(&self, id: &OrderId) -> Result, ChainstateError>; diff --git a/chainstate/src/interface/chainstate_interface_impl.rs b/chainstate/src/interface/chainstate_interface_impl.rs index a318132f4f..887721ff72 100644 --- a/chainstate/src/interface/chainstate_interface_impl.rs +++ b/chainstate/src/interface/chainstate_interface_impl.rs @@ -20,25 +20,25 @@ use std::{ }; use crate::{ + ChainInfo, ChainstateConfig, ChainstateError, ChainstateEvent, ChainstateInterface, Locator, + NonZeroPoolBalances, detail::{ - self, block_checking::BlockChecker, bootstrap::export_bootstrap_stream, + self, BlockSource, CHAINSTATE_TRACING_TARGET_VERBOSE_BLOCK_IDS, OrphanBlocksRef, + block_checking::BlockChecker, bootstrap::export_bootstrap_stream, calculate_median_time_past, tx_verification_strategy::TransactionVerificationStrategy, - BlockSource, OrphanBlocksRef, CHAINSTATE_TRACING_TARGET_VERBOSE_BLOCK_IDS, }, - ChainInfo, ChainstateConfig, ChainstateError, ChainstateEvent, ChainstateInterface, Locator, - NonZeroPoolBalances, }; use chainstate_storage::BlockchainStorage; use chainstate_types::{BlockIndex, EpochData, GenBlockIndex, PropertyQueryError}; use common::{ chain::{ - block::{signed_block_header::SignedBlockHeader, Block, BlockReward, GenBlock}, - config::ChainConfig, - tokens::{RPCTokenInfo, TokenAuxiliaryData, TokenId}, AccountNonce, AccountType, Currency, DelegationId, OrderId, PoolId, RpcOrderInfo, Transaction, TxInput, TxOutput, UtxoOutPoint, + block::{Block, BlockReward, GenBlock, signed_block_header::SignedBlockHeader}, + config::ChainConfig, + tokens::{RPCTokenInfo, TokenAuxiliaryData, TokenId}, }, - primitives::{id::WithId, Amount, BlockHeight, Id, Idable}, + primitives::{Amount, BlockHeight, Id, Idable, id::WithId}, }; use orders_accounting::OrderData; use pos_accounting::{DelegationData, PoSAccountingStorageRead, PoolData}; diff --git a/chainstate/src/interface/chainstate_interface_impl_delegation.rs b/chainstate/src/interface/chainstate_interface_impl_delegation.rs index 6df741e3d3..d855c48503 100644 --- a/chainstate/src/interface/chainstate_interface_impl_delegation.rs +++ b/chainstate/src/interface/chainstate_interface_impl_delegation.rs @@ -23,11 +23,11 @@ use std::{ use chainstate_types::{BlockIndex, EpochData, GenBlockIndex, Locator}; use common::{ chain::{ - block::{signed_block_header::SignedBlockHeader, timestamp::BlockTimestamp, BlockReward}, - config::ChainConfig, - tokens::{RPCTokenInfo, TokenAuxiliaryData, TokenId}, AccountNonce, AccountType, Block, Currency, DelegationId, GenBlock, OrderId, PoolId, RpcOrderInfo, Transaction, TxInput, UtxoOutPoint, + block::{BlockReward, signed_block_header::SignedBlockHeader, timestamp::BlockTimestamp}, + config::ChainConfig, + tokens::{RPCTokenInfo, TokenAuxiliaryData, TokenId}, }, primitives::{Amount, BlockHeight, Id}, }; @@ -38,8 +38,8 @@ use utils_networking::broadcaster; use utxo::Utxo; use crate::{ - chainstate_interface::ChainstateInterface, BlockSource, ChainInfo, ChainstateConfig, - ChainstateError, ChainstateEvent, NonZeroPoolBalances, + BlockSource, ChainInfo, ChainstateConfig, ChainstateError, ChainstateEvent, + NonZeroPoolBalances, chainstate_interface::ChainstateInterface, }; impl ChainstateInterface for T @@ -460,14 +460,14 @@ mod tests { use chainstate_storage::inmemory::Store; use common::{ - chain::{config::create_unit_test_config, ChainConfig}, + chain::{ChainConfig, config::create_unit_test_config}, primitives::BlockHeight, time_getter::TimeGetter, }; use crate::{ - chainstate_interface::ChainstateInterface, make_chainstate, ChainstateConfig, - DefaultTransactionVerificationStrategy, + ChainstateConfig, DefaultTransactionVerificationStrategy, + chainstate_interface::ChainstateInterface, make_chainstate, }; fn test_interface_ref(chainstate: &C, chain_config: &ChainConfig) { diff --git a/chainstate/src/lib.rs b/chainstate/src/lib.rs index 1d8fc86b29..43322e41bf 100644 --- a/chainstate/src/lib.rs +++ b/chainstate/src/lib.rs @@ -37,13 +37,13 @@ use crate::{detail::Chainstate, interface::chainstate_interface_impl}; pub use crate::{ config::{ChainstateConfig, MaxTipAge}, detail::{ - ban_score, block_invalidation::BlockInvalidatorError, bootstrap::BootstrapError, - calculate_median_time_past, calculate_median_time_past_from_blocktimestamps, BlockError, - BlockProcessingErrorClass, BlockProcessingErrorClassification, BlockSource, ChainInfo, - CheckBlockError, CheckBlockTransactionsError, ConnectTransactionError, IOPolicyError, - InitializationError, Locator, NonZeroPoolBalances, OrphanCheckError, SpendStakeError, - StorageCompatibilityCheckError, TokenIssuanceError, TokensError, - TransactionVerifierStorageError, MEDIAN_TIME_SPAN, + BlockError, BlockProcessingErrorClass, BlockProcessingErrorClassification, BlockSource, + ChainInfo, CheckBlockError, CheckBlockTransactionsError, ConnectTransactionError, + IOPolicyError, InitializationError, Locator, MEDIAN_TIME_SPAN, NonZeroPoolBalances, + OrphanCheckError, SpendStakeError, StorageCompatibilityCheckError, TokenIssuanceError, + TokensError, TransactionVerifierStorageError, ban_score, + block_invalidation::BlockInvalidatorError, bootstrap::BootstrapError, + calculate_median_time_past, calculate_median_time_past_from_blocktimestamps, }, }; pub use chainstate_types::{BlockIndex, GenBlockIndex, GenBlockIndexRef, PropertyQueryError}; diff --git a/chainstate/src/rpc/mod.rs b/chainstate/src/rpc/mod.rs index 30c7182fcd..9bba366f07 100644 --- a/chainstate/src/rpc/mod.rs +++ b/chainstate/src/rpc/mod.rs @@ -21,31 +21,31 @@ use std::{collections::BTreeMap, convert::Infallible, num::NonZeroUsize, sync::A use chainstate_types::BlockIndex; use common::{ - address::{dehexify::to_dehexified_json, Address, RpcAddress}, + TokenDecimals, + address::{Address, RpcAddress, dehexify::to_dehexified_json}, chain::{ - output_values_holder::collect_token_v1_ids_from_output_values_holder, - tokens::{RPCTokenInfo, TokenId}, ChainConfig, DelegationId, Destination, OrderId, PoolId, RpcCurrency, RpcOrderInfo, TxOutput, + output_values_holder::collect_token_v1_ids_from_output_values_holder, + tokens::{RPCTokenInfo, TokenId}, }, primitives::{Amount, BlockHeight, Id}, - TokenDecimals, }; -use rpc::{subscription, RpcResult}; +use rpc::{RpcResult, subscription}; use serialization::hex_encoded::HexEncoded; use crate::{ - chainstate_interface::ChainstateInterface, export_bootstrap_file, import_bootstrap_file, Block, - BlockSource, ChainInfo, ChainstateError, GenBlock, + Block, BlockSource, ChainInfo, ChainstateError, GenBlock, + chainstate_interface::ChainstateInterface, export_bootstrap_file, import_bootstrap_file, }; use self::types::{block::RpcBlock, event::RpcEvent}; pub use types::{ + RpcTypeError, input::RpcUtxoOutpoint, output::{RpcOutputValueIn, RpcOutputValueOut, RpcTxOutput}, signed_transaction::RpcSignedTransaction, - RpcTypeError, }; #[rpc::describe] diff --git a/chainstate/src/rpc/types/account.rs b/chainstate/src/rpc/types/account.rs index a9ff73ba0b..8fec273b08 100644 --- a/chainstate/src/rpc/types/account.rs +++ b/chainstate/src/rpc/types/account.rs @@ -16,9 +16,9 @@ use common::{ address::RpcAddress, chain::{ - tokens::{IsTokenUnfreezable, TokenId}, AccountCommand, AccountSpending, ChainConfig, DelegationId, Destination, OrderAccountCommand, OrderId, + tokens::{IsTokenUnfreezable, TokenId}, }, primitives::amount::RpcAmountOut, }; diff --git a/chainstate/src/rpc/types/block.rs b/chainstate/src/rpc/types/block.rs index 09d605be50..eed7dec78c 100644 --- a/chainstate/src/rpc/types/block.rs +++ b/chainstate/src/rpc/types/block.rs @@ -15,15 +15,15 @@ use chainstate_types::BlockIndex; use common::{ - chain::{block::timestamp::BlockTimestamp, Block, ChainConfig, GenBlock}, - primitives::{BlockHeight, Id, Idable}, TokenDecimalsProvider, + chain::{Block, ChainConfig, GenBlock, block::timestamp::BlockTimestamp}, + primitives::{BlockHeight, Id, Idable}, }; use serialization::hex_encoded::HexEncoded; use super::{ - block_reward::RpcBlockReward, consensus_data::RpcConsensusData, - signed_transaction::RpcSignedTransaction, RpcTypeError, + RpcTypeError, block_reward::RpcBlockReward, consensus_data::RpcConsensusData, + signed_transaction::RpcSignedTransaction, }; #[derive(Debug, Clone, serde::Serialize)] diff --git a/chainstate/src/rpc/types/block_reward.rs b/chainstate/src/rpc/types/block_reward.rs index 84c46c2035..9d86071989 100644 --- a/chainstate/src/rpc/types/block_reward.rs +++ b/chainstate/src/rpc/types/block_reward.rs @@ -14,11 +14,11 @@ // limitations under the License. use common::{ - chain::{block::BlockReward, ChainConfig}, TokenDecimalsProvider, + chain::{ChainConfig, block::BlockReward}, }; -use super::{output::RpcTxOutput, RpcTypeError}; +use super::{RpcTypeError, output::RpcTxOutput}; #[derive(Debug, Clone, serde::Serialize)] pub struct RpcBlockReward { diff --git a/chainstate/src/rpc/types/consensus_data.rs b/chainstate/src/rpc/types/consensus_data.rs index 13585853a1..112f0eb97c 100644 --- a/chainstate/src/rpc/types/consensus_data.rs +++ b/chainstate/src/rpc/types/consensus_data.rs @@ -15,11 +15,11 @@ use common::{ address::RpcAddress, - chain::{block::ConsensusData, ChainConfig, PoolId}, + chain::{ChainConfig, PoolId, block::ConsensusData}, }; use rpc::types::RpcHexString; -use super::{input::RpcTxInput, RpcTypeError}; +use super::{RpcTypeError, input::RpcTxInput}; #[derive(Debug, Clone, serde::Serialize)] #[serde(tag = "type", content = "content")] diff --git a/chainstate/src/rpc/types/input.rs b/chainstate/src/rpc/types/input.rs index 3019f4b4b1..d48a3baf9d 100644 --- a/chainstate/src/rpc/types/input.rs +++ b/chainstate/src/rpc/types/input.rs @@ -19,8 +19,8 @@ use common::{ }; use super::{ - account::{RpcAccountCommand, RpcAccountSpending, RpcOrderAccountCommand}, RpcTypeError, + account::{RpcAccountCommand, RpcAccountSpending, RpcOrderAccountCommand}, }; #[derive(Debug, Clone, serde::Serialize, rpc_description::HasValueHint)] diff --git a/chainstate/src/rpc/types/mod.rs b/chainstate/src/rpc/types/mod.rs index a7aacace6c..4c71cfc0e6 100644 --- a/chainstate/src/rpc/types/mod.rs +++ b/chainstate/src/rpc/types/mod.rs @@ -23,7 +23,7 @@ pub mod output; pub mod signed_transaction; pub mod token; -use common::{address::AddressError, TokenDecimalsUnavailableError}; +use common::{TokenDecimalsUnavailableError, address::AddressError}; #[derive(thiserror::Error, Debug)] pub enum RpcTypeError { diff --git a/chainstate/src/rpc/types/output.rs b/chainstate/src/rpc/types/output.rs index 33e69395c7..4d02c4ec2d 100644 --- a/chainstate/src/rpc/types/output.rs +++ b/chainstate/src/rpc/types/output.rs @@ -14,21 +14,21 @@ // limitations under the License. use common::{ + TokenDecimalsProvider, address::RpcAddress, chain::{ - htlc::HashedTimelockContract, output_value::OutputValue, stakelock::StakePoolData, - timelock::OutputTimeLock, tokens::TokenId, ChainConfig, DelegationId, Destination, PoolId, - TxOutput, + ChainConfig, DelegationId, Destination, PoolId, TxOutput, htlc::HashedTimelockContract, + output_value::OutputValue, stakelock::StakePoolData, timelock::OutputTimeLock, + tokens::TokenId, }, primitives::amount::{RpcAmountIn, RpcAmountOut}, - TokenDecimalsProvider, }; use crypto::vrf::VRFPublicKey; use rpc::types::RpcHexString; use super::{ - token::{RpcNftIssuance, RpcTokenIssuance}, RpcTypeError, + token::{RpcNftIssuance, RpcTokenIssuance}, }; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, rpc_description::HasValueHint)] diff --git a/chainstate/src/rpc/types/signed_transaction.rs b/chainstate/src/rpc/types/signed_transaction.rs index be30a4549b..e51e2809b7 100644 --- a/chainstate/src/rpc/types/signed_transaction.rs +++ b/chainstate/src/rpc/types/signed_transaction.rs @@ -14,13 +14,13 @@ // limitations under the License. use common::{ + TokenDecimalsProvider, chain::{ChainConfig, SignedTransaction, Transaction}, primitives::{Id, Idable}, - TokenDecimalsProvider, }; use serialization::hex_encoded::HexEncoded; -use super::{input::RpcTxInput, output::RpcTxOutput, RpcTypeError}; +use super::{RpcTypeError, input::RpcTxInput, output::RpcTxOutput}; #[derive(Debug, Clone, serde::Serialize, rpc_description::HasValueHint)] pub struct RpcSignedTransaction { diff --git a/chainstate/src/rpc/types/token.rs b/chainstate/src/rpc/types/token.rs index 3d4bbba48d..94b5ec733a 100644 --- a/chainstate/src/rpc/types/token.rs +++ b/chainstate/src/rpc/types/token.rs @@ -16,8 +16,8 @@ use common::{ address::RpcAddress, chain::{ - tokens::{IsTokenFreezable, NftIssuance, TokenIssuance, TokenTotalSupply}, ChainConfig, Destination, + tokens::{IsTokenFreezable, NftIssuance, TokenIssuance, TokenTotalSupply}, }, primitives::amount::RpcAmountOut, }; diff --git a/chainstate/storage/src/internal/mod.rs b/chainstate/storage/src/internal/mod.rs index 6cc95aec3c..c071327ffb 100644 --- a/chainstate/storage/src/internal/mod.rs +++ b/chainstate/storage/src/internal/mod.rs @@ -33,7 +33,7 @@ use pos_accounting::{ use utils::log_error; use crate::{ - schema::Schema, BlockchainStorageRead, BlockchainStorageWrite, TransactionRw, Transactional, + BlockchainStorageRead, BlockchainStorageWrite, TransactionRw, Transactional, schema::Schema, }; pub use blockchain_storage::{ diff --git a/chainstate/storage/src/internal/store_tx/mod.rs b/chainstate/storage/src/internal/store_tx/mod.rs index 046f1db4a9..6a46ba478e 100644 --- a/chainstate/storage/src/internal/store_tx/mod.rs +++ b/chainstate/storage/src/internal/store_tx/mod.rs @@ -18,11 +18,11 @@ mod write_impls; use common::primitives::{BlockHeight, Id}; use serialization::{Codec, DecodeAll, Encode, EncodeLike}; -use storage::{schema, MakeMapRef}; +use storage::{MakeMapRef, schema}; use crate::{ - schema::{self as db, Schema}, ChainstateStorageVersion, + schema::{self as db, Schema}, }; mod well_known { diff --git a/chainstate/storage/src/internal/store_tx/read_impls.rs b/chainstate/storage/src/internal/store_tx/read_impls.rs index 90b8a8a650..dd9cf5dd6c 100644 --- a/chainstate/storage/src/internal/store_tx/read_impls.rs +++ b/chainstate/storage/src/internal/store_tx/read_impls.rs @@ -19,13 +19,13 @@ use super::db; use chainstate_types::{BlockIndex, EpochData, EpochStorageRead, SealedStorageTag, TipStorageTag}; use common::{ chain::{ - block::{signed_block_header::SignedBlockHeader, BlockReward}, - config::{EpochIndex, MagicBytes}, - tokens::{TokenAuxiliaryData, TokenId}, AccountNonce, AccountType, Block, DelegationId, GenBlock, OrderId, PoolId, Transaction, UtxoOutPoint, + block::{BlockReward, signed_block_header::SignedBlockHeader}, + config::{EpochIndex, MagicBytes}, + tokens::{TokenAuxiliaryData, TokenId}, }, - primitives::{Amount, BlockHeight, Id, H256}, + primitives::{Amount, BlockHeight, H256, Id}, }; use orders_accounting::{OrderData, OrdersAccountingStorageRead, OrdersAccountingUndo}; use pos_accounting::{ diff --git a/chainstate/storage/src/internal/store_tx/write_impls.rs b/chainstate/storage/src/internal/store_tx/write_impls.rs index 8704d47d57..b5c734e59b 100644 --- a/chainstate/storage/src/internal/store_tx/write_impls.rs +++ b/chainstate/storage/src/internal/store_tx/write_impls.rs @@ -13,15 +13,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::{well_known, StoreTxRw}; +use super::{StoreTxRw, well_known}; use crate::{BlockchainStorageWrite, ChainstateStorageVersion, SealedStorageTag, TipStorageTag}; use chainstate_types::{BlockIndex, EpochData, EpochStorageWrite}; use common::{ chain::{ - config::{EpochIndex, MagicBytes}, - tokens::{TokenAuxiliaryData, TokenId}, AccountNonce, AccountType, Block, DelegationId, GenBlock, OrderId, PoolId, Transaction, UtxoOutPoint, + config::{EpochIndex, MagicBytes}, + tokens::{TokenAuxiliaryData, TokenId}, }, primitives::{Amount, BlockHeight, Id, Idable}, }; diff --git a/chainstate/storage/src/internal/test.rs b/chainstate/storage/src/internal/test.rs index 0e117a1d45..dc21cc78b6 100644 --- a/chainstate/storage/src/internal/test.rs +++ b/chainstate/storage/src/internal/test.rs @@ -18,12 +18,12 @@ use common::chain::output_value::OutputValue; use common::chain::transaction::signed_transaction::SignedTransaction; use common::chain::{Block, Destination, OutPointSourceId, TxOutput, UtxoOutPoint}; use common::primitives::Id; -use common::primitives::{Amount, BlockHeight, Idable, H256}; +use common::primitives::{Amount, BlockHeight, H256, Idable}; use crypto::key::{KeyKind, PrivateKey}; use randomness::{CryptoRng, RngExt as _}; use rstest::rstest; use serialization::Encode; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use utxo::{ Utxo, UtxosBlockRewardUndo, UtxosBlockUndo, UtxosStorageRead, UtxosStorageWrite, UtxosTxUndoWithSources, @@ -58,10 +58,10 @@ fn assert_no_block(db_tx: &DbTx, block_id: Id crate::Result>; + -> crate::Result>; /// Get all keys (block ids) from the block map. This is used in the chainstate's /// "heavy" consistency checks. @@ -276,7 +276,7 @@ pub trait BlockchainStorageWrite: fn del_accounting_epoch_undo_delta(&mut self, epoch_index: EpochIndex) -> Result<()>; fn set_account_nonce_count(&mut self, account: &AccountType, nonce: AccountNonce) - -> Result<()>; + -> Result<()>; fn del_account_nonce_count(&mut self, account: &AccountType) -> Result<()>; } diff --git a/chainstate/storage/src/mock/mock_impl.rs b/chainstate/storage/src/mock/mock_impl.rs index 2ba535aa4a..40426af7ff 100644 --- a/chainstate/storage/src/mock/mock_impl.rs +++ b/chainstate/storage/src/mock/mock_impl.rs @@ -20,11 +20,11 @@ use std::collections::{BTreeMap, BTreeSet}; use chainstate_types::{BlockIndex, EpochData, EpochStorageRead, EpochStorageWrite}; use common::{ chain::{ - block::{signed_block_header::SignedBlockHeader, BlockReward}, + AccountNonce, AccountType, Block, DelegationId, GenBlock, OrderId, PoolId, UtxoOutPoint, + block::{BlockReward, signed_block_header::SignedBlockHeader}, config::{EpochIndex, MagicBytes}, tokens::{TokenAuxiliaryData, TokenId}, transaction::Transaction, - AccountNonce, AccountType, Block, DelegationId, GenBlock, OrderId, PoolId, UtxoOutPoint, }, primitives::{Amount, BlockHeight, Id}, }; diff --git a/chainstate/storage/src/mock/tests.rs b/chainstate/storage/src/mock/tests.rs index 5a1d7bdf29..f1c0839c52 100644 --- a/chainstate/storage/src/mock/tests.rs +++ b/chainstate/storage/src/mock/tests.rs @@ -19,9 +19,9 @@ use crate::{ TransactionRw, Transactional, }; use common::{ - chain::block::{timestamp::BlockTimestamp, BlockReward, ConsensusData}, - chain::{signed_transaction::SignedTransaction, transaction::Transaction, Block, GenBlock}, - primitives::{Id, Idable, H256}, + chain::block::{BlockReward, ConsensusData, timestamp::BlockTimestamp}, + chain::{Block, GenBlock, signed_transaction::SignedTransaction, transaction::Transaction}, + primitives::{H256, Id, Idable}, }; type TestStore = crate::inmemory::Store; diff --git a/chainstate/storage/src/schema.rs b/chainstate/storage/src/schema.rs index 04f80c05ec..c8d6275ed7 100644 --- a/chainstate/storage/src/schema.rs +++ b/chainstate/storage/src/schema.rs @@ -18,10 +18,10 @@ use chainstate_types::{BlockIndex, EpochData}; use common::{ chain::{ - config::EpochIndex, - tokens::{TokenAuxiliaryData, TokenId}, AccountNonce, AccountType, Block, DelegationId, GenBlock, OrderId, PoolId, Transaction, UtxoOutPoint, + config::EpochIndex, + tokens::{TokenAuxiliaryData, TokenId}, }, primitives::{Amount, BlockHeight, Id}, }; diff --git a/chainstate/test-framework/src/block_builder.rs b/chainstate/test-framework/src/block_builder.rs index 2d04d9d2be..898ad36ce6 100644 --- a/chainstate/test-framework/src/block_builder.rs +++ b/chainstate/test-framework/src/block_builder.rs @@ -15,25 +15,25 @@ use std::collections::{BTreeMap, BTreeSet}; +use crate::TestFramework; use crate::framework::BlockOutputs; use crate::signature_destination_getter::SignatureDestinationGetter; use crate::utils::{create_new_outputs, outputs_from_block, sign_witnesses}; -use crate::TestFramework; use chainstate::{BlockSource, ChainstateError}; use chainstate_storage::{BlockchainStorageRead, Transactional}; use chainstate_types::BlockIndex; +use common::chain::block::BlockHeader; use common::chain::block::block_body::BlockBody; use common::chain::block::signed_block_header::{BlockHeaderSignature, BlockHeaderSignatureData}; -use common::chain::block::BlockHeader; use common::chain::{AccountNonce, AccountType, OutPointSourceId, UtxoOutPoint}; use common::{ chain::{ - block::{timestamp::BlockTimestamp, BlockReward, ConsensusData}, + Block, GenBlock, Transaction, TxInput, TxOutput, + block::{BlockReward, ConsensusData, timestamp::BlockTimestamp}, signature::inputsig::InputWitness, signed_transaction::SignedTransaction, - Block, GenBlock, Transaction, TxInput, TxOutput, }, - primitives::{Id, H256}, + primitives::{H256, Id}, }; use crypto::key::PrivateKey; use itertools::Itertools; diff --git a/chainstate/test-framework/src/framework.rs b/chainstate/test-framework/src/framework.rs index ff85a6726e..2a125e0c77 100644 --- a/chainstate/test-framework/src/framework.rs +++ b/chainstate/test-framework/src/framework.rs @@ -17,21 +17,21 @@ use std::{collections::BTreeMap, sync::Arc}; use rstest::rstest; -use chainstate::{chainstate_interface::ChainstateInterface, BlockSource, ChainstateError}; +use chainstate::{BlockSource, ChainstateError, chainstate_interface::ChainstateInterface}; use chainstate_storage::{ BlockchainStorageRead, BlockchainStorageWrite, TransactionRw, Transactional, }; use chainstate_types::{ - pos_randomness::PoSRandomness, BlockIndex, BlockStatus, EpochStorageRead as _, GenBlockIndex, - TipStorageTag, + BlockIndex, BlockStatus, EpochStorageRead as _, GenBlockIndex, TipStorageTag, + pos_randomness::PoSRandomness, }; use common::{ chain::{ - signature::sighash::{self, input_commitments::SighashInputCommitment}, Block, ChainConfig, GenBlock, GenBlockId, Genesis, OutPointSourceId, PoolId, TxInput, TxOutput, UtxoOutPoint, + signature::sighash::{self, input_commitments::SighashInputCommitment}, }, - primitives::{id::WithId, time::Time, Amount, BlockHeight, Id, Idable}, + primitives::{Amount, BlockHeight, Id, Idable, id::WithId, time::Time}, time_getter::TimeGetter, }; use crypto::{key::PrivateKey, vrf::VRFPrivateKey}; @@ -42,6 +42,7 @@ use utils::atomics::SeqCstAtomicU64; use utxo::{Utxo, UtxosDB}; use crate::{ + BlockBuilder, TestChainstate, TestFrameworkBuilder, TestStore, TxVerificationStrategy, framework_builder::TestFrameworkBuilderValue, get_output_value, key_manager::KeyManager, @@ -49,11 +50,10 @@ use crate::{ random_tx_maker::StakingPoolsObserver, staking_pools::StakingPools, utils::{ - assert_block_index_opt_identical_to, assert_gen_block_index_identical_to, - assert_gen_block_index_opt_identical_to, find_create_pool_tx_in_genesis, - outputs_from_block, outputs_from_genesis, SighashInputCommitmentInfoProvider, + SighashInputCommitmentInfoProvider, assert_block_index_opt_identical_to, + assert_gen_block_index_identical_to, assert_gen_block_index_opt_identical_to, + find_create_pool_tx_in_genesis, outputs_from_block, outputs_from_genesis, }, - BlockBuilder, TestChainstate, TestFrameworkBuilder, TestStore, TxVerificationStrategy, }; /// The `Chainstate` wrapper that simplifies operations and checks in the tests. @@ -714,8 +714,8 @@ impl TestFramework { fn build_test_framework(#[case] seed: test_utils::random::Seed) { use chainstate::ChainstateConfig; use common::chain::{ - config::{Builder as ChainConfigBuilder, ChainType}, Destination, NetUpgrades, + config::{Builder as ChainConfigBuilder, ChainType}, }; use common::time_getter::TimeGetter; let chain_type = ChainType::Mainnet; @@ -753,8 +753,8 @@ fn process_block(#[case] seed: test_utils::random::Seed) { use crate::TransactionBuilder; use common::{ chain::{ - output_value::OutputValue, signature::inputsig::InputWitness, Destination, GenBlock, - OutPointSourceId, TxInput, TxOutput, + Destination, GenBlock, OutPointSourceId, TxInput, TxOutput, output_value::OutputValue, + signature::inputsig::InputWitness, }, primitives::{Amount, Id, Idable}, }; diff --git a/chainstate/test-framework/src/framework_builder.rs b/chainstate/test-framework/src/framework_builder.rs index f76d8cf8c6..f676ca9760 100644 --- a/chainstate/test-framework/src/framework_builder.rs +++ b/chainstate/test-framework/src/framework_builder.rs @@ -19,12 +19,12 @@ use std::{ }; use crate::{ + TestFramework, TestStore, key_manager::KeyManager, staking_pools::StakingPools, tx_verification_strategy::{ DisposableTransactionVerificationStrategy, RandomizedTransactionVerificationStrategy, }, - TestFramework, TestStore, }; use chainstate::{BlockError, ChainstateConfig, DefaultTransactionVerificationStrategy}; use common::{ diff --git a/chainstate/test-framework/src/helpers.rs b/chainstate/test-framework/src/helpers.rs index 3e9636d836..8701235c68 100644 --- a/chainstate/test-framework/src/helpers.rs +++ b/chainstate/test-framework/src/helpers.rs @@ -17,12 +17,11 @@ use chainstate::BlockSource; use chainstate_storage::{BlockchainStorageRead, Transactional}; use common::{ chain::{ - make_token_id, + AccountCommand, AccountNonce, AccountType, Block, Destination, GenBlock, OrderId, + OrdersVersion, Transaction, TxInput, TxOutput, UtxoOutPoint, make_token_id, output_value::OutputValue, signature::inputsig::InputWitness, tokens::{IsTokenFreezable, TokenId, TokenIssuance, TokenIssuanceV1, TokenTotalSupply}, - AccountCommand, AccountNonce, AccountType, Block, Destination, GenBlock, OrderId, - OrdersVersion, Transaction, TxInput, TxOutput, UtxoOutPoint, }, primitives::{Amount, BlockHeight, Id, Idable}, }; @@ -30,7 +29,7 @@ use orders_accounting::{OrdersAccountingDB, OrdersAccountingView as _}; use randomness::{CryptoRng, Rng, RngExt as _, SliceRandom as _}; use test_utils::{random_ascii_alphanumeric_string, token_utils::random_nft_issuance}; -use crate::{get_output_value, TestFramework, TransactionBuilder}; +use crate::{TestFramework, TransactionBuilder, get_output_value}; // Note: this function will create 2 blocks pub fn issue_and_mint_random_token_from_best_block( diff --git a/chainstate/test-framework/src/key_manager.rs b/chainstate/test-framework/src/key_manager.rs index b79737a8d1..cb777ef263 100644 --- a/chainstate/test-framework/src/key_manager.rs +++ b/chainstate/test-framework/src/key_manager.rs @@ -19,22 +19,22 @@ use std::{collections::BTreeMap, num::NonZeroU8}; use common::{ address::pubkeyhash::PublicKeyHash, chain::{ + ChainConfig, Destination, Transaction, TxOutput, classic_multisig::ClassicMultisigChallenge, signature::{ inputsig::{ + InputWitness, classical_multisig::authorize_classical_multisig::{ - sign_classical_multisig_spending, AuthorizedClassicalMultisigSpend, - ClassicalMultisigCompletionStatus, + AuthorizedClassicalMultisigSpend, ClassicalMultisigCompletionStatus, + sign_classical_multisig_spending, }, htlc::produce_classical_multisig_signature_for_htlc_refunding, standard_signature::StandardInputSignature, - InputWitness, }, sighash::{ input_commitments::SighashInputCommitment, sighashtype::SigHashType, signature_hash, }, }, - ChainConfig, Destination, Transaction, TxOutput, }, }; use crypto::key::{KeyKind, PrivateKey, PublicKey}; diff --git a/chainstate/test-framework/src/pos_block_builder.rs b/chainstate/test-framework/src/pos_block_builder.rs index ad31dc515a..611f84d245 100644 --- a/chainstate/test-framework/src/pos_block_builder.rs +++ b/chainstate/test-framework/src/pos_block_builder.rs @@ -16,30 +16,30 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::{ + TestFramework, random_tx_maker::StakingPoolsObserver, signature_destination_getter::SignatureDestinationGetter, utils::{ calculate_new_pos_compact_target, find_create_pool_tx_in_genesis, get_pos_status, pos_mine, produce_kernel_signature, sign_witnesses, }, - TestFramework, }; use chainstate::{BlockSource, ChainstateError}; use chainstate_storage::{BlockchainStorageRead, Transactional}; -use chainstate_types::{pos_randomness::PoSRandomness, BlockIndex}; +use chainstate_types::{BlockIndex, pos_randomness::PoSRandomness}; use common::{ chain::{ + AccountNonce, AccountType, Block, Destination, GenBlock, PoolId, TxInput, TxOutput, + UtxoOutPoint, block::{ + BlockHeader, BlockReward, ConsensusData, block_body::BlockBody, consensus_data::PoSData, signed_block_header::{BlockHeaderSignature, BlockHeaderSignatureData}, timestamp::BlockTimestamp, - BlockHeader, BlockReward, ConsensusData, }, signature::inputsig::InputWitness, signed_transaction::SignedTransaction, - AccountNonce, AccountType, Block, Destination, GenBlock, PoolId, TxInput, TxOutput, - UtxoOutPoint, }, primitives::{Id, Idable}, }; @@ -49,7 +49,7 @@ use crypto::{ }; use orders_accounting::{InMemoryOrdersAccounting, OrdersAccountingDB}; use pos_accounting::{InMemoryPoSAccounting, PoSAccountingDB}; -use randomness::{seq::IteratorRandom, CryptoRng, Rng, RngExt as _}; +use randomness::{CryptoRng, Rng, RngExt as _, seq::IteratorRandom}; use serialization::Encode; use tokens_accounting::{InMemoryTokensAccounting, TokensAccountingDB}; diff --git a/chainstate/test-framework/src/random_tx_maker.rs b/chainstate/test-framework/src/random_tx_maker.rs index e5cd3f725d..296f9975ca 100644 --- a/chainstate/test-framework/src/random_tx_maker.rs +++ b/chainstate/test-framework/src/random_tx_maker.rs @@ -16,25 +16,25 @@ use std::collections::BTreeMap; use crate::{ + TestChainstate, key_manager::KeyManager, utils::{output_value_amount, output_value_with_amount}, - TestChainstate, }; use chainstate::chainstate_interface::ChainstateInterface; use common::{ chain::{ + AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, AccountType, DelegationId, + Destination, GenBlockId, OrderAccountCommand, OrderData, OrderId, OrdersVersion, + OutPointSourceId, PoolId, Transaction, TxInput, TxOutput, UtxoOutPoint, htlc::{HashedTimelockContract, HtlcSecretHash}, make_delegation_id, make_order_id, make_pool_id, make_token_id, output_value::OutputValue, stakelock::StakePoolData, timelock::OutputTimeLock, tokens::{IsTokenUnfreezable, NftIssuance, TokenId, TokenIssuance, TokenTotalSupply}, - AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, AccountType, DelegationId, - Destination, GenBlockId, OrderAccountCommand, OrderData, OrderId, OrdersVersion, - OutPointSourceId, PoolId, Transaction, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight, CoinOrTokenId, Id, Idable, H256}, + primitives::{Amount, BlockHeight, CoinOrTokenId, H256, Id, Idable, per_thousand::PerThousand}, }; use crypto::{ key::{KeyKind, PrivateKey}, @@ -49,7 +49,7 @@ use pos_accounting::{ PoSAccountingDeltaData, PoSAccountingOperations, PoSAccountingUndo, PoSAccountingView, PoolData, }; -use randomness::{seq::IteratorRandom, CryptoRng, Rng, RngExt as _, SliceRandom}; +use randomness::{CryptoRng, Rng, RngExt as _, SliceRandom, seq::IteratorRandom}; use test_utils::{random_ascii_alphanumeric_string, token_utils::*}; use tokens_accounting::{ InMemoryTokensAccounting, TokensAccountingCache, TokensAccountingDB, TokensAccountingDeltaData, @@ -456,8 +456,9 @@ impl<'a> RandomTxMaker<'a> { rng: &mut impl CryptoRng, tokens_cache: &mut (impl TokensAccountingView + TokensAccountingOperations), pos_accounting_before_tx: &impl PoSAccountingView, - pos_accounting_latest: &mut (impl PoSAccountingView - + PoSAccountingOperations), + pos_accounting_latest: &mut ( + impl PoSAccountingView + PoSAccountingOperations + ), orders_cache: &mut (impl OrdersAccountingView + OrdersAccountingOperations), accounts: &[AccountType], key_manager: &mut KeyManager, diff --git a/chainstate/test-framework/src/test_block_index_handle.rs b/chainstate/test-framework/src/test_block_index_handle.rs index 7349ea442d..8f07b9928d 100644 --- a/chainstate/test-framework/src/test_block_index_handle.rs +++ b/chainstate/test-framework/src/test_block_index_handle.rs @@ -15,7 +15,7 @@ use chainstate::PropertyQueryError; use chainstate_storage::BlockchainStorageRead; -use chainstate_types::{storage_result, BlockIndex, BlockIndexHandle, GenBlockIndex}; +use chainstate_types::{BlockIndex, BlockIndexHandle, GenBlockIndex, storage_result}; use common::{ chain::{Block, ChainConfig, GenBlock, GenBlockId}, primitives::Id, diff --git a/chainstate/test-framework/src/transaction_builder.rs b/chainstate/test-framework/src/transaction_builder.rs index d382161a72..85adeeadc1 100644 --- a/chainstate/test-framework/src/transaction_builder.rs +++ b/chainstate/test-framework/src/transaction_builder.rs @@ -15,8 +15,8 @@ use common::{ chain::{ - output_value::OutputValue, signature::inputsig::InputWitness, - signed_transaction::SignedTransaction, Destination, Transaction, TxInput, TxOutput, + Destination, Transaction, TxInput, TxOutput, output_value::OutputValue, + signature::inputsig::InputWitness, signed_transaction::SignedTransaction, }, primitives::Amount, }; @@ -97,10 +97,10 @@ impl TransactionBuilder { #[trace] #[case(test_utils::random::Seed::from_entropy())] fn build_transaction(#[case] seed: test_utils::random::Seed) { - use common::chain::signature::inputsig::InputWitness; use common::chain::OutPointSourceId; - use common::primitives::Id; + use common::chain::signature::inputsig::InputWitness; use common::primitives::H256; + use common::primitives::Id; let mut rng = test_utils::random::make_seedable_rng(seed); diff --git a/chainstate/test-framework/src/tx_verification_strategy/disposable_strategy.rs b/chainstate/test-framework/src/tx_verification_strategy/disposable_strategy.rs index b6e1be89f9..dab2bf47d5 100644 --- a/chainstate/test-framework/src/tx_verification_strategy/disposable_strategy.rs +++ b/chainstate/test-framework/src/tx_verification_strategy/disposable_strategy.rs @@ -18,19 +18,19 @@ use chainstate::{ }; use chainstate_types::BlockIndex; use common::{ - chain::{block::timestamp::BlockTimestamp, Block, ChainConfig}, - primitives::{id::WithId, Idable}, + chain::{Block, ChainConfig, block::timestamp::BlockTimestamp}, + primitives::{Idable, id::WithId}, }; use constraints_value_accumulator::AccumulatedFee; use orders_accounting::OrdersAccountingView; use pos_accounting::PoSAccountingView; use tokens_accounting::TokensAccountingView; use tx_verifier::{ + TransactionSource, transaction_verifier::{ - error::ConnectTransactionError, flush::flush_to_storage, - storage::TransactionVerifierStorageRef, TransactionSourceForConnect, TransactionVerifier, + TransactionSourceForConnect, TransactionVerifier, error::ConnectTransactionError, + flush::flush_to_storage, storage::TransactionVerifierStorageRef, }, - TransactionSource, }; use utils::{shallow_clone::ShallowClone, tap_log::TapLog}; use utxo::UtxosView; diff --git a/chainstate/test-framework/src/tx_verification_strategy/randomized_strategy.rs b/chainstate/test-framework/src/tx_verification_strategy/randomized_strategy.rs index d03506b066..8d83298e0c 100644 --- a/chainstate/test-framework/src/tx_verification_strategy/randomized_strategy.rs +++ b/chainstate/test-framework/src/tx_verification_strategy/randomized_strategy.rs @@ -18,22 +18,22 @@ use chainstate::{ }; use chainstate_types::BlockIndex; use common::{ - chain::{block::timestamp::BlockTimestamp, Block, ChainConfig}, - primitives::{id::WithId, Idable}, + chain::{Block, ChainConfig, block::timestamp::BlockTimestamp}, + primitives::{Idable, id::WithId}, }; use constraints_value_accumulator::AccumulatedFee; use orders_accounting::OrdersAccountingView; use pos_accounting::PoSAccountingView; use randomness::{Rng, RngExt as _}; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use tokens_accounting::TokensAccountingView; use tx_verifier::{ + TransactionSource, transaction_verifier::{ + TransactionSourceForConnect, TransactionVerifier, TransactionVerifierDelta, error::ConnectTransactionError, flush::flush_to_storage, - storage::TransactionVerifierStorageRef, TransactionSourceForConnect, TransactionVerifier, - TransactionVerifierDelta, + storage::TransactionVerifierStorageRef, }, - TransactionSource, }; use utils::{shallow_clone::ShallowClone, tap_log::TapLog}; use utxo::UtxosView; diff --git a/chainstate/test-framework/src/utils.rs b/chainstate/test-framework/src/utils.rs index fae67ec203..0553a5be0d 100644 --- a/chainstate/test-framework/src/utils.rs +++ b/chainstate/test-framework/src/utils.rs @@ -16,40 +16,40 @@ use std::borrow::Cow; use crate::{ - framework::BlockOutputs, key_manager::KeyManager, - signature_destination_getter::SignatureDestinationGetter, TestBlockIndexHandle, TestFramework, + TestBlockIndexHandle, TestFramework, framework::BlockOutputs, key_manager::KeyManager, + signature_destination_getter::SignatureDestinationGetter, }; use chainstate::{BlockIndex, GenBlockIndex}; use chainstate_storage::{BlockchainStorageRead, Transactional as _}; -use chainstate_types::{pos_randomness::PoSRandomness, TipStorageTag}; +use chainstate_types::{TipStorageTag, pos_randomness::PoSRandomness}; use common::{ + Uint256, chain::{ + Block, ChainConfig, CoinUnit, ConsensusUpgrade, Destination, GenBlock, Genesis, + NetUpgrades, OrderId, OutPointSourceId, PoSChainConfig, PoSChainConfigBuilder, PoSStatus, + PoolId, RequiredConsensus, TxInput, TxOutput, UtxoOutPoint, block::{ - consensus_data::PoSData, timestamp::BlockTimestamp, BlockRewardTransactable, - ConsensusData, + BlockRewardTransactable, ConsensusData, consensus_data::PoSData, + timestamp::BlockTimestamp, }, - config::{create_unit_test_config, Builder as ConfigBuilder, ChainType, EpochIndex}, + config::{Builder as ConfigBuilder, ChainType, EpochIndex, create_unit_test_config}, output_value::OutputValue, signature::{ - inputsig::{standard_signature::StandardInputSignature, InputWitness}, + inputsig::{InputWitness, standard_signature::StandardInputSignature}, sighash::{ self, input_commitments::{ - make_sighash_input_commitments_for_transaction_inputs_at_height, SighashInputCommitment, + make_sighash_input_commitments_for_transaction_inputs_at_height, }, sighashtype::SigHashType, }, }, stakelock::StakePoolData, - Block, ChainConfig, CoinUnit, ConsensusUpgrade, Destination, GenBlock, Genesis, - NetUpgrades, OrderId, OutPointSourceId, PoSChainConfig, PoSChainConfigBuilder, PoSStatus, - PoolId, RequiredConsensus, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight, Compact, Id, Idable, H256}, - Uint256, + primitives::{Amount, BlockHeight, Compact, H256, Id, Idable, per_thousand::PerThousand}, }; -use consensus::{find_timestamp_for_staking, ConsensusPoSError}; +use consensus::{ConsensusPoSError, find_timestamp_for_staking}; use crypto::{ key::{KeyKind, PrivateKey, PublicKey}, vrf::{VRFPrivateKey, VRFPublicKey}, diff --git a/chainstate/test-framework/src/utxo_for_spending.rs b/chainstate/test-framework/src/utxo_for_spending.rs index 5aad7701f3..1839f0dfb8 100644 --- a/chainstate/test-framework/src/utxo_for_spending.rs +++ b/chainstate/test-framework/src/utxo_for_spending.rs @@ -15,14 +15,14 @@ use common::{ chain::{ - output_value::OutputValue, Destination, OutPointSourceId, SignedTransaction, TxOutput, - UtxoOutPoint, + Destination, OutPointSourceId, SignedTransaction, TxOutput, UtxoOutPoint, + output_value::OutputValue, }, primitives::{Amount, Idable}, }; use randomness::CryptoRng; -use crate::{empty_witness, TransactionBuilder}; +use crate::{TransactionBuilder, empty_witness}; /// A struct that tracks a utxo and amount available for spending. pub struct UtxoForSpending { diff --git a/chainstate/test-suite/benches/benches.rs b/chainstate/test-suite/benches/benches.rs index d8cd9a9318..a38c9e0a1f 100644 --- a/chainstate/test-suite/benches/benches.rs +++ b/chainstate/test-suite/benches/benches.rs @@ -15,8 +15,8 @@ use chainstate_test_framework::TestFramework; use common::{ - chain::{config::create_unit_test_config, stakelock::StakePoolData, Destination, PoolId}, - primitives::{per_thousand::PerThousand, Amount, BlockDistance, Idable, H256}, + chain::{Destination, PoolId, config::create_unit_test_config, stakelock::StakePoolData}, + primitives::{Amount, BlockDistance, H256, Idable, per_thousand::PerThousand}, }; use crypto::{ key::{KeyKind, PrivateKey}, @@ -24,7 +24,7 @@ use crypto::{ }; use test_utils::random::make_seedable_rng; -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; pub fn pow_reorg(c: &mut Criterion) { let mut rng = make_seedable_rng(1111.into()); diff --git a/chainstate/test-suite/src/tests/basic_tests.rs b/chainstate/test-suite/src/tests/basic_tests.rs index 78e8f5049d..d033748296 100644 --- a/chainstate/test-suite/src/tests/basic_tests.rs +++ b/chainstate/test-suite/src/tests/basic_tests.rs @@ -16,8 +16,8 @@ use chainstate_test_framework::TestFramework; use common::primitives::Idable; use rstest::rstest; -use test_utils::random::make_seedable_rng; use test_utils::random::Seed; +use test_utils::random::make_seedable_rng; #[rstest] #[trace] diff --git a/chainstate/test-suite/src/tests/block_invalidation.rs b/chainstate/test-suite/src/tests/block_invalidation.rs index 5bf8f65ab1..33d0c4d9c7 100644 --- a/chainstate/test-suite/src/tests/block_invalidation.rs +++ b/chainstate/test-suite/src/tests/block_invalidation.rs @@ -21,25 +21,25 @@ use chainstate::{ BlockError, BlockInvalidatorError, BlockSource, ChainstateError, ChainstateEvent, CheckBlockError, }; -use chainstate_test_framework::{storage::Builder as StorageBuilder, TestFramework}; +use chainstate_test_framework::{TestFramework, storage::Builder as StorageBuilder}; use chainstate_types::{BlockStatus, BlockValidationStage}; use common::{ + Uint256, chain::{ self, - block::{consensus_data::PoWData, Block, ConsensusData}, + block::{Block, ConsensusData, consensus_data::PoWData}, }, primitives::{BlockDistance, BlockHeight, Id, Idable}, - Uint256, }; use randomness::{CryptoRng, RngExt as _}; use test_utils::{ assert_matches, mock_time_getter::mocked_time_getter_seconds, - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, }; use utils::atomics::SeqCstAtomicU64; -use super::helpers::{block_creation_helpers::*, block_status_helpers::*, EventList}; +use super::helpers::{EventList, block_creation_helpers::*, block_status_helpers::*}; mod storage_configs { use super::StorageBuilder; diff --git a/chainstate/test-suite/src/tests/block_status.rs b/chainstate/test-suite/src/tests/block_status.rs index 3d4dac0b4d..955400f83f 100644 --- a/chainstate/test-suite/src/tests/block_status.rs +++ b/chainstate/test-suite/src/tests/block_status.rs @@ -20,7 +20,7 @@ use chainstate::{BlockError, BlockSource, ChainstateError, CheckBlockError}; use chainstate_test_framework::TestFramework; use chainstate_types::BlockValidationStage; use common::primitives::Idable; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; // Check processing of a good block. #[rstest] diff --git a/chainstate/test-suite/src/tests/bootstrap.rs b/chainstate/test-suite/src/tests/bootstrap.rs index d4ebb30edb..5c1a55817f 100644 --- a/chainstate/test-suite/src/tests/bootstrap.rs +++ b/chainstate/test-suite/src/tests/bootstrap.rs @@ -23,18 +23,18 @@ use rstest::rstest; use strum::IntoEnumIterator; use chainstate::{ - chainstate_interface::ChainstateInterface, BootstrapError, ChainstateConfig, ChainstateError, + BootstrapError, ChainstateConfig, ChainstateError, chainstate_interface::ChainstateInterface, }; use chainstate_storage::BlockchainStorage; use chainstate_test_framework::TestFramework; use common::{ - chain::{self, config::ChainType, Block, ChainConfig, Destination, NetUpgrades}, + chain::{self, Block, ChainConfig, Destination, NetUpgrades, config::ChainType}, primitives::{Id, Idable}, }; use logging::log; -use randomness::{seq::IteratorRandom as _, CryptoRng, RngExt as _}; +use randomness::{CryptoRng, RngExt as _, seq::IteratorRandom as _}; use serialization::Encode as _; -use test_utils::random::{gen_random_bytes, make_seedable_rng, Seed}; +use test_utils::random::{Seed, gen_random_bytes, make_seedable_rng}; /// Ensure that the blocks vector put blocks in order with height in the blockchain fn check_height_order(blocks: &[Id], tf: &TestFramework) { diff --git a/chainstate/test-suite/src/tests/chainstate_accounting_storage_tests.rs b/chainstate/test-suite/src/tests/chainstate_accounting_storage_tests.rs index 25c3fdfb83..5a53d9f976 100644 --- a/chainstate/test-suite/src/tests/chainstate_accounting_storage_tests.rs +++ b/chainstate/test-suite/src/tests/chainstate_accounting_storage_tests.rs @@ -22,20 +22,20 @@ use accounting::{DataDelta, DeltaAmountCollection, DeltaDataCollection}; use chainstate::BlockSource; use chainstate_storage::{BlockchainStorageRead, Transactional}; use chainstate_test_framework::{ - anyonecanspend_address, empty_witness, TestFramework, TestStore, TransactionBuilder, + TestFramework, TestStore, TransactionBuilder, anyonecanspend_address, empty_witness, }; use common::{ chain::{ - config::Builder as ConfigBuilder, output_value::OutputValue, stakelock::StakePoolData, Destination, OutPointSourceId, PoolId, SignedTransaction, TxInput, TxOutput, UtxoOutPoint, + config::Builder as ConfigBuilder, output_value::OutputValue, stakelock::StakePoolData, }, - primitives::{per_thousand::PerThousand, Amount, Idable}, + primitives::{Amount, Idable, per_thousand::PerThousand}, }; use crypto::vrf::{VRFKeyKind, VRFPrivateKey}; use pos_accounting::PoolData; use randomness::{CryptoRng, RngExt as _}; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use utxo::UtxosStorageRead; fn create_pool_data( @@ -166,12 +166,14 @@ fn store_pool_data_and_balance(#[case] seed: Seed) { expected_tip_storage_data ); - assert!(storage - .transaction_ro() - .unwrap() - .read_pos_accounting_data_sealed() - .unwrap() - .is_empty()); + assert!( + storage + .transaction_ro() + .unwrap() + .read_pos_accounting_data_sealed() + .unwrap() + .is_empty() + ); }); } @@ -259,12 +261,14 @@ fn accounting_storage_two_blocks_one_epoch_no_seal(#[case] seed: Seed) { ); // check that result is not stored to sealed - assert!(storage - .transaction_ro() - .unwrap() - .read_pos_accounting_data_sealed() - .unwrap() - .is_empty()); + assert!( + storage + .transaction_ro() + .unwrap() + .read_pos_accounting_data_sealed() + .unwrap() + .is_empty() + ); // check that delta for epoch is stored let expected_epoch_delta = pos_accounting::PoSAccountingDeltaData { @@ -295,12 +299,14 @@ fn accounting_storage_two_blocks_one_epoch_no_seal(#[case] seed: Seed) { .expect("some"); assert_eq!(epoch_delta, expected_epoch_delta); - assert!(storage - .transaction_ro() - .unwrap() - .get_accounting_epoch_undo_delta(0) - .unwrap() - .is_none()); + assert!( + storage + .transaction_ro() + .unwrap() + .get_accounting_epoch_undo_delta(0) + .unwrap() + .is_none() + ); }); } @@ -570,24 +576,30 @@ fn accounting_storage_seal_one_epoch(#[case] seed: Seed) { .expect("some"); assert_eq!(epoch2_delta, expected_epoch2_delta); - assert!(storage - .transaction_ro() - .unwrap() - .get_accounting_epoch_undo_delta(0) - .unwrap() - .is_none()); - assert!(storage - .transaction_ro() - .unwrap() - .get_accounting_epoch_undo_delta(1) - .unwrap() - .is_some()); - assert!(storage - .transaction_ro() - .unwrap() - .get_accounting_epoch_undo_delta(2) - .unwrap() - .is_none()); + assert!( + storage + .transaction_ro() + .unwrap() + .get_accounting_epoch_undo_delta(0) + .unwrap() + .is_none() + ); + assert!( + storage + .transaction_ro() + .unwrap() + .get_accounting_epoch_undo_delta(1) + .unwrap() + .is_some() + ); + assert!( + storage + .transaction_ro() + .unwrap() + .get_accounting_epoch_undo_delta(2) + .unwrap() + .is_none() + ); }); } @@ -673,18 +685,22 @@ fn accounting_storage_seal_every_block(#[case] seed: Seed) { .expect("some"); assert_eq!(epoch1_delta, expected_epoch1_delta); - assert!(storage - .transaction_ro() - .unwrap() - .get_accounting_epoch_undo_delta(0) - .unwrap() - .is_none()); - assert!(storage - .transaction_ro() - .unwrap() - .get_accounting_epoch_undo_delta(1) - .unwrap() - .is_some()); + assert!( + storage + .transaction_ro() + .unwrap() + .get_accounting_epoch_undo_delta(0) + .unwrap() + .is_none() + ); + assert!( + storage + .transaction_ro() + .unwrap() + .get_accounting_epoch_undo_delta(1) + .unwrap() + .is_some() + ); }); } @@ -749,25 +765,31 @@ fn accounting_storage_no_accounting_data(#[case] seed: Seed) { ); // check that deltas per epoch are not stored - assert!(storage - .transaction_ro() - .unwrap() - .get_accounting_epoch_delta(block1_epoch_index) - .unwrap() - .is_none()); + assert!( + storage + .transaction_ro() + .unwrap() + .get_accounting_epoch_delta(block1_epoch_index) + .unwrap() + .is_none() + ); // check that undo per epoch are not stored - assert!(storage - .transaction_ro() - .unwrap() - .get_accounting_epoch_undo_delta(0) - .unwrap() - .is_none()); - assert!(storage - .transaction_ro() - .unwrap() - .get_accounting_epoch_undo_delta(1) - .unwrap() - .is_none()); + assert!( + storage + .transaction_ro() + .unwrap() + .get_accounting_epoch_undo_delta(0) + .unwrap() + .is_none() + ); + assert!( + storage + .transaction_ro() + .unwrap() + .get_accounting_epoch_undo_delta(1) + .unwrap() + .is_none() + ); }); } diff --git a/chainstate/test-suite/src/tests/chainstate_storage_tests.rs b/chainstate/test-suite/src/tests/chainstate_storage_tests.rs index 2f38aa95f8..d06c751f1f 100644 --- a/chainstate/test-suite/src/tests/chainstate_storage_tests.rs +++ b/chainstate/test-suite/src/tests/chainstate_storage_tests.rs @@ -17,15 +17,14 @@ use std::collections::BTreeMap; use chainstate_storage::{BlockchainStorageRead, Transactional}; use chainstate_test_framework::{ - anyonecanspend_address, empty_witness, TestFramework, TestStore, TransactionBuilder, + TestFramework, TestStore, TransactionBuilder, anyonecanspend_address, empty_witness, }; use common::{ chain::{ - make_token_id, + ChainstateUpgradeBuilder, Destination, OutPointSourceId, TokenIssuanceVersion, Transaction, + TxInput, TxOutput, UtxoOutPoint, make_token_id, output_value::OutputValue, tokens::{NftIssuance, TokenAuxiliaryData, TokenIssuanceV0}, - ChainstateUpgradeBuilder, Destination, OutPointSourceId, TokenIssuanceVersion, Transaction, - TxInput, TxOutput, UtxoOutPoint, }, primitives::{Amount, Id, Idable}, }; diff --git a/chainstate/test-suite/src/tests/data_deposit.rs b/chainstate/test-suite/src/tests/data_deposit.rs index 8331bcfe79..e6977fcdee 100644 --- a/chainstate/test-suite/src/tests/data_deposit.rs +++ b/chainstate/test-suite/src/tests/data_deposit.rs @@ -19,13 +19,13 @@ use chainstate::{ }; use chainstate_test_framework::{TestFramework, TransactionBuilder}; use common::chain::{ - output_value::OutputValue, signature::inputsig::InputWitness, Destination, OutPointSourceId, - TxInput, TxOutput, UtxoOutPoint, + Destination, OutPointSourceId, TxInput, TxOutput, UtxoOutPoint, output_value::OutputValue, + signature::inputsig::InputWitness, }; use common::primitives::{Amount, BlockHeight, CoinOrTokenId, Idable}; use randomness::RngExt as _; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use tx_verifier::CheckTransactionError; #[rstest] diff --git a/chainstate/test-suite/src/tests/delegation_tests.rs b/chainstate/test-suite/src/tests/delegation_tests.rs index 8630f7919b..35682302d7 100644 --- a/chainstate/test-suite/src/tests/delegation_tests.rs +++ b/chainstate/test-suite/src/tests/delegation_tests.rs @@ -18,26 +18,26 @@ use rstest::rstest; use chainstate::{BlockError, ChainstateError, ConnectTransactionError, IOPolicyError}; use chainstate_storage::Transactional; use chainstate_test_framework::{ - create_stake_pool_data_with_all_reward_to_staker, empty_witness, get_output_value, - TestFramework, TestStore, TransactionBuilder, + TestFramework, TestStore, TransactionBuilder, create_stake_pool_data_with_all_reward_to_staker, + empty_witness, get_output_value, }; use chainstate_types::TipStorageTag; use common::{ chain::{ + AccountNonce, AccountOutPoint, AccountSpending, AccountType, DelegationId, Destination, + OutPointSourceId, PoolId, SignedTransaction, TxInput, TxOutput, UtxoOutPoint, config::create_unit_test_config, make_delegation_id, output_value::OutputValue, signature::{ - inputsig::{standard_signature::StandardInputSignature, InputWitness}, - sighash::input_commitments::SighashInputCommitment, DestinationSigError, + inputsig::{InputWitness, standard_signature::StandardInputSignature}, + sighash::input_commitments::SighashInputCommitment, }, stakelock::StakePoolData, timelock::OutputTimeLock, - AccountNonce, AccountOutPoint, AccountSpending, AccountType, DelegationId, Destination, - OutPointSourceId, PoolId, SignedTransaction, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, Idable, H256}, + primitives::{Amount, H256, Idable, per_thousand::PerThousand}, }; use crypto::{ key::{KeyKind, PrivateKey}, @@ -45,7 +45,7 @@ use crypto::{ }; use pos_accounting::{DelegationData, PoSAccountingStorageRead}; use randomness::{CryptoRng, RngExt as _}; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use tx_verifier::error::{InputCheckError, ScriptError}; fn prepare_stake_pool( diff --git a/chainstate/test-suite/src/tests/double_spend_tests.rs b/chainstate/test-suite/src/tests/double_spend_tests.rs index 00353e1085..1f1c8cd879 100644 --- a/chainstate/test-suite/src/tests/double_spend_tests.rs +++ b/chainstate/test-suite/src/tests/double_spend_tests.rs @@ -18,12 +18,12 @@ use chainstate::{ ConnectTransactionError, }; use chainstate_test_framework::{ - anyonecanspend_address, empty_witness, TestFramework, TransactionBuilder, + TestFramework, TransactionBuilder, anyonecanspend_address, empty_witness, }; use common::{ chain::{ - output_value::OutputValue, signed_transaction::SignedTransaction, OutPointSourceId, - Transaction, TxInput, TxOutput, UtxoOutPoint, + OutPointSourceId, Transaction, TxInput, TxOutput, UtxoOutPoint, output_value::OutputValue, + signed_transaction::SignedTransaction, }, primitives::{Amount, CoinOrTokenId, Id, Idable}, }; diff --git a/chainstate/test-suite/src/tests/events_tests.rs b/chainstate/test-suite/src/tests/events_tests.rs index b96c7223b8..97898200e2 100644 --- a/chainstate/test-suite/src/tests/events_tests.rs +++ b/chainstate/test-suite/src/tests/events_tests.rs @@ -25,13 +25,13 @@ use chainstate::{ }; use chainstate_test_framework::{OrphanErrorHandler, TestChainstate, TestFramework}; use common::{ - chain::{block::timestamp::BlockTimestamp, GenBlock}, - primitives::{id::Idable, BlockHeight, Id}, + chain::{GenBlock, block::timestamp::BlockTimestamp}, + primitives::{BlockHeight, Id, id::Idable}, }; use randomness::RngExt as _; use test_utils::{ assert_matches, - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, }; // TODO use EventList from helpers instead. diff --git a/chainstate/test-suite/src/tests/framework_tests.rs b/chainstate/test-suite/src/tests/framework_tests.rs index 5fbc18af0b..b9f7f55750 100644 --- a/chainstate/test-suite/src/tests/framework_tests.rs +++ b/chainstate/test-suite/src/tests/framework_tests.rs @@ -21,10 +21,9 @@ use chainstate::{BlockIndex, ChainstateConfig}; use chainstate_storage::{BlockchainStorageWrite, TransactionRw, Transactional}; use common::{ chain::{ - self, + self, Destination, NetUpgrades, block::timestamp::BlockTimestamp, - config::{create_regtest, ChainType}, - Destination, NetUpgrades, + config::{ChainType, create_regtest}, }, primitives::Idable, }; @@ -32,7 +31,7 @@ use randomness::CryptoRng; use chainstate_test_framework::TestFramework; use chainstate_types::{BlockStatus, BlockValidationStage}; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use super::helpers::block_creation_helpers::build_block; diff --git a/chainstate/test-suite/src/tests/fungible_tokens.rs b/chainstate/test-suite/src/tests/fungible_tokens.rs index 82e6277d05..01413a4824 100644 --- a/chainstate/test-suite/src/tests/fungible_tokens.rs +++ b/chainstate/test-suite/src/tests/fungible_tokens.rs @@ -22,23 +22,22 @@ use chainstate::{ BlockError, BlockSource, ChainstateError, CheckBlockError, CheckBlockTransactionsError, ConnectTransactionError, TokensError, }; -use chainstate_test_framework::{get_output_value, TestFramework, TransactionBuilder}; +use chainstate_test_framework::{TestFramework, TransactionBuilder, get_output_value}; use common::{ chain::{ - make_token_id, + ChainstateUpgradeBuilder, Destination, OutPointSourceId, TokenIssuanceVersion, TxInput, + TxOutput, UtxoOutPoint, make_token_id, output_value::OutputValue, signature::inputsig::InputWitness, tokens::{Metadata, NftIssuanceV0, TokenData, TokenId, TokenIssuanceV0, TokenTransfer}, - ChainstateUpgradeBuilder, Destination, OutPointSourceId, TokenIssuanceVersion, TxInput, - TxOutput, UtxoOutPoint, }, - primitives::{id, Amount, BlockHeight, Id, Idable}, + primitives::{Amount, BlockHeight, Id, Idable, id}, }; use crypto::hash::StreamHasher; use randomness::{CryptoRng, RngExt as _}; use serialization::extras::non_empty_vec::DataOrNoVec; use test_utils::{ - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, random_ascii_alphanumeric_string, token_utils::random_token_issuance, }; diff --git a/chainstate/test-suite/src/tests/fungible_tokens_v1.rs b/chainstate/test-suite/src/tests/fungible_tokens_v1.rs index 105fe6b4c3..d9e5af6fbe 100644 --- a/chainstate/test-suite/src/tests/fungible_tokens_v1.rs +++ b/chainstate/test-suite/src/tests/fungible_tokens_v1.rs @@ -23,47 +23,47 @@ use chainstate::{ }; use chainstate_storage::{BlockchainStorageRead, Transactional}; use chainstate_test_framework::{ + TestFramework, TransactionBuilder, helpers::{ issue_token_from_block, issue_token_from_genesis, make_token_issuance, mint_tokens_in_block, }, - TestFramework, TransactionBuilder, }; use common::{ chain::{ + AccountCommand, AccountNonce, AccountType, Block, ChainstateUpgradeBuilder, Destination, + GenBlock, OrderAccountCommand, OrderData, OutPointSourceId, SignedTransaction, Transaction, + TxInput, TxOutput, UtxoOutPoint, htlc::{HashedTimelockContract, HtlcSecret}, make_order_id, make_token_id, output_value::OutputValue, signature::{ - inputsig::{standard_signature::StandardInputSignature, InputWitness}, - sighash::input_commitments::SighashInputCommitment, DestinationSigError, + inputsig::{InputWitness, standard_signature::StandardInputSignature}, + sighash::input_commitments::SighashInputCommitment, }, timelock::OutputTimeLock, tokens::{ IsTokenFreezable, IsTokenFrozen, IsTokenUnfreezable, TokenId, TokenIssuance, TokenIssuanceV1, TokenTotalSupply, }, - AccountCommand, AccountNonce, AccountType, Block, ChainstateUpgradeBuilder, Destination, - GenBlock, OrderAccountCommand, OrderData, OutPointSourceId, SignedTransaction, Transaction, - TxInput, TxOutput, UtxoOutPoint, }, - primitives::{amount::SignedAmount, Amount, BlockHeight, CoinOrTokenId, Id, Idable}, + primitives::{Amount, BlockHeight, CoinOrTokenId, Id, Idable, amount::SignedAmount}, }; use crypto::key::{KeyKind, PrivateKey}; use randomness::{CryptoRng, RngExt as _}; use test_utils::{ assert_matches_return_val, gen_text_with_non_ascii, - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, random_ascii_alphanumeric_string, split_value, }; use tx_verifier::{ + CheckTransactionError, error::{InputCheckError, ScriptError, TimelockError}, transaction_verifier::error::TokenIssuanceError, - CheckTransactionError, }; use crate::tests::helpers::token_checks::{ - assert_token_missing, check_fungible_token, ExpectedFungibleTokenData, + ExpectedFungibleTokenData, assert_token_missing, check_fungible_token, }; fn unmint_tokens_in_block( @@ -6409,7 +6409,7 @@ fn reorg_tokens_tx_with_simple_tx(#[case] seed: Seed) { fn issue_same_token_alternative_pos_chain(#[case] seed: Seed) { use chainstate_test_framework::create_stake_pool_data_with_all_reward_to_staker; use common::{ - chain::{config::create_unit_test_config, PoolId}, + chain::{PoolId, config::create_unit_test_config}, primitives::H256, }; use crypto::vrf::{VRFKeyKind, VRFPrivateKey}; diff --git a/chainstate/test-suite/src/tests/get_stake_pool_balances_at_heights.rs b/chainstate/test-suite/src/tests/get_stake_pool_balances_at_heights.rs index 56ded7b951..22121144dc 100644 --- a/chainstate/test-suite/src/tests/get_stake_pool_balances_at_heights.rs +++ b/chainstate/test-suite/src/tests/get_stake_pool_balances_at_heights.rs @@ -19,18 +19,19 @@ use rstest::rstest; use chainstate::ChainstateConfig; use chainstate_test_framework::{ + PoSBlockBuilder, TestFramework, TransactionBuilder, UtxoForSpending, create_custom_genesis_with_stake_pool, create_stake_pool_data_with_all_reward_to_staker, - empty_witness, PoSBlockBuilder, TestFramework, TransactionBuilder, UtxoForSpending, + empty_witness, }; use chainstate_types::TipStorageTag; use common::{ chain::{ - self, config::ChainType, make_delegation_id, output_value::OutputValue, - timelock::OutputTimeLock, AccountNonce, AccountOutPoint, AccountSpending, CoinUnit, - ConsensusUpgrade, DelegationId, Destination, NetUpgrades, OutPointSourceId, - PoSChainConfigBuilder, PoolId, TxInput, TxOutput, UtxoOutPoint, + self, AccountNonce, AccountOutPoint, AccountSpending, CoinUnit, ConsensusUpgrade, + DelegationId, Destination, NetUpgrades, OutPointSourceId, PoSChainConfigBuilder, PoolId, + TxInput, TxOutput, UtxoOutPoint, config::ChainType, make_delegation_id, + output_value::OutputValue, timelock::OutputTimeLock, }, - primitives::{amount::SignedAmount, Amount, BlockCount, BlockHeight, Idable, H256}, + primitives::{Amount, BlockCount, BlockHeight, H256, Idable, amount::SignedAmount}, }; use crypto::{ key::{KeyKind, PrivateKey}, @@ -38,8 +39,8 @@ use crypto::{ }; use logging::log; use pos_accounting::PoSAccountingStorageRead; -use randomness::{seq::IteratorRandom, CryptoRng, Rng, RngExt as _}; -use test_utils::random::{make_seedable_rng, Seed}; +use randomness::{CryptoRng, Rng, RngExt as _, seq::IteratorRandom}; +use test_utils::random::{Seed, make_seedable_rng}; #[rstest] #[trace] diff --git a/chainstate/test-suite/src/tests/helpers/block_creation_helpers.rs b/chainstate/test-suite/src/tests/helpers/block_creation_helpers.rs index 0a6c86f670..03cefa4ff8 100644 --- a/chainstate/test-suite/src/tests/helpers/block_creation_helpers.rs +++ b/chainstate/test-suite/src/tests/helpers/block_creation_helpers.rs @@ -15,12 +15,12 @@ use chainstate::{BlockError, BlockIndex, BlockSource, ChainstateError, OrphanCheckError}; use chainstate_test_framework::{ - anyonecanspend_address, empty_witness, TestFramework, TransactionBuilder, + TestFramework, TransactionBuilder, anyonecanspend_address, empty_witness, }; use common::{ chain::{ - output_value::OutputValue, signed_transaction::SignedTransaction, timelock::OutputTimeLock, Block, GenBlock, OutPointSourceId, Transaction, TxInput, TxOutput, + output_value::OutputValue, signed_transaction::SignedTransaction, timelock::OutputTimeLock, }, primitives::{Amount, Id, Idable}, }; diff --git a/chainstate/test-suite/src/tests/helpers/in_memory_storage_wrapper.rs b/chainstate/test-suite/src/tests/helpers/in_memory_storage_wrapper.rs index 05e22a5719..d69fe554c8 100644 --- a/chainstate/test-suite/src/tests/helpers/in_memory_storage_wrapper.rs +++ b/chainstate/test-suite/src/tests/helpers/in_memory_storage_wrapper.rs @@ -20,12 +20,12 @@ use ::tx_verifier::transaction_verifier::storage::{ }; use chainstate_storage::{BlockchainStorageRead, Transactional}; use chainstate_test_framework::TestStore; -use chainstate_types::{storage_result, GenBlockIndex, TipStorageTag}; +use chainstate_types::{GenBlockIndex, TipStorageTag, storage_result}; use common::{ chain::{ - tokens::{TokenAuxiliaryData, TokenId}, AccountNonce, AccountType, ChainConfig, DelegationId, GenBlock, GenBlockId, OrderId, PoolId, Transaction, + tokens::{TokenAuxiliaryData, TokenId}, }, primitives::{Amount, Id}, }; @@ -35,8 +35,8 @@ use pos_accounting::{ }; use tokens_accounting::{TokenAccountingUndo, TokensAccountingStorageRead}; use tx_verifier::{ - transaction_verifier::{CachedBlockUndo, CachedUtxosBlockUndo}, TransactionSource, + transaction_verifier::{CachedBlockUndo, CachedUtxosBlockUndo}, }; use utxo::UtxosStorageRead; diff --git a/chainstate/test-suite/src/tests/helpers/mod.rs b/chainstate/test-suite/src/tests/helpers/mod.rs index 7fd3226c56..d9c91035ec 100644 --- a/chainstate/test-suite/src/tests/helpers/mod.rs +++ b/chainstate/test-suite/src/tests/helpers/mod.rs @@ -19,12 +19,11 @@ use std::{ }; use chainstate::ChainstateEvent; -use chainstate_test_framework::{anyonecanspend_address, TestFramework, TransactionBuilder}; +use chainstate_test_framework::{TestFramework, TransactionBuilder, anyonecanspend_address}; use common::{ chain::{ - block::timestamp::BlockTimestamp, output_value::OutputValue, - signature::inputsig::InputWitness, timelock::OutputTimeLock, Destination, Transaction, - TxInput, TxOutput, + Destination, Transaction, TxInput, TxOutput, block::timestamp::BlockTimestamp, + output_value::OutputValue, signature::inputsig::InputWitness, timelock::OutputTimeLock, }, primitives::{Amount, BlockDistance, Id, Idable}, }; diff --git a/chainstate/test-suite/src/tests/helpers/pos.rs b/chainstate/test-suite/src/tests/helpers/pos.rs index 2e42c2632b..ff2d33128d 100644 --- a/chainstate/test-suite/src/tests/helpers/pos.rs +++ b/chainstate/test-suite/src/tests/helpers/pos.rs @@ -13,7 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use chainstate_test_framework::{calculate_new_pos_compact_target, TestFramework}; +use chainstate_test_framework::{TestFramework, calculate_new_pos_compact_target}; use common::{ chain::{CoinUnit, Genesis}, primitives::{BlockHeight, Compact}, diff --git a/chainstate/test-suite/src/tests/helpers/token_checks.rs b/chainstate/test-suite/src/tests/helpers/token_checks.rs index 4dd0f97475..c33a155624 100644 --- a/chainstate/test-suite/src/tests/helpers/token_checks.rs +++ b/chainstate/test-suite/src/tests/helpers/token_checks.rs @@ -20,13 +20,12 @@ use chainstate_storage::{BlockchainStorageRead as _, Transactional}; use chainstate_test_framework::TestFramework; use common::{ chain::{ - make_token_id, + Block, Transaction, TxOutput, make_token_id, tokens::{ IsTokenFrozen, Metadata, NftIssuance, NftIssuanceV0, RPCFungibleTokenInfo, RPCNonFungibleTokenInfo, RPCTokenInfo, TokenAuxiliaryData, TokenId, TokenIssuance, TokenIssuanceV1, }, - Block, Transaction, TxOutput, }, primitives::{Amount, Id, Idable}, }; diff --git a/chainstate/test-suite/src/tests/history_iteration.rs b/chainstate/test-suite/src/tests/history_iteration.rs index 30ae477421..aeaa9d0e35 100644 --- a/chainstate/test-suite/src/tests/history_iteration.rs +++ b/chainstate/test-suite/src/tests/history_iteration.rs @@ -19,8 +19,8 @@ use chainstate::BlockSource; use chainstate_storage::Transactional; use chainstate_test_framework::{TestBlockIndexHandle, TestFramework}; use chainstate_types::BlockIndexHistoryIterator; -use common::primitives::{Id, Idable, H256}; -use test_utils::random::{make_seedable_rng, Seed}; +use common::primitives::{H256, Id, Idable}; +use test_utils::random::{Seed, make_seedable_rng}; #[rstest] #[trace] diff --git a/chainstate/test-suite/src/tests/homomorphism.rs b/chainstate/test-suite/src/tests/homomorphism.rs index 02b4d4eba8..3a6fdaf410 100644 --- a/chainstate/test-suite/src/tests/homomorphism.rs +++ b/chainstate/test-suite/src/tests/homomorphism.rs @@ -16,14 +16,14 @@ use super::*; use chainstate_storage::Transactional; use chainstate_test_framework::{ - anyonecanspend_address, create_stake_pool_data_with_all_reward_to_staker, empty_witness, - TestFramework, TestStore, TransactionBuilder, TxVerificationStrategy, + TestFramework, TestStore, TransactionBuilder, TxVerificationStrategy, anyonecanspend_address, + create_stake_pool_data_with_all_reward_to_staker, empty_witness, }; use common::{ chain::{ - make_delegation_id, make_token_id, output_value::OutputValue, timelock::OutputTimeLock, - tokens::TokenIssuance, AccountCommand, AccountNonce, Destination, OutPointSourceId, PoolId, - TxInput, TxOutput, UtxoOutPoint, + AccountCommand, AccountNonce, Destination, OutPointSourceId, PoolId, TxInput, TxOutput, + UtxoOutPoint, make_delegation_id, make_token_id, output_value::OutputValue, + timelock::OutputTimeLock, tokens::TokenIssuance, }, primitives::{Amount, Idable}, }; diff --git a/chainstate/test-suite/src/tests/htlc.rs b/chainstate/test-suite/src/tests/htlc.rs index dfc8e24bd0..ec917b6333 100644 --- a/chainstate/test-suite/src/tests/htlc.rs +++ b/chainstate/test-suite/src/tests/htlc.rs @@ -20,11 +20,14 @@ use chainstate_test_framework::{TestFramework, TransactionBuilder}; use common::{ address::pubkeyhash::PublicKeyHash, chain::{ + AccountCommand, AccountNonce, ChainConfig, ChainstateUpgradeBuilder, Destination, + HtlcActivated, TokenIssuanceVersion, TxInput, TxOutput, classic_multisig::ClassicMultisigChallenge, htlc::{HashedTimelockContract, HtlcSecret, HtlcSecretHash}, make_token_id, output_value::OutputValue, signature::{ + DestinationSigError, inputsig::{ authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, classical_multisig::authorize_classical_multisig::AuthorizedClassicalMultisigSpend, @@ -38,13 +41,10 @@ use common::{ sighash::{ input_commitments::SighashInputCommitment, sighashtype::SigHashType, signature_hash, }, - DestinationSigError, }, signed_transaction::SignedTransaction, timelock::OutputTimeLock, tokens::{TokenData, TokenIssuance, TokenTransfer}, - AccountCommand, AccountNonce, ChainConfig, ChainstateUpgradeBuilder, Destination, - HtlcActivated, TokenIssuanceVersion, TxInput, TxOutput, }, primitives::{Amount, Idable}, }; diff --git a/chainstate/test-suite/src/tests/initialization.rs b/chainstate/test-suite/src/tests/initialization.rs index 31e02e3003..aaf4f51c43 100644 --- a/chainstate/test-suite/src/tests/initialization.rs +++ b/chainstate/test-suite/src/tests/initialization.rs @@ -18,8 +18,8 @@ use chainstate::ChainstateError; use chainstate_test_framework::TestFramework; use common::{ chain::{ - config::{Builder as ChainConfigBuilder, ChainType}, NetUpgrades, + config::{Builder as ChainConfigBuilder, ChainType}, }, primitives::Id, }; diff --git a/chainstate/test-suite/src/tests/input_commitments.rs b/chainstate/test-suite/src/tests/input_commitments.rs index 1b078d83ce..fb77c2e021 100644 --- a/chainstate/test-suite/src/tests/input_commitments.rs +++ b/chainstate/test-suite/src/tests/input_commitments.rs @@ -19,32 +19,32 @@ use itertools::Itertools as _; use rstest::rstest; use chainstate::{ - chainstate_interface::ChainstateInterface, BlockError, ChainstateError, ConnectTransactionError, + BlockError, ChainstateError, ConnectTransactionError, chainstate_interface::ChainstateInterface, }; use chainstate_test_framework::{ - create_chain_config_with_staking_pool, empty_witness, + PoSBlockBuilder, TestFramework, TransactionBuilder, create_chain_config_with_staking_pool, + empty_witness, helpers::{calculate_fill_order, issue_and_mint_random_token_from_best_block}, - PoSBlockBuilder, TestFramework, TransactionBuilder, }; use common::{ chain::{ - self, + self, AccountCommand, AccountNonce, ChainstateUpgradeBuilder, Destination, + OrderAccountCommand, OrderData, OrderId, OrdersVersion, OutPointSourceId, PoolId, + SighashInputCommitmentVersion, SignedTransaction, Transaction, TxInput, TxOutput, + UtxoOutPoint, config::create_unit_test_config, make_order_id, output_value::OutputValue, signature::{ - inputsig::{standard_signature::StandardInputSignature, InputWitness}, - sighash::input_commitments::SighashInputCommitment, DestinationSigError, + inputsig::{InputWitness, standard_signature::StandardInputSignature}, + sighash::input_commitments::SighashInputCommitment, }, stakelock::StakePoolData, timelock::OutputTimeLock, tokens::{IsTokenFreezable, TokenTotalSupply}, - AccountCommand, AccountNonce, ChainstateUpgradeBuilder, Destination, OrderAccountCommand, - OrderData, OrderId, OrdersVersion, OutPointSourceId, PoolId, SighashInputCommitmentVersion, - SignedTransaction, Transaction, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight, Idable, H256}, + primitives::{Amount, BlockHeight, H256, Idable, per_thousand::PerThousand}, }; use crypto::{ key::{KeyKind, PrivateKey}, @@ -54,7 +54,7 @@ use logging::log; use randomness::{CryptoRng, RngExt as _}; use test_utils::{ assert_matches_return_val, - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, }; use tx_verifier::{ error::{InputCheckError, ScriptError}, diff --git a/chainstate/test-suite/src/tests/mempool_output_timelock.rs b/chainstate/test-suite/src/tests/mempool_output_timelock.rs index 4ca1bb1b96..842496a344 100644 --- a/chainstate/test-suite/src/tests/mempool_output_timelock.rs +++ b/chainstate/test-suite/src/tests/mempool_output_timelock.rs @@ -20,14 +20,14 @@ use chainstate::ConnectTransactionError; use chainstate_test_framework::{TestFramework, TestStore, TransactionBuilder}; use common::{ chain::{ - block::timestamp::BlockTimestamp, config::Builder as ConfigBuilder, - timelock::OutputTimeLock, ChainConfig, + ChainConfig, block::timestamp::BlockTimestamp, config::Builder as ConfigBuilder, + timelock::OutputTimeLock, }, - primitives::{time, BlockHeight}, + primitives::{BlockHeight, time}, }; use randomness::CryptoRng; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use tx_verifier::{ error::{InputCheckError, ScriptError, TimelockError}, transaction_verifier::{TransactionSourceForConnect, TransactionVerifier}, diff --git a/chainstate/test-suite/src/tests/mod.rs b/chainstate/test-suite/src/tests/mod.rs index 6464a31005..970e3e0a46 100644 --- a/chainstate/test-suite/src/tests/mod.rs +++ b/chainstate/test-suite/src/tests/mod.rs @@ -16,12 +16,12 @@ use chainstate::BlockSource; use chainstate_test_framework::TestFramework; use common::{ - chain::{signature::inputsig::InputWitness, GenBlock, Genesis}, + chain::{GenBlock, Genesis, signature::inputsig::InputWitness}, primitives::{BlockHeight, Id}, }; use randomness::RngExt as _; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; mod basic_tests; mod block_invalidation; diff --git a/chainstate/test-suite/src/tests/nft_burn.rs b/chainstate/test-suite/src/tests/nft_burn.rs index b0e3bfb1d8..3862cf1d98 100644 --- a/chainstate/test-suite/src/tests/nft_burn.rs +++ b/chainstate/test-suite/src/tests/nft_burn.rs @@ -19,15 +19,15 @@ use chainstate::{BlockError, ChainstateError, ConnectTransactionError}; use chainstate_test_framework::{TestFramework, TransactionBuilder}; use common::{ chain::{ - output_value::OutputValue, signature::inputsig::InputWitness, tokens::TokenId, ChainstateUpgradeBuilder, Destination, OutPointSourceId, TokenIssuanceVersion, TxInput, - TxOutput, UtxoOutPoint, + TxOutput, UtxoOutPoint, output_value::OutputValue, signature::inputsig::InputWitness, + tokens::TokenId, }, primitives::{Amount, BlockHeight, CoinOrTokenId, Idable}, }; use randomness::RngExt as _; use test_utils::{ - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, token_utils::random_nft_issuance, }; @@ -155,9 +155,10 @@ fn nft_burn_valid_case(#[case] seed: Seed) { .unwrap() .unwrap(); let block = tf.block(*block_index.block_id()); - assert!(tf - .outputs_from_genblock(block.get_id().into()) - .contains_key(&first_burn_outpoint_id)); + assert!( + tf.outputs_from_genblock(block.get_id().into()) + .contains_key(&first_burn_outpoint_id) + ); // Try to transfer burned tokens let result = tf diff --git a/chainstate/test-suite/src/tests/nft_issuance.rs b/chainstate/test-suite/src/tests/nft_issuance.rs index 63705b595c..59333ded3f 100644 --- a/chainstate/test-suite/src/tests/nft_issuance.rs +++ b/chainstate/test-suite/src/tests/nft_issuance.rs @@ -22,11 +22,11 @@ use chainstate::{ use chainstate_test_framework::{TestFramework, TransactionBuilder}; use common::{ chain::{ - output_value::OutputValue, - signature::inputsig::InputWitness, - tokens::{is_rfc3986_valid_symbol, Metadata, NftIssuance, NftIssuanceV0, TokenId}, Block, ChainstateUpgradeBuilder, Destination, GenBlock, OutPointSourceId, TokenIssuanceVersion, TxInput, TxOutput, UtxoOutPoint, + output_value::OutputValue, + signature::inputsig::InputWitness, + tokens::{Metadata, NftIssuance, NftIssuanceV0, TokenId, is_rfc3986_valid_symbol}, }, primitives::{BlockHeight, Id, Idable}, }; @@ -34,13 +34,13 @@ use randomness::{CryptoRng, RngExt as _}; use serialization::extras::non_empty_vec::DataOrNoVec; use test_utils::{ gen_text_with_non_ascii, - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, random_ascii_alphanumeric_string, token_utils::{random_creator, random_nft_issuance, random_token_issuance_v1}, }; -use tx_verifier::{error::TokenIssuanceError, CheckTransactionError}; +use tx_verifier::{CheckTransactionError, error::TokenIssuanceError}; -use crate::tests::helpers::token_checks::{check_nft, ExpectedNftData}; +use crate::tests::helpers::token_checks::{ExpectedNftData, check_nft}; #[rstest] #[trace] diff --git a/chainstate/test-suite/src/tests/nft_reorgs.rs b/chainstate/test-suite/src/tests/nft_reorgs.rs index a71fb24828..10f3511c83 100644 --- a/chainstate/test-suite/src/tests/nft_reorgs.rs +++ b/chainstate/test-suite/src/tests/nft_reorgs.rs @@ -17,18 +17,18 @@ use chainstate::{BlockError, BlockSource, ChainstateError, ConnectTransactionErr use chainstate_test_framework::{TestFramework, TransactionBuilder}; use common::{ chain::{ - output_value::OutputValue, signature::inputsig::InputWitness, tokens::TokenId, Destination, - OutPointSourceId, TxInput, TxOutput, UtxoOutPoint, + Destination, OutPointSourceId, TxInput, TxOutput, UtxoOutPoint, output_value::OutputValue, + signature::inputsig::InputWitness, tokens::TokenId, }, primitives::{Amount, BlockHeight, Idable}, }; use rstest::rstest; use test_utils::{ - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, token_utils::random_nft_issuance, }; -use crate::tests::helpers::token_checks::{assert_token_missing, check_nft, ExpectedNftData}; +use crate::tests::helpers::token_checks::{ExpectedNftData, assert_token_missing, check_nft}; #[rstest] #[trace] diff --git a/chainstate/test-suite/src/tests/nft_transfer.rs b/chainstate/test-suite/src/tests/nft_transfer.rs index e6a6bc4852..c418c36b27 100644 --- a/chainstate/test-suite/src/tests/nft_transfer.rs +++ b/chainstate/test-suite/src/tests/nft_transfer.rs @@ -16,20 +16,20 @@ use rstest::rstest; use chainstate::{BlockError, ChainstateError, ConnectTransactionError}; -use chainstate_test_framework::{get_output_value, TestFramework, TransactionBuilder}; +use chainstate_test_framework::{TestFramework, TransactionBuilder, get_output_value}; use common::{ chain::{ + ChainstateUpgradeBuilder, Destination, NetUpgrades, OutPointSourceId, TokenIssuanceVersion, + TxInput, TxOutput, UtxoOutPoint, output_value::OutputValue, signature::inputsig::InputWitness, tokens::{NftIssuance, TokenId}, - ChainstateUpgradeBuilder, Destination, NetUpgrades, OutPointSourceId, TokenIssuanceVersion, - TxInput, TxOutput, UtxoOutPoint, }, primitives::{Amount, BlockHeight, CoinOrTokenId, Idable}, }; use randomness::RngExt; use test_utils::{ - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, token_utils::random_nft_issuance, }; @@ -60,9 +60,10 @@ fn nft_transfer_wrong_id(#[case] seed: Seed) { .unwrap() .unwrap(); let block = tf.block(*block_index.block_id()); - assert!(tf - .outputs_from_genblock(block.get_id().into()) - .contains_key(&issuance_outpoint_id)); + assert!( + tf.outputs_from_genblock(block.get_id().into()) + .contains_key(&issuance_outpoint_id) + ); // Try to transfer NFT with wrong ID let random_token_id = TokenId::random_using(&mut rng); diff --git a/chainstate/test-suite/src/tests/orders_tests.rs b/chainstate/test-suite/src/tests/orders_tests.rs index ee3f5ce2c2..0dc99f5e68 100644 --- a/chainstate/test-suite/src/tests/orders_tests.rs +++ b/chainstate/test-suite/src/tests/orders_tests.rs @@ -23,38 +23,39 @@ use chainstate::{ }; use chainstate_storage::Transactional as _; use chainstate_test_framework::{ + TestFramework, TransactionBuilder, helpers::{ calculate_fill_order, issue_and_mint_random_token_from_best_block, issue_random_nft_from_best_block, order_min_non_zero_fill_amount, }, - output_value_amount, TestFramework, TransactionBuilder, + output_value_amount, }; use common::{ address::pubkeyhash::PublicKeyHash, chain::{ - make_order_id, + AccountCommand, AccountNonce, AccountType, ChainstateUpgradeBuilder, Currency, Destination, + IdCreationError, OrderAccountCommand, OrderData, OrderId, OrdersVersion, RpcOrderInfo, + SignedTransaction, Transaction, TxInput, TxOutput, UtxoOutPoint, make_order_id, output_value::{OutputValue, RpcOutputValue}, signature::{ - inputsig::{standard_signature::StandardInputSignature, InputWitness}, + DestinationSigError, EvaluatedInputWitness, + inputsig::{InputWitness, standard_signature::StandardInputSignature}, sighash::{input_commitments::SighashInputCommitment, sighashtype::SigHashType}, - verify_signature, DestinationSigError, EvaluatedInputWitness, + verify_signature, }, tokens::{IsTokenFreezable, TokenId, TokenTotalSupply}, - AccountCommand, AccountNonce, AccountType, ChainstateUpgradeBuilder, Currency, Destination, - IdCreationError, OrderAccountCommand, OrderData, OrderId, OrdersVersion, RpcOrderInfo, - SignedTransaction, Transaction, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{Amount, BlockHeight, CoinOrTokenId, Idable, H256}, + primitives::{Amount, BlockHeight, CoinOrTokenId, H256, Idable}, }; use crypto::key::{KeyKind, PrivateKey}; use logging::log; use orders_accounting::OrdersAccountingStorageRead as _; use randomness::{CryptoRng, RngExt as _, SliceRandom}; -use test_utils::random::{gen_random_bytes, make_seedable_rng, Seed}; +use test_utils::random::{Seed, gen_random_bytes, make_seedable_rng}; use tx_verifier::{ + CheckTransactionError, error::{InputCheckError, InputCheckErrorPayload, ScriptError, TranslationError}, input_check::signature_only_check::verify_tx_signature, - CheckTransactionError, }; fn create_test_framework_with_orders( diff --git a/chainstate/test-suite/src/tests/output_timelock.rs b/chainstate/test-suite/src/tests/output_timelock.rs index 735c1344c8..2a594dce1d 100644 --- a/chainstate/test-suite/src/tests/output_timelock.rs +++ b/chainstate/test-suite/src/tests/output_timelock.rs @@ -17,11 +17,11 @@ use std::sync::Arc; use common::{ chain::{ - block::{timestamp::BlockTimestamp, GenBlock}, + OutPointSourceId, TxInput, TxOutput, + block::{GenBlock, timestamp::BlockTimestamp}, output_value::OutputValue, signature::inputsig::InputWitness, timelock::OutputTimeLock, - OutPointSourceId, TxInput, TxOutput, }, primitives::{Amount, BlockHeight, Id, Idable}, }; @@ -32,12 +32,12 @@ use super::helpers::add_block_with_locked_output; use chainstate::BlockError; use chainstate::ChainstateError; use chainstate::ConnectTransactionError; -use chainstate_test_framework::anyonecanspend_address; use chainstate_test_framework::TestFramework; use chainstate_test_framework::TransactionBuilder; +use chainstate_test_framework::anyonecanspend_address; use test_utils::{ mock_time_getter::mocked_time_getter_seconds, - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, }; use utils::atomics::SeqCstAtomicU64; diff --git a/chainstate/test-suite/src/tests/pos_accounting_reorg.rs b/chainstate/test-suite/src/tests/pos_accounting_reorg.rs index 03ebc2ee6b..9629db8dc5 100644 --- a/chainstate/test-suite/src/tests/pos_accounting_reorg.rs +++ b/chainstate/test-suite/src/tests/pos_accounting_reorg.rs @@ -21,20 +21,20 @@ use accounting::{DataDelta, DeltaAmountCollection, DeltaDataCollection}; use chainstate::BlockSource; use chainstate_storage::{BlockchainStorageWrite, TransactionRw, Transactional}; use chainstate_test_framework::{ - anyonecanspend_address, create_stake_pool_data_with_all_reward_to_staker, empty_witness, - TestFramework, TestStore, TransactionBuilder, + TestFramework, TestStore, TransactionBuilder, anyonecanspend_address, + create_stake_pool_data_with_all_reward_to_staker, empty_witness, }; use common::{ chain::{ - config::{create_unit_test_config, Builder as ConfigBuilder}, + AccountNonce, AccountOutPoint, AccountSpending, Destination, GenBlock, OutPointSourceId, + PoolId, TxInput, TxOutput, UtxoOutPoint, + config::{Builder as ConfigBuilder, create_unit_test_config}, make_delegation_id, output_value::OutputValue, stakelock::StakePoolData, timelock::OutputTimeLock, - AccountNonce, AccountOutPoint, AccountSpending, Destination, GenBlock, OutPointSourceId, - PoolId, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, Id, Idable, H256}, + primitives::{Amount, H256, Id, Idable, per_thousand::PerThousand}, }; use crypto::{ key::{KeyKind, PrivateKey}, @@ -43,7 +43,7 @@ use crypto::{ use pos_accounting::PoSAccountingDeltaData; use randomness::RngExt; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; // Produce `genesis -> a` chain, then a parallel `genesis -> b -> c` that should trigger a reorg. // Block `a` and block `c` have stake pool operation. diff --git a/chainstate/test-suite/src/tests/pos_maturity_settings.rs b/chainstate/test-suite/src/tests/pos_maturity_settings.rs index d25a943db9..f30c6a74ca 100644 --- a/chainstate/test-suite/src/tests/pos_maturity_settings.rs +++ b/chainstate/test-suite/src/tests/pos_maturity_settings.rs @@ -16,25 +16,25 @@ use super::helpers::pos::create_custom_genesis_with_stake_pool; use chainstate::{BlockError, ChainstateError, ConnectTransactionError}; -use chainstate_test_framework::{empty_witness, TestFramework, TransactionBuilder}; +use chainstate_test_framework::{TestFramework, TransactionBuilder, empty_witness}; use common::{ + Uint256, chain::{ + AccountNonce, AccountSpending, ConsensusUpgrade, Destination, NetUpgrades, + OutPointSourceId, PoSChainConfigBuilder, PoolId, TxInput, TxOutput, UtxoOutPoint, config::Builder as ConfigBuilder, make_delegation_id, output_value::OutputValue, - stakelock::StakePoolData, timelock::OutputTimeLock, AccountNonce, AccountSpending, - ConsensusUpgrade, Destination, NetUpgrades, OutPointSourceId, PoSChainConfigBuilder, - PoolId, TxInput, TxOutput, UtxoOutPoint, + stakelock::StakePoolData, timelock::OutputTimeLock, }, primitives::{ - per_thousand::PerThousand, Amount, BlockCount, BlockHeight, CoinOrTokenId, Idable, + Amount, BlockCount, BlockHeight, CoinOrTokenId, Idable, per_thousand::PerThousand, }, - Uint256, }; use crypto::{ key::{KeyKind, PrivateKey}, vrf::{VRFKeyKind, VRFPrivateKey}, }; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; #[rstest] #[trace] diff --git a/chainstate/test-suite/src/tests/pos_processing_tests.rs b/chainstate/test-suite/src/tests/pos_processing_tests.rs index 9076aee649..e5d20a57de 100644 --- a/chainstate/test-suite/src/tests/pos_processing_tests.rs +++ b/chainstate/test-suite/src/tests/pos_processing_tests.rs @@ -18,41 +18,41 @@ use std::{borrow::Cow, num::NonZeroU64, time::Duration}; use rstest::rstest; use chainstate::{ - chainstate_interface::ChainstateInterface, BlockError, BlockSource, ChainstateError, - CheckBlockError, ConnectTransactionError, SpendStakeError, + BlockError, BlockSource, ChainstateError, CheckBlockError, ConnectTransactionError, + SpendStakeError, chainstate_interface::ChainstateInterface, }; use chainstate_storage::Transactional; use chainstate_test_framework::{ - anyonecanspend_address, create_stake_pool_data_with_all_reward_to_staker, empty_witness, - TestFramework, TransactionBuilder, + TestFramework, TransactionBuilder, anyonecanspend_address, + create_stake_pool_data_with_all_reward_to_staker, empty_witness, }; use chainstate_types::{ - pos_randomness::{PoSRandomness, PoSRandomnessError}, - vrf_tools::{construct_transcript, ProofOfStakeVRFError}, EpochStorageRead, TipStorageTag, + pos_randomness::{PoSRandomness, PoSRandomnessError}, + vrf_tools::{ProofOfStakeVRFError, construct_transcript}, }; use common::{ + Uint256, chain::{ + AccountNonce, AccountOutPoint, AccountSpending, ChainConfig, ChainstateUpgradeBuilder, + ConsensusUpgrade, Destination, GenBlock, NetUpgrades, OutPointSourceId, PoSChainConfig, + PoSChainConfigBuilder, PoolId, RequiredConsensus, SignedTransaction, + StakerDestinationUpdateForbidden, TxInput, TxOutput, UtxoOutPoint, block::{ - consensus_data::PoSData, timestamp::BlockTimestamp, BlockRewardTransactable, - ConsensusData, + BlockRewardTransactable, ConsensusData, consensus_data::PoSData, + timestamp::BlockTimestamp, }, - config::{create_unit_test_config, Builder as ConfigBuilder, ChainType, EpochIndex}, + config::{Builder as ConfigBuilder, ChainType, EpochIndex, create_unit_test_config}, make_delegation_id, output_value::OutputValue, signature::{ - inputsig::{standard_signature::StandardInputSignature, InputWitness}, + inputsig::{InputWitness, standard_signature::StandardInputSignature}, sighash::{input_commitments::SighashInputCommitment, sighashtype::SigHashType}, }, stakelock::StakePoolData, timelock::OutputTimeLock, - AccountNonce, AccountOutPoint, AccountSpending, ChainConfig, ChainstateUpgradeBuilder, - ConsensusUpgrade, Destination, GenBlock, NetUpgrades, OutPointSourceId, PoSChainConfig, - PoSChainConfigBuilder, PoolId, RequiredConsensus, SignedTransaction, - StakerDestinationUpdateForbidden, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, BlockCount, BlockHeight, Id, Idable, H256}, - Uint256, + primitives::{Amount, BlockCount, BlockHeight, H256, Id, Idable, per_thousand::PerThousand}, }; use consensus::{BlockSignatureError, ConsensusPoSError, ConsensusVerificationError}; use crypto::{ @@ -63,7 +63,7 @@ use pos_accounting::PoSAccountingStorageRead; use randomness::{CryptoRng, RngExt as _}; use test_utils::{ assert_matches, - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, }; use utils::const_nz_u64; @@ -2174,12 +2174,11 @@ fn pos_decommission_genesis_pool(#[case] seed: Seed) { OutputValue::Coin(genesis_pool_balance) ); - assert!(PoSAccountingStorageRead::::get_pool_balance( - &tf.storage, - genesis_pool_id - ) - .unwrap() - .is_none()); + assert!( + PoSAccountingStorageRead::::get_pool_balance(&tf.storage, genesis_pool_id) + .unwrap() + .is_none() + ); assert!( PoSAccountingStorageRead::::get_pool_balance(&tf.storage, new_pool_id) .unwrap() diff --git a/chainstate/test-suite/src/tests/pos_retargeting_tests.rs b/chainstate/test-suite/src/tests/pos_retargeting_tests.rs index 85a632c993..77d8b62122 100644 --- a/chainstate/test-suite/src/tests/pos_retargeting_tests.rs +++ b/chainstate/test-suite/src/tests/pos_retargeting_tests.rs @@ -14,15 +14,15 @@ // limitations under the License. use chainstate::{ - chainstate_interface::ChainstateInterface, BlockError, ChainstateError, CheckBlockError, + BlockError, ChainstateError, CheckBlockError, chainstate_interface::ChainstateInterface, }; -use chainstate_test_framework::{anyonecanspend_address, TestFramework}; +use chainstate_test_framework::{TestFramework, anyonecanspend_address}; use chainstate_types::vrf_tools::construct_transcript; use common::{ chain::{ - block::{consensus_data::PoSData, timestamp::BlockTimestamp, ConsensusData}, - signature::inputsig::InputWitness, TxInput, TxOutput, + block::{ConsensusData, consensus_data::PoSData, timestamp::BlockTimestamp}, + signature::inputsig::InputWitness, }, primitives::Compact, }; @@ -32,7 +32,7 @@ use crypto::{ vrf::{VRFKeyKind, VRFPrivateKey}, }; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; #[rstest] #[trace] diff --git a/chainstate/test-suite/src/tests/processing_tests.rs b/chainstate/test-suite/src/tests/processing_tests.rs index aa3d4a79e3..df6c3a56d4 100644 --- a/chainstate/test-suite/src/tests/processing_tests.rs +++ b/chainstate/test-suite/src/tests/processing_tests.rs @@ -16,39 +16,38 @@ use std::{borrow::Cow, sync::Arc}; use chainstate::{ - chainstate_interface::ChainstateInterface, make_chainstate, BlockError, - BlockProcessingErrorClass, BlockProcessingErrorClassification, BlockSource, ChainstateConfig, - ChainstateError, CheckBlockError, CheckBlockTransactionsError, ConnectTransactionError, - DefaultTransactionVerificationStrategy, OrphanCheckError, + BlockError, BlockProcessingErrorClass, BlockProcessingErrorClassification, BlockSource, + ChainstateConfig, ChainstateError, CheckBlockError, CheckBlockTransactionsError, + ConnectTransactionError, DefaultTransactionVerificationStrategy, OrphanCheckError, + chainstate_interface::ChainstateInterface, make_chainstate, }; use chainstate_test_framework::{ - anyonecanspend_address, empty_witness, get_output_value, TestFramework, TestStore, - TransactionBuilder, + TestFramework, TestStore, TransactionBuilder, anyonecanspend_address, empty_witness, + get_output_value, }; use chainstate_types::{ BlockStatus, BlockValidationStage, GenBlockIndex, GetAncestorError, PropertyQueryError, }; use common::{ + Uint256, chain::{ - self, - block::{consensus_data::PoWData, timestamp::BlockTimestamp, ConsensusData}, - config::{create_unit_test_config, Builder as ConfigBuilder}, + self, Block, ConsensusUpgrade, Destination, GenBlock, NetUpgrades, PoolId, Transaction, + TxInput, TxOutput, UtxoOutPoint, + block::{ConsensusData, consensus_data::PoWData, timestamp::BlockTimestamp}, + config::{Builder as ConfigBuilder, create_unit_test_config}, output_value::OutputValue, signature::{ - inputsig::{standard_signature::StandardInputSignature, InputWitness}, - sighash::{input_commitments::SighashInputCommitment, sighashtype::SigHashType}, DestinationSigError, + inputsig::{InputWitness, standard_signature::StandardInputSignature}, + sighash::{input_commitments::SighashInputCommitment, sighashtype::SigHashType}, }, signed_transaction::SignedTransaction, stakelock::StakePoolData, timelock::OutputTimeLock, - Block, ConsensusUpgrade, Destination, GenBlock, NetUpgrades, PoolId, Transaction, TxInput, - TxOutput, UtxoOutPoint, }, primitives::{ - per_thousand::PerThousand, Amount, BlockCount, BlockHeight, Compact, Id, Idable, H256, + Amount, BlockCount, BlockHeight, Compact, H256, Id, Idable, per_thousand::PerThousand, }, - Uint256, }; use consensus::{ConsensusPoWError, ConsensusVerificationError}; use crypto::{ @@ -60,7 +59,7 @@ use rstest::rstest; use test_utils::{ assert_matches, assert_matches_return_val, mock_time_getter::mocked_time_getter_seconds, - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, }; use tx_verifier::{ error::{InputCheckError, ScriptError, TimelockError}, diff --git a/chainstate/test-suite/src/tests/reorgs_tests.rs b/chainstate/test-suite/src/tests/reorgs_tests.rs index 4a7bdbebfd..4279cb75d8 100644 --- a/chainstate/test-suite/src/tests/reorgs_tests.rs +++ b/chainstate/test-suite/src/tests/reorgs_tests.rs @@ -23,10 +23,10 @@ use chainstate::{ use chainstate_test_framework::TestFramework; use common::{ chain::{Block, GenBlock, Transaction, UtxoOutPoint}, - primitives::{id::Idable, BlockHeight, Id}, + primitives::{BlockHeight, Id, id::Idable}, }; use randomness::CryptoRng; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; // TODO use EventList from helpers instead. type EventList = Arc, BlockHeight)>>>; diff --git a/chainstate/test-suite/src/tests/signature_tests.rs b/chainstate/test-suite/src/tests/signature_tests.rs index 9e2dedaaac..c2e0dfa2ac 100644 --- a/chainstate/test-suite/src/tests/signature_tests.rs +++ b/chainstate/test-suite/src/tests/signature_tests.rs @@ -19,34 +19,34 @@ use rstest::rstest; use chainstate::ConnectTransactionError; use chainstate_test_framework::{ - anyonecanspend_address, empty_witness, TestFramework, TransactionBuilder, + TestFramework, TransactionBuilder, anyonecanspend_address, empty_witness, }; use common::{ address::pubkeyhash::PublicKeyHash, chain::{ - self, + self, ConsensusUpgrade, Destination, NetUpgrades, OutPointSourceId, TxInput, TxOutput, classic_multisig::ClassicMultisigChallenge, config::ChainType, output_value::OutputValue, signature::{ + DestinationSigError, inputsig::{ + InputWitness, classical_multisig::authorize_classical_multisig::AuthorizedClassicalMultisigSpend, - standard_signature::StandardInputSignature, InputWitness, + standard_signature::StandardInputSignature, }, sighash::{ input_commitments::SighashInputCommitment, sighashtype::SigHashType, signature_hash, }, - DestinationSigError, }, signed_transaction::SignedTransaction, - ConsensusUpgrade, Destination, NetUpgrades, OutPointSourceId, TxInput, TxOutput, }, primitives::{Amount, BlockHeight, Idable}, }; use crypto::key::{KeyKind, PrivateKey}; use randomness::{RngExt as _, SliceRandom}; use serialization::Encode; -use test_utils::random::{gen_random_bytes, Seed}; +use test_utils::random::{Seed, gen_random_bytes}; use tx_verifier::error::{InputCheckError, ScriptError}; #[rstest] diff --git a/chainstate/test-suite/src/tests/stake_pool_tests.rs b/chainstate/test-suite/src/tests/stake_pool_tests.rs index 9ac987b795..1c2bd2e7cb 100644 --- a/chainstate/test-suite/src/tests/stake_pool_tests.rs +++ b/chainstate/test-suite/src/tests/stake_pool_tests.rs @@ -20,24 +20,24 @@ use chainstate::{ IOPolicyError, }; use chainstate_test_framework::{ - anyonecanspend_address, create_stake_pool_data_with_all_reward_to_staker, empty_witness, - get_output_value, TestFramework, TransactionBuilder, + TestFramework, TransactionBuilder, anyonecanspend_address, + create_stake_pool_data_with_all_reward_to_staker, empty_witness, get_output_value, }; use chainstate_types::TipStorageTag; use common::{ chain::{ + AccountCommand, AccountNonce, Destination, GenBlock, OutPointSourceId, PoolId, + SignedTransaction, TxInput, TxOutput, UtxoOutPoint, output_value::OutputValue, signature::{ - inputsig::{standard_signature::StandardInputSignature, InputWitness}, DestinationSigError, + inputsig::{InputWitness, standard_signature::StandardInputSignature}, }, stakelock::StakePoolData, timelock::OutputTimeLock, tokens::TokenIssuance, - AccountCommand, AccountNonce, Destination, GenBlock, OutPointSourceId, PoolId, - SignedTransaction, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight, CoinOrTokenId, Id, Idable}, + primitives::{Amount, BlockHeight, CoinOrTokenId, Id, Idable, per_thousand::PerThousand}, }; use crypto::{ key::{KeyKind, PrivateKey}, @@ -46,7 +46,7 @@ use crypto::{ use pos_accounting::PoSAccountingStorageRead; use randomness::RngExt; use test_utils::{ - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, token_utils::random_token_issuance_v1, }; use tx_verifier::error::{InputCheckError, ScriptError}; diff --git a/chainstate/test-suite/src/tests/syncing_tests.rs b/chainstate/test-suite/src/tests/syncing_tests.rs index 77b6346236..0901ba90fe 100644 --- a/chainstate/test-suite/src/tests/syncing_tests.rs +++ b/chainstate/test-suite/src/tests/syncing_tests.rs @@ -25,19 +25,18 @@ use chainstate::{ use chainstate_test_framework::{TestFramework, TestFrameworkBuilder}; use chainstate_types::{BlockStatus, BlockValidationStage, PropertyQueryError}; use common::{ + Uint256, chain::{ - self, + self, Block, GenBlock, block::{signed_block_header::SignedBlockHeader, timestamp::BlockTimestamp}, - Block, GenBlock, }, - primitives::{BlockDistance, BlockHeight, Id, Idable, H256}, - Uint256, + primitives::{BlockDistance, BlockHeight, H256, Id, Idable}, }; use logging::log; use randomness::RngExt; use test_utils::{ assert_matches, - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, }; use tx_verifier::CheckTransactionError; diff --git a/chainstate/test-suite/src/tests/tokens_misc_tests.rs b/chainstate/test-suite/src/tests/tokens_misc_tests.rs index 38a92f95ec..97e76b8652 100644 --- a/chainstate/test-suite/src/tests/tokens_misc_tests.rs +++ b/chainstate/test-suite/src/tests/tokens_misc_tests.rs @@ -20,22 +20,22 @@ use rstest::rstest; use chainstate::{ChainstateError, PropertyQueryError}; use chainstate_test_framework::{ - helpers::{issue_token_from_block, issue_token_from_genesis, make_token_issuance}, TestFramework, TransactionBuilder, + helpers::{issue_token_from_block, issue_token_from_genesis, make_token_issuance}, }; use common::{ chain::{ + Destination, TxInput, TxOutput, UtxoOutPoint, output_value::OutputValue, signature::inputsig::InputWitness, tokens::{IsTokenFreezable, IsTokenFrozen, TokenId, TokenIssuance, TokenTotalSupply}, - Destination, TxInput, TxOutput, UtxoOutPoint, }, primitives::{Amount, BlockHeight, Idable}, }; use randomness::seq::IteratorRandom as _; use test_utils::{ assert_matches_return_val, - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, token_utils::random_nft_issuance, }; diff --git a/chainstate/test-suite/src/tests/tx_fee.rs b/chainstate/test-suite/src/tests/tx_fee.rs index f897869e78..c6538da9e5 100644 --- a/chainstate/test-suite/src/tests/tx_fee.rs +++ b/chainstate/test-suite/src/tests/tx_fee.rs @@ -17,21 +17,21 @@ use super::helpers::in_memory_storage_wrapper::InMemoryStorageWrapper; use super::*; use chainstate_test_framework::{ - create_stake_pool_data_with_all_reward_to_staker, empty_witness, TestFramework, TestStore, - TransactionBuilder, + TestFramework, TestStore, TransactionBuilder, create_stake_pool_data_with_all_reward_to_staker, + empty_witness, }; use common::{ chain::{ - config::{create_unit_test_config, ChainType}, + AccountCommand, AccountNonce, AccountSpending, ChainConfig, ChainstateUpgradeBuilder, + DelegationId, Destination, NetUpgrades, PoolId, TokenIssuanceVersion, TxInput, TxOutput, + UtxoOutPoint, + config::{ChainType, create_unit_test_config}, make_delegation_id, make_token_id, output_value::OutputValue, timelock::OutputTimeLock, tokens::{ IsTokenFreezable, TokenIssuance, TokenIssuanceV0, TokenIssuanceV1, TokenTotalSupply, }, - AccountCommand, AccountNonce, AccountSpending, ChainConfig, ChainstateUpgradeBuilder, - DelegationId, Destination, NetUpgrades, PoolId, TokenIssuanceVersion, TxInput, TxOutput, - UtxoOutPoint, }, primitives::{Amount, Fee, Idable}, }; diff --git a/chainstate/test-suite/src/tests/tx_verifier_among_threads.rs b/chainstate/test-suite/src/tests/tx_verifier_among_threads.rs index 79766fbe97..2037b78c9f 100644 --- a/chainstate/test-suite/src/tests/tx_verifier_among_threads.rs +++ b/chainstate/test-suite/src/tests/tx_verifier_among_threads.rs @@ -20,12 +20,12 @@ use common::chain::config::Builder as ConfigBuilder; use common::primitives::Amount; use common::{ chain::{DelegationId, OrderId, PoolId, UtxoOutPoint}, - primitives::{Id, H256}, + primitives::{H256, Id}, }; use orders_accounting::{OrderData, OrdersAccountingView}; use pos_accounting::PoSAccountingView; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use tokens_accounting::TokensAccountingView; use tx_verifier::transaction_verifier::TransactionVerifier; use utxo::{Utxo, UtxosView}; diff --git a/chainstate/test-suite/src/tests/tx_verifier_disconnect.rs b/chainstate/test-suite/src/tests/tx_verifier_disconnect.rs index 3639d77531..407f26e159 100644 --- a/chainstate/test-suite/src/tests/tx_verifier_disconnect.rs +++ b/chainstate/test-suite/src/tests/tx_verifier_disconnect.rs @@ -18,12 +18,12 @@ use super::*; use chainstate::ConnectTransactionError; use chainstate_test_framework::{ - anyonecanspend_address, empty_witness, TestFramework, TestStore, TransactionBuilder, + TestFramework, TestStore, TransactionBuilder, anyonecanspend_address, empty_witness, }; use common::{ chain::{ - config::Builder as ConfigBuilder, output_value::OutputValue, ChainConfig, GenBlockId, - OutPointSourceId, TxInput, TxOutput, + ChainConfig, GenBlockId, OutPointSourceId, TxInput, TxOutput, + config::Builder as ConfigBuilder, output_value::OutputValue, }, primitives::{Amount, Idable}, }; @@ -67,9 +67,11 @@ fn attempt_to_disconnect_tx_mainchain(#[case] seed: Seed, #[case] num_blocks: us let tx_id = tx.transaction().get_id(); // check if can be disconnected - assert!(!verifier - .can_disconnect_transaction(&TransactionSource::Chain(block_id), &tx_id) - .unwrap()); + assert!( + !verifier + .can_disconnect_transaction(&TransactionSource::Chain(block_id), &tx_id) + .unwrap() + ); // try to disconnect anyway let mut tmp_verifier = verifier.derive_child(); @@ -88,9 +90,11 @@ fn attempt_to_disconnect_tx_mainchain(#[case] seed: Seed, #[case] num_blocks: us let tx = block.transactions().first().unwrap(); let tx_id = tx.transaction().get_id(); - assert!(verifier - .can_disconnect_transaction(&TransactionSource::Chain(block_id), &tx_id) - .unwrap()); + assert!( + verifier + .can_disconnect_transaction(&TransactionSource::Chain(block_id), &tx_id) + .unwrap() + ); verifier .disconnect_transaction(&TransactionSource::Chain(block_id), tx) .unwrap(); @@ -165,12 +169,22 @@ fn connect_disconnect_tx_mempool(#[case] seed: Seed) { .unwrap(); // disconnect should work in proper order only: tx2 and then tx1 - assert!(!verifier - .can_disconnect_transaction(&TransactionSource::Mempool, &tx1.transaction().get_id()) - .unwrap()); - assert!(verifier - .can_disconnect_transaction(&TransactionSource::Mempool, &tx2.transaction().get_id()) - .unwrap()); + assert!( + !verifier + .can_disconnect_transaction( + &TransactionSource::Mempool, + &tx1.transaction().get_id() + ) + .unwrap() + ); + assert!( + verifier + .can_disconnect_transaction( + &TransactionSource::Mempool, + &tx2.transaction().get_id() + ) + .unwrap() + ); assert_eq!( verifier.disconnect_transaction(&TransactionSource::Mempool, &tx1), @@ -180,9 +194,14 @@ fn connect_disconnect_tx_mempool(#[case] seed: Seed) { ); verifier.disconnect_transaction(&TransactionSource::Mempool, &tx2).unwrap(); - assert!(verifier - .can_disconnect_transaction(&TransactionSource::Mempool, &tx1.transaction().get_id()) - .unwrap()); + assert!( + verifier + .can_disconnect_transaction( + &TransactionSource::Mempool, + &tx1.transaction().get_id() + ) + .unwrap() + ); verifier.disconnect_transaction(&TransactionSource::Mempool, &tx1).unwrap(); }); } @@ -257,12 +276,22 @@ fn connect_disconnect_tx_mempool_derived(#[case] seed: Seed) { // disconnect should work in proper order only: tx2 and then tx1 let mut child_verifier = verifier.derive_child(); - assert!(!child_verifier - .can_disconnect_transaction(&TransactionSource::Mempool, &tx1.transaction().get_id()) - .unwrap()); - assert!(child_verifier - .can_disconnect_transaction(&TransactionSource::Mempool, &tx2.transaction().get_id()) - .unwrap()); + assert!( + !child_verifier + .can_disconnect_transaction( + &TransactionSource::Mempool, + &tx1.transaction().get_id() + ) + .unwrap() + ); + assert!( + child_verifier + .can_disconnect_transaction( + &TransactionSource::Mempool, + &tx2.transaction().get_id() + ) + .unwrap() + ); assert_eq!( child_verifier.disconnect_transaction(&TransactionSource::Mempool, &tx1), @@ -279,9 +308,14 @@ fn connect_disconnect_tx_mempool_derived(#[case] seed: Seed) { let mut child_verifier = verifier.derive_child(); - assert!(child_verifier - .can_disconnect_transaction(&TransactionSource::Mempool, &tx1.transaction().get_id()) - .unwrap()); + assert!( + child_verifier + .can_disconnect_transaction( + &TransactionSource::Mempool, + &tx1.transaction().get_id() + ) + .unwrap() + ); child_verifier .disconnect_transaction(&TransactionSource::Mempool, &tx1) .unwrap(); diff --git a/chainstate/tx-verifier/src/lib.rs b/chainstate/tx-verifier/src/lib.rs index 043441ba00..27069a4059 100644 --- a/chainstate/tx-verifier/src/lib.rs +++ b/chainstate/tx-verifier/src/lib.rs @@ -16,7 +16,8 @@ pub mod transaction_verifier; pub use transaction_verifier::{ - check_transaction::{check_transaction, CheckTransactionError}, + TransactionSource, TransactionVerifier, + check_transaction::{CheckTransactionError, check_transaction}, error, flush::flush_to_storage, input_check, @@ -26,5 +27,4 @@ pub use transaction_verifier::{ }, timelock_check, tokens_check::{check_nft_issuance_data, check_tokens_issuance}, - TransactionSource, TransactionVerifier, }; diff --git a/chainstate/tx-verifier/src/transaction_verifier/accounting_undo_cache/cached_block_undo.rs b/chainstate/tx-verifier/src/transaction_verifier/accounting_undo_cache/cached_block_undo.rs index 35d55f3edd..7c8a7b6440 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/accounting_undo_cache/cached_block_undo.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/accounting_undo_cache/cached_block_undo.rs @@ -13,13 +13,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::{btree_map::Entry, BTreeMap}; +use std::collections::{BTreeMap, btree_map::Entry}; use std::fmt::Debug; use accounting::{BlockRewardUndo, BlockUndo, BlockUndoError, TxUndo}; use common::{chain::Transaction, primitives::Id}; -use crate::transaction_verifier::{cached_operation::combine, CachedOperation}; +use crate::transaction_verifier::{CachedOperation, cached_operation::combine}; #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct CachedBlockUndo { diff --git a/chainstate/tx-verifier/src/transaction_verifier/accounting_undo_cache/mod.rs b/chainstate/tx-verifier/src/transaction_verifier/accounting_undo_cache/mod.rs index 1471f505be..eb8693b0fa 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/accounting_undo_cache/mod.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/accounting_undo_cache/mod.rs @@ -13,10 +13,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::{btree_map::Entry, BTreeMap}; +use std::collections::{BTreeMap, btree_map::Entry}; use std::fmt::Debug; -use super::{error::ConnectTransactionError, CachedOperation, TransactionSource}; +use super::{CachedOperation, TransactionSource, error::ConnectTransactionError}; use accounting::{BlockRewardUndo, BlockUndoError, TxUndo}; use common::{chain::Transaction, primitives::Id}; diff --git a/chainstate/tx-verifier/src/transaction_verifier/accounting_undo_cache/tests.rs b/chainstate/tx-verifier/src/transaction_verifier/accounting_undo_cache/tests.rs index 4e80612d76..67e91bf551 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/accounting_undo_cache/tests.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/accounting_undo_cache/tests.rs @@ -16,12 +16,12 @@ use super::*; use crate::{ - transaction_verifier::{flush, storage::TransactionVerifierStorageRef, tests::mock}, TransactionVerifier, + transaction_verifier::{flush, storage::TransactionVerifierStorageRef, tests::mock}, }; use common::{ - chain::{config::Builder as ConfigBuilder, Block}, + chain::{Block, config::Builder as ConfigBuilder}, primitives::H256, }; use orders_accounting::OrdersAccountingDeltaUndoData; diff --git a/chainstate/tx-verifier/src/transaction_verifier/check_transaction.rs b/chainstate/tx-verifier/src/transaction_verifier/check_transaction.rs index d4ade5d00b..7503e16f68 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/check_transaction.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/check_transaction.rs @@ -18,12 +18,12 @@ use std::collections::BTreeSet; use chainstate_types::PropertyQueryError; use common::{ chain::{ - output_value::OutputValue, - signature::inputsig::InputWitness, - tokens::{get_tokens_issuance_count, NftIssuance}, AccountCommand, ChainConfig, ChangeTokenMetadataUriActivated, HtlcActivated, OrderId, OrdersVersion, SignedTransaction, TokenIssuanceVersion, Transaction, TransactionSize, TxInput, TxOutput, + output_value::OutputValue, + signature::inputsig::InputWitness, + tokens::{NftIssuance, get_tokens_issuance_count}, }, primitives::{Amount, BlockHeight, CoinOrTokenId, Id, Idable}, }; @@ -230,7 +230,7 @@ fn check_tokens_tx( match change_token_metadata_uri_activated { ChangeTokenMetadataUriActivated::Yes => { /* do nothing */ } ChangeTokenMetadataUriActivated::No => { - return Err(CheckTransactionError::ChangeTokenMetadataUriNotActivated) + return Err(CheckTransactionError::ChangeTokenMetadataUriNotActivated); } } @@ -464,7 +464,7 @@ fn check_order_inputs_outputs( common::chain::OrdersActivated::No => { return Err(CheckTransactionError::OrdersAreNotActivated( tx.transaction().get_id(), - )) + )); } } } diff --git a/chainstate/tx-verifier/src/transaction_verifier/error.rs b/chainstate/tx-verifier/src/transaction_verifier/error.rs index 8cb3b897b2..cedfa12155 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/error.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/error.rs @@ -16,10 +16,10 @@ use chainstate_types::GetAncestorError; use common::{ chain::{ - block::{Block, GenBlock}, - tokens::TokenId, AccountNonce, AccountType, DelegationId, IdCreationError, OrderId, OutPointSourceId, PoolId, Transaction, UtxoOutPoint, + block::{Block, GenBlock}, + tokens::TokenId, }, primitives::{Amount, BlockHeight, CoinOrTokenId, Id}, }; @@ -119,7 +119,9 @@ pub enum ConnectTransactionError { InputCheck(#[from] InputCheckError), #[error("Transaction {0} has conclude order input {1} with amounts that don't match the db")] ConcludeInputAmountsDontMatch(Id, OrderId), - #[error("ProduceBlockFromStake for block {0} modifies staker destination for pool {1}; this is no longer allowed")] + #[error( + "ProduceBlockFromStake for block {0} modifies staker destination for pool {1}; this is no longer allowed" + )] ProduceBlockFromStakeChangesStakerDestination(Id, PoolId), #[error("Id creation error: {0}")] IdCreationError(#[from] IdCreationError), diff --git a/chainstate/tx-verifier/src/transaction_verifier/flush.rs b/chainstate/tx-verifier/src/transaction_verifier/flush.rs index 53f07b1ffa..13c317a73d 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/flush.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/flush.rs @@ -14,9 +14,9 @@ // limitations under the License. use super::{ + CachedOperation, TransactionVerifierDelta, storage::{TransactionVerifierStorageMut, TransactionVerifierStorageRef}, token_issuance_cache::{CachedAuxDataOp, CachedTokenIndexOp, ConsumedTokenIssuanceCache}, - CachedOperation, TransactionVerifierDelta, }; use orders_accounting::FlushableOrdersAccountingView; use pos_accounting::FlushablePoSAccountingView; diff --git a/chainstate/tx-verifier/src/transaction_verifier/hierarchy.rs b/chainstate/tx-verifier/src/transaction_verifier/hierarchy.rs index 7bbe656739..292a581290 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/hierarchy.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/hierarchy.rs @@ -16,6 +16,7 @@ use std::collections::{BTreeMap, BTreeSet}; use super::{ + CachedOperation, TransactionSource, TransactionVerifier, accounting_undo_cache::CachedBlockUndo, storage::{ TransactionVerifierStorageError, TransactionVerifierStorageMut, @@ -23,14 +24,13 @@ use super::{ }, token_issuance_cache::{CachedAuxDataOp, CachedTokenIndexOp}, utxos_undo_cache::CachedUtxosBlockUndo, - CachedOperation, TransactionSource, TransactionVerifier, }; -use chainstate_types::{storage_result, GenBlockIndex, TipStorageTag}; +use chainstate_types::{GenBlockIndex, TipStorageTag, storage_result}; use common::{ chain::{ - tokens::{TokenAuxiliaryData, TokenId}, AccountNonce, AccountType, DelegationId, GenBlock, OrderId, PoolId, Transaction, UtxoOutPoint, + tokens::{TokenAuxiliaryData, TokenId}, }, primitives::{Amount, Id}, }; @@ -50,13 +50,13 @@ use tokens_accounting::{ use utxo::{ConsumedUtxoCache, FlushableUtxoView, UtxosStorageRead, UtxosView}; impl< - C, - S: TransactionVerifierStorageRef, - U: UtxosView, - A: PoSAccountingView, - T: TokensAccountingView, - O: OrdersAccountingView, - > TransactionVerifierStorageRef for TransactionVerifier + C, + S: TransactionVerifierStorageRef, + U: UtxosView, + A: PoSAccountingView, + T: TokensAccountingView, + O: OrdersAccountingView, +> TransactionVerifierStorageRef for TransactionVerifier where ::Error: From, { diff --git a/chainstate/tx-verifier/src/transaction_verifier/input_check/input_commitments.rs b/chainstate/tx-verifier/src/transaction_verifier/input_check/input_commitments.rs index 914a67e49e..feae00ae11 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/input_check/input_commitments.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/input_check/input_commitments.rs @@ -15,19 +15,18 @@ use common::{ chain::{ + ChainConfig, OrderId, PoolId, SignedTransaction, block::BlockRewardTransactable, signature::{ + Signable, sighash::{ self, input_commitments::{ - make_sighash_input_commitments_for_kernel_inputs, + SighashInputCommitment, make_sighash_input_commitments_for_kernel_inputs, make_sighash_input_commitments_for_transaction_inputs_at_height, - SighashInputCommitment, }, }, - Signable, }, - ChainConfig, OrderId, PoolId, SignedTransaction, }, primitives::BlockHeight, }; diff --git a/chainstate/tx-verifier/src/transaction_verifier/input_check/mod.rs b/chainstate/tx-verifier/src/transaction_verifier/input_check/mod.rs index e4aa330b1c..5c3b6f002c 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/input_check/mod.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/input_check/mod.rs @@ -21,23 +21,23 @@ use std::{borrow::Cow, convert::Infallible}; use chainstate_types::block_index_ancestor_getter; use common::{ chain::{ + ChainConfig, DelegationId, Destination, GenBlock, OrderId, PoolId, TxInput, TxOutput, block::timestamp::BlockTimestamp, signature::{ + DestinationSigError, Transactable, inputsig::InputWitness, sighash::{ self, input_commitments::{SighashInputCommitment, SighashInputCommitmentCreationError}, }, - DestinationSigError, Transactable, }, tokens::TokenId, - ChainConfig, DelegationId, Destination, GenBlock, OrderId, PoolId, TxInput, TxOutput, }, primitives::{BlockHeight, Id}, }; use mintscript::{ - translate::InputInfoProvider, InputInfo, SignatureContext, TimelockContext, TranslateInput, - WitnessScript, + InputInfo, SignatureContext, TimelockContext, TranslateInput, WitnessScript, + translate::InputInfoProvider, }; use utils::debug_assert_or_log; diff --git a/chainstate/tx-verifier/src/transaction_verifier/input_check/signature_only_check.rs b/chainstate/tx-verifier/src/transaction_verifier/input_check/signature_only_check.rs index 19350a7611..fe6598da4a 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/input_check/signature_only_check.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/input_check/signature_only_check.rs @@ -16,16 +16,16 @@ use std::convert::Infallible; use common::chain::{ + ChainConfig, DelegationId, Destination, PoolId, SignedTransaction, TxInput, TxOutput, partially_signed_transaction::PartiallySignedTransaction, signature::{ - inputsig::InputWitness, sighash::input_commitments::SighashInputCommitment, - DestinationSigError, Transactable, + DestinationSigError, Transactable, inputsig::InputWitness, + sighash::input_commitments::SighashInputCommitment, }, tokens::TokenId, - ChainConfig, DelegationId, Destination, PoolId, SignedTransaction, TxInput, TxOutput, }; use mintscript::{ - script::ScriptError, translate::InputInfoProvider, InputInfo, SignatureContext, TranslateInput, + InputInfo, SignatureContext, TranslateInput, script::ScriptError, translate::InputInfoProvider, }; use utils::ensure; diff --git a/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/mod.rs b/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/mod.rs index 092d32ddea..fd3e929d98 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/mod.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/mod.rs @@ -15,11 +15,11 @@ use common::{ chain::{ + Block, ChainConfig, TokenIssuanceVersion, Transaction, TxInput, TxOutput, block::{BlockRewardTransactable, ConsensusData}, output_value::OutputValue, signature::Signable, - tokens::{get_tokens_issuance_count, TokenId}, - Block, ChainConfig, TokenIssuanceVersion, Transaction, TxInput, TxOutput, + tokens::{TokenId, get_tokens_issuance_count}, }, primitives::{Amount, BlockHeight, Fee, Id, Idable, Subsidy}, }; @@ -134,13 +134,13 @@ pub fn check_reward_inputs_outputs_policy( [] => { return Err(ConnectTransactionError::SpendStakeError( SpendStakeError::NoBlockRewardOutputs, - )) + )); } [_] => { /* ok */ } _ => { return Err(ConnectTransactionError::SpendStakeError( SpendStakeError::MultipleBlockRewardOutputs, - )) + )); } }; } diff --git a/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/purposes_check.rs b/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/purposes_check.rs index 25c36a96b4..7f5a475d46 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/purposes_check.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/purposes_check.rs @@ -15,8 +15,8 @@ use common::{ chain::{ - block::BlockRewardTransactable, signature::Signable, Block, ChainConfig, - StakerDestinationUpdateForbidden, Transaction, TxInput, TxOutput, + Block, ChainConfig, StakerDestinationUpdateForbidden, Transaction, TxInput, TxOutput, + block::BlockRewardTransactable, signature::Signable, }, primitives::{BlockHeight, Id}, }; @@ -58,7 +58,7 @@ pub fn check_reward_inputs_outputs_purposes( [] => { return Err(ConnectTransactionError::SpendStakeError( SpendStakeError::ConsensusPoSError(ConsensusPoSError::NoKernel), - )) + )); } // single input [intput_utxo] => match intput_utxo { @@ -75,7 +75,7 @@ pub fn check_reward_inputs_outputs_purposes( return Err(ConnectTransactionError::IOPolicyError( IOPolicyError::InvalidInputTypeInReward, block_id.into(), - )) + )); } TxOutput::CreateStakePool(input_pool_id, input_pool_data) => { (input_pool_id, input_pool_data.staker()) @@ -88,7 +88,7 @@ pub fn check_reward_inputs_outputs_purposes( _ => { return Err(ConnectTransactionError::SpendStakeError( SpendStakeError::ConsensusPoSError(ConsensusPoSError::MultipleKernels), - )) + )); } }; @@ -99,7 +99,7 @@ pub fn check_reward_inputs_outputs_purposes( [] => { return Err(ConnectTransactionError::SpendStakeError( SpendStakeError::NoBlockRewardOutputs, - )) + )); } [output] => match output { TxOutput::Transfer(..) @@ -116,7 +116,7 @@ pub fn check_reward_inputs_outputs_purposes( return Err(ConnectTransactionError::IOPolicyError( IOPolicyError::InvalidOutputTypeInReward, block_id.into(), - )) + )); } TxOutput::ProduceBlockFromStake(output_staker_destination, output_pool_id) => { (output_staker_destination, output_pool_id) @@ -125,7 +125,7 @@ pub fn check_reward_inputs_outputs_purposes( _ => { return Err(ConnectTransactionError::SpendStakeError( SpendStakeError::MultipleBlockRewardOutputs, - )) + )); } }; diff --git a/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/constraints_tests.rs b/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/constraints_tests.rs index 56cd25f424..98684a80e7 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/constraints_tests.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/constraints_tests.rs @@ -19,18 +19,18 @@ use rstest::rstest; use common::{ chain::{ + AccountNonce, AccountSpending, Destination, NetUpgrades, PoolId, TxOutput, config::ChainType, output_value::OutputValue, stakelock::StakePoolData, - timelock::OutputTimeLock, AccountNonce, AccountSpending, Destination, NetUpgrades, PoolId, - TxOutput, + timelock::OutputTimeLock, }, - primitives::{per_thousand::PerThousand, Amount, CoinOrTokenId, H256}, + primitives::{Amount, CoinOrTokenId, H256, per_thousand::PerThousand}, }; use crypto::vrf::{VRFKeyKind, VRFPrivateKey}; use orders_accounting::{InMemoryOrdersAccounting, OrdersAccountingDB}; use pos_accounting::DelegationData; use randomness::{CryptoRng, Rng, RngExt as _, SliceRandom}; use test_utils::{ - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, split_value, }; diff --git a/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/mod.rs b/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/mod.rs index 42adc26d79..1793024914 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/mod.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/mod.rs @@ -17,15 +17,15 @@ use std::collections::BTreeMap; use common::{ chain::{ - block::{consensus_data::PoSData, timestamp::BlockTimestamp, BlockReward, ConsensusData}, Block, DelegationId, GenBlock, OutPointSourceId, PoolId, TxInput, TxOutput, UtxoOutPoint, + block::{BlockReward, ConsensusData, consensus_data::PoSData, timestamp::BlockTimestamp}, }, - primitives::{Compact, Id, H256}, + primitives::{Compact, H256, Id}, }; -use crypto::vrf::{transcript::no_rng::VRFTranscript, VRFKeyKind, VRFPrivateKey, VRFPublicKey}; +use crypto::vrf::{VRFKeyKind, VRFPrivateKey, VRFPublicKey, transcript::no_rng::VRFTranscript}; use itertools::Itertools; -use randomness::{seq::IteratorRandom, Rng}; -use test_utils::random::{make_seedable_rng, Seed}; +use randomness::{Rng, seq::IteratorRandom}; +use test_utils::random::{Seed, make_seedable_rng}; use utxo::{Utxo, UtxosDBInMemoryImpl}; use super::*; diff --git a/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/outputs_utils.rs b/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/outputs_utils.rs index f065b5c24e..784438b181 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/outputs_utils.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/outputs_utils.rs @@ -15,6 +15,8 @@ use common::{ chain::{ + AccountCommand, AccountNonce, AccountSpending, DelegationId, Destination, OrderData, + OrderId, PoolId, TxInput, TxOutput, htlc::{HashedTimelockContract, HtlcSecretHash}, output_value::OutputValue, stakelock::StakePoolData, @@ -23,10 +25,8 @@ use common::{ IsTokenFreezable, IsTokenUnfreezable, Metadata, NftIssuance, NftIssuanceV0, TokenId, TokenIssuance, TokenIssuanceV1, TokenTotalSupply, }, - AccountCommand, AccountNonce, AccountSpending, DelegationId, Destination, OrderData, - OrderId, PoolId, TxInput, TxOutput, }, - primitives::{per_thousand::PerThousand, Amount, H256}, + primitives::{Amount, H256, per_thousand::PerThousand}, }; use serialization::extras::non_empty_vec::DataOrNoVec; diff --git a/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/purpose_tests.rs b/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/purpose_tests.rs index 004c2f19b8..7f33244f20 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/purpose_tests.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/purpose_tests.rs @@ -19,16 +19,16 @@ use rstest::rstest; use common::{ chain::{ - self, stakelock::StakePoolData, ChainstateUpgradeBuilder, Destination, GenBlock, - NetUpgrades, OutPointSourceId, StakerDestinationUpdateForbidden, TxInput, UtxoOutPoint, + self, ChainstateUpgradeBuilder, Destination, GenBlock, NetUpgrades, OutPointSourceId, + StakerDestinationUpdateForbidden, TxInput, UtxoOutPoint, stakelock::StakePoolData, }, - primitives::{per_thousand::PerThousand, Id, H256}, + primitives::{H256, Id, per_thousand::PerThousand}, }; use crypto::key::{KeyKind, PrivateKey}; use randomness::{RngExt as _, SliceRandom}; use test_utils::{ assert_matches, - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, }; use utxo::{Utxo, UtxosDBInMemoryImpl}; diff --git a/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/reward_tests.rs b/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/reward_tests.rs index 4337eb6f0b..a4945f5712 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/reward_tests.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/input_output_policy/tests/reward_tests.rs @@ -16,19 +16,19 @@ use super::*; use common::{ chain::{ + Destination, GenBlock, PoolId, UtxoOutPoint, block::consensus_data::{PoSData, PoWData}, config::ChainType, output_value::OutputValue, stakelock::StakePoolData, timelock::OutputTimeLock, - Destination, GenBlock, PoolId, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, CoinOrTokenId, Compact, H256}, + primitives::{CoinOrTokenId, Compact, H256, per_thousand::PerThousand}, }; use crypto::vrf::{VRFKeyKind, VRFPrivateKey}; use randomness::RngExt; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; #[rstest] #[trace] diff --git a/chainstate/tx-verifier/src/transaction_verifier/mod.rs b/chainstate/tx-verifier/src/transaction_verifier/mod.rs index 8cf1f08a9a..676f0e30f1 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/mod.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/mod.rs @@ -50,7 +50,7 @@ pub use accounting_undo_cache::CachedBlockUndo; mod utxos_undo_cache; pub use utxos_undo_cache::CachedUtxosBlockUndo; -pub use input_output_policy::{calculate_tokens_burned_in_outputs, IOPolicyError}; +pub use input_output_policy::{IOPolicyError, calculate_tokens_burned_in_outputs}; use std::collections::{BTreeMap, BTreeSet}; @@ -63,21 +63,21 @@ use self::{ utxos_undo_cache::{CachedUtxoBlockUndoOp, UtxosBlockUndoCache}, }; use ::utils::{ensure, shallow_clone::ShallowClone}; -pub use reward_distribution::{distribute_pos_reward, RewardDistributionError}; +pub use reward_distribution::{RewardDistributionError, distribute_pos_reward}; use chainstate_types::{BlockIndex, TipStorageTag}; use common::{ chain::{ - block::{timestamp::BlockTimestamp, BlockRewardTransactable, ConsensusData}, + AccountCommand, AccountNonce, AccountSpending, AccountType, Block, ChainConfig, + DelegationId, FrozenTokensValidationVersion, GenBlock, OrderAccountCommand, OrdersVersion, + Transaction, TxInput, TxOutput, UtxoOutPoint, + block::{BlockRewardTransactable, ConsensusData, timestamp::BlockTimestamp}, make_delegation_id, make_order_id, make_pool_id, make_token_id, output_value::OutputValue, signature::Signable, signed_transaction::SignedTransaction, - AccountCommand, AccountNonce, AccountSpending, AccountType, Block, ChainConfig, - DelegationId, FrozenTokensValidationVersion, GenBlock, OrderAccountCommand, OrdersVersion, - Transaction, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{id::WithId, Amount, BlockHeight, Fee, Id, Idable}, + primitives::{Amount, BlockHeight, Fee, Id, Idable, id::WithId}, }; use pos_accounting::{ PoSAccountingDB, PoSAccountingDelta, PoSAccountingDeltaData, PoSAccountingOperations, @@ -1222,10 +1222,10 @@ where ) -> Result<(), input_check::InputCheckError> where Tx: input_check::FullyVerifiable< - PoSAccountingDelta, - TokensAccountingCache, - OrdersAccountingCache, - >, + PoSAccountingDelta, + TokensAccountingCache, + OrdersAccountingCache, + >, { input_check::verify_full( tx, diff --git a/chainstate/tx-verifier/src/transaction_verifier/pos_accounting_delta_adapter.rs b/chainstate/tx-verifier/src/transaction_verifier/pos_accounting_delta_adapter.rs index 896cb417ab..f45b20b140 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/pos_accounting_delta_adapter.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/pos_accounting_delta_adapter.rs @@ -15,7 +15,7 @@ use std::collections::BTreeMap; -use super::{storage::TransactionVerifierStorageError, TransactionSource}; +use super::{TransactionSource, storage::TransactionVerifierStorageError}; use common::{ chain::{DelegationId, PoolId}, diff --git a/chainstate/tx-verifier/src/transaction_verifier/reward_distribution.rs b/chainstate/tx-verifier/src/transaction_verifier/reward_distribution.rs index 73d007eb56..ee58cb335a 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/reward_distribution.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/reward_distribution.rs @@ -17,12 +17,11 @@ use static_assertions::assert_eq_size; use std::collections::BTreeMap; use common::{ - amount_sum, + Uint256, amount_sum, chain::{Block, DelegationId, PoolId, RewardDistributionVersion}, primitives::{ - amount::UnsignedIntType as AmountUIntType, per_thousand::PerThousand, Amount, Id, + Amount, Id, amount::UnsignedIntType as AmountUIntType, per_thousand::PerThousand, }, - Uint256, }; use pos_accounting::{PoSAccountingOperations, PoSAccountingView}; use thiserror::Error; @@ -50,7 +49,9 @@ pub enum RewardDistributionError { "Reward in block {0} for the pool {1} staker which is {2:?} cannot be bigger than total reward {3:?}" )] StakerRewardCannotExceedTotalReward(Id, PoolId, Amount, Amount), - #[error("Actually distributed delegation rewards {0} for pool {1} in block {2:?} is bigger then total delegations reward {3:?}")] + #[error( + "Actually distributed delegation rewards {0} for pool {1} in block {2:?} is bigger then total delegations reward {3:?}" + )] DistributedDelegationsRewardExceedTotal(PoolId, Id, Amount, Amount), #[error("Reward for delegation {0} overflowed: {1:?}*{2:?}/{3:?}")] DelegationRewardOverflow(DelegationId, Amount, Amount, Amount), @@ -317,15 +318,15 @@ fn calculate_rewards_per_delegation<'a, I: Iterator PoolId { PoolId::new(H256::from_low_u64_be(v)) @@ -534,33 +535,39 @@ mod tests { ), Err(RewardDistributionError::InvariantPoolBalanceIsZero(pool_id)) ); - assert!(calculate_staker_reward_v1( - reward, - pool_balance, - staker_balance, - Amount::ZERO, - mpt_zero, - pool_id - ) - .is_ok()); - assert!(calculate_staker_reward_v1( - reward, - pool_balance, - staker_balance, - Amount::ZERO, - mpt, - pool_id - ) - .is_ok()); - assert!(calculate_staker_reward_v1( - reward, - pool_balance, - Amount::ZERO, - Amount::ZERO, - mpt, - pool_id - ) - .is_ok()); + assert!( + calculate_staker_reward_v1( + reward, + pool_balance, + staker_balance, + Amount::ZERO, + mpt_zero, + pool_id + ) + .is_ok() + ); + assert!( + calculate_staker_reward_v1( + reward, + pool_balance, + staker_balance, + Amount::ZERO, + mpt, + pool_id + ) + .is_ok() + ); + assert!( + calculate_staker_reward_v1( + reward, + pool_balance, + Amount::ZERO, + Amount::ZERO, + mpt, + pool_id + ) + .is_ok() + ); // negative amount assert_eq!( calculate_staker_reward_v1( @@ -586,15 +593,17 @@ mod tests { Ok(reward) ); // overflow - assert!(calculate_staker_reward_v1( - Amount::MAX, - pool_balance, - staker_balance, - cost_per_block, - mpt_more_than_one, - pool_id - ) - .is_ok()); + assert!( + calculate_staker_reward_v1( + Amount::MAX, + pool_balance, + staker_balance, + cost_per_block, + mpt_more_than_one, + pool_id + ) + .is_ok() + ); // arbitrary values assert_eq!( diff --git a/chainstate/tx-verifier/src/transaction_verifier/storage.rs b/chainstate/tx-verifier/src/transaction_verifier/storage.rs index 69621de1ab..c5a33e3de7 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/storage.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/storage.rs @@ -15,11 +15,11 @@ use std::ops::Deref; -use chainstate_types::{storage_result, GenBlockIndex, TipStorageTag}; +use chainstate_types::{GenBlockIndex, TipStorageTag, storage_result}; use common::{ chain::{ - tokens::{TokenAuxiliaryData, TokenId}, AccountNonce, AccountType, Block, GenBlock, Transaction, + tokens::{TokenAuxiliaryData, TokenId}, }, primitives::Id, }; @@ -36,8 +36,8 @@ use tokens_accounting::{ use utxo::{FlushableUtxoView, UtxosStorageRead}; use super::{ - accounting_undo_cache::CachedBlockUndo, error::TokensError, - utxos_undo_cache::CachedUtxosBlockUndo, TransactionSource, + TransactionSource, accounting_undo_cache::CachedBlockUndo, error::TokensError, + utxos_undo_cache::CachedUtxosBlockUndo, }; #[derive(Error, Debug, PartialEq, Eq, Clone)] diff --git a/chainstate/tx-verifier/src/transaction_verifier/tests/hierarchy_read.rs b/chainstate/tx-verifier/src/transaction_verifier/tests/hierarchy_read.rs index 6589342432..b52b7c3de3 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/tests/hierarchy_read.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/tests/hierarchy_read.rs @@ -22,9 +22,9 @@ use super::*; use chainstate_types::GenBlockIndex; use common::{ chain::{ + DelegationId, PoolId, config::Builder as ConfigBuilder, tokens::{IsTokenFreezable, IsTokenFrozen, TokenAuxiliaryData, TokenId, TokenTotalSupply}, - DelegationId, PoolId, }, primitives::H256, }; diff --git a/chainstate/tx-verifier/src/transaction_verifier/tests/hierarchy_write.rs b/chainstate/tx-verifier/src/transaction_verifier/tests/hierarchy_write.rs index 600744fbb7..637037759f 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/tests/hierarchy_write.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/tests/hierarchy_write.rs @@ -18,9 +18,9 @@ use rstest::rstest; use accounting::TxUndo; use common::chain::{ + DelegationId, PoolId, config::Builder as ConfigBuilder, tokens::{IsTokenFreezable, IsTokenFrozen, TokenAuxiliaryData, TokenId, TokenTotalSupply}, - DelegationId, PoolId, }; use orders_accounting::OrdersAccountingDeltaUndoData; use pos_accounting::DeltaMergeUndo; diff --git a/chainstate/tx-verifier/src/transaction_verifier/tests/mock.rs b/chainstate/tx-verifier/src/transaction_verifier/tests/mock.rs index 59e5c7f176..5599b23da9 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/tests/mock.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/tests/mock.rs @@ -18,19 +18,19 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::transaction_verifier::TransactionSource; use super::{ + CachedUtxosBlockUndo, accounting_undo_cache::CachedBlockUndo, storage::{ TransactionVerifierStorageError, TransactionVerifierStorageMut, TransactionVerifierStorageRef, }, - CachedUtxosBlockUndo, }; -use chainstate_types::{storage_result, GenBlockIndex, TipStorageTag}; +use chainstate_types::{GenBlockIndex, TipStorageTag, storage_result}; use common::{ chain::{ - tokens::{TokenAuxiliaryData, TokenId}, AccountNonce, AccountType, DelegationId, GenBlock, OrderId, PoolId, Transaction, UtxoOutPoint, + tokens::{TokenAuxiliaryData, TokenId}, }, primitives::{Amount, Id}, }; diff --git a/chainstate/tx-verifier/src/transaction_verifier/tests/mod.rs b/chainstate/tx-verifier/src/transaction_verifier/tests/mod.rs index 3a9c1a4214..4cf0f5dd87 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/tests/mod.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/tests/mod.rs @@ -20,10 +20,10 @@ pub mod mock; use super::*; use common::{ chain::{ - output_value::OutputValue, stakelock::StakePoolData, Destination, OutPointSourceId, - UtxoOutPoint, + Destination, OutPointSourceId, UtxoOutPoint, output_value::OutputValue, + stakelock::StakePoolData, }, - primitives::{amount::UnsignedIntType, per_thousand::PerThousand, BlockHeight, H256}, + primitives::{BlockHeight, H256, amount::UnsignedIntType, per_thousand::PerThousand}, }; use crypto::{ key::{KeyKind, PrivateKey}, diff --git a/chainstate/tx-verifier/src/transaction_verifier/timelock_check.rs b/chainstate/tx-verifier/src/transaction_verifier/timelock_check.rs index 88108dd411..11921fe787 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/timelock_check.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/timelock_check.rs @@ -14,7 +14,7 @@ // limitations under the License. use common::{ - chain::{block::timestamp::BlockTimestamp, timelock::OutputTimeLock, UtxoOutPoint}, + chain::{UtxoOutPoint, block::timestamp::BlockTimestamp, timelock::OutputTimeLock}, primitives::{BlockCount, BlockHeight}, }; use mintscript::checker::TimelockChecker as _; diff --git a/chainstate/tx-verifier/src/transaction_verifier/token_issuance_cache.rs b/chainstate/tx-verifier/src/transaction_verifier/token_issuance_cache.rs index 4fa7723a87..9027b3797e 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/token_issuance_cache.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/token_issuance_cache.rs @@ -13,23 +13,22 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::{btree_map::Entry, BTreeMap}; +use std::collections::{BTreeMap, btree_map::Entry}; use common::{ chain::{ - make_token_id, + Block, ChainConfig, Transaction, TxOutput, make_token_id, tokens::{TokenAuxiliaryData, TokenId}, - Block, ChainConfig, Transaction, TxOutput, }, - primitives::{BlockHeight, Id, Idable, H256}, + primitives::{BlockHeight, H256, Id, Idable}, }; use utils::ensure; use crate::error::TokenIssuanceError; use super::{ - error::{ConnectTransactionError, TokensError}, CachedOperation, + error::{ConnectTransactionError, TokensError}, }; pub type CachedAuxDataOp = CachedOperation; @@ -164,7 +163,7 @@ impl TokenIssuanceCache { Entry::Vacant(_) => { return Err(TokensError::InvariantBrokenUndoIssuanceOnNonexistentToken( token_id, - )) + )); } } self.del_token_id(&tx.get_id())?; diff --git a/chainstate/tx-verifier/src/transaction_verifier/tokens_check/check_utils.rs b/chainstate/tx-verifier/src/transaction_verifier/tokens_check/check_utils.rs index 97fc4b781f..16a380890e 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/tokens_check/check_utils.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/tokens_check/check_utils.rs @@ -15,7 +15,7 @@ use crate::error::TokenIssuanceError; -use common::chain::{tokens::is_rfc3986_valid_symbol, ChainConfig}; +use common::chain::{ChainConfig, tokens::is_rfc3986_valid_symbol}; use utils::ensure; fn check_is_text_ascii_alphanumeric(str: &[u8]) -> bool { diff --git a/chainstate/tx-verifier/src/transaction_verifier/tokens_check/mod.rs b/chainstate/tx-verifier/src/transaction_verifier/tokens_check/mod.rs index e4957add41..46e0631aae 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/tokens_check/mod.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/tokens_check/mod.rs @@ -18,8 +18,8 @@ use self::check_utils::check_media_hash; use crate::error::TokenIssuanceError; use common::chain::{ - tokens::{NftIssuanceV0, TokenIssuance}, ChainConfig, + tokens::{NftIssuanceV0, TokenIssuance}, }; use serialization::{DecodeAll, Encode}; use utils::ensure; diff --git a/chainstate/tx-verifier/src/transaction_verifier/utxos_undo_cache/cached_utxo_block_undo.rs b/chainstate/tx-verifier/src/transaction_verifier/utxos_undo_cache/cached_utxo_block_undo.rs index 9db342e6fe..8c9d8b1677 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/utxos_undo_cache/cached_utxo_block_undo.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/utxos_undo_cache/cached_utxo_block_undo.rs @@ -13,9 +13,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::{btree_map::Entry, BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, btree_map::Entry}; -use crate::transaction_verifier::{cached_operation::combine, CachedOperation}; +use crate::transaction_verifier::{CachedOperation, cached_operation::combine}; use common::{ chain::{OutPointSourceId, Transaction}, primitives::Id, diff --git a/chainstate/tx-verifier/src/transaction_verifier/utxos_undo_cache/mod.rs b/chainstate/tx-verifier/src/transaction_verifier/utxos_undo_cache/mod.rs index d3e9cb2dba..6499c3cdd6 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/utxos_undo_cache/mod.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/utxos_undo_cache/mod.rs @@ -13,9 +13,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::{btree_map::Entry, BTreeMap}; +use std::collections::{BTreeMap, btree_map::Entry}; -use super::{error::ConnectTransactionError, CachedOperation, TransactionSource}; +use super::{CachedOperation, TransactionSource, error::ConnectTransactionError}; use common::{chain::Transaction, primitives::Id}; use utxo::{UtxosBlockRewardUndo, UtxosTxUndo, UtxosTxUndoWithSources}; diff --git a/chainstate/tx-verifier/src/transaction_verifier/utxos_undo_cache/tests.rs b/chainstate/tx-verifier/src/transaction_verifier/utxos_undo_cache/tests.rs index 6473fefa66..286c35c30f 100644 --- a/chainstate/tx-verifier/src/transaction_verifier/utxos_undo_cache/tests.rs +++ b/chainstate/tx-verifier/src/transaction_verifier/utxos_undo_cache/tests.rs @@ -16,16 +16,16 @@ use super::*; use crate::{ + TransactionVerifier, transaction_verifier::{ flush, storage::TransactionVerifierStorageRef, tests::{create_utxo, mock}, }, - TransactionVerifier, }; use common::{ - chain::{config::Builder as ConfigBuilder, Block}, + chain::{Block, config::Builder as ConfigBuilder}, primitives::H256, }; use orders_accounting::OrdersAccountingDeltaUndoData; diff --git a/chainstate/types/src/ancestor.rs b/chainstate/types/src/ancestor.rs index b3a71e386d..d0f27f00ca 100644 --- a/chainstate/types/src/ancestor.rs +++ b/chainstate/types/src/ancestor.rs @@ -21,8 +21,8 @@ use common::{ }; use crate::{ - get_skip_height, storage_result, BlockIndexHandle, GenBlockIndex, GetAncestorError, - PropertyQueryError, + BlockIndexHandle, GenBlockIndex, GetAncestorError, PropertyQueryError, get_skip_height, + storage_result, }; pub enum AncestorGetterStartingPoint<'a> { diff --git a/chainstate/types/src/block_index.rs b/chainstate/types/src/block_index.rs index 2c7a686509..8caa88d737 100644 --- a/chainstate/types/src/block_index.rs +++ b/chainstate/types/src/block_index.rs @@ -13,11 +13,11 @@ // See the License for the specific language governing permissions and // limitations under the License. +use common::Uint256; use common::chain::block::signed_block_header::SignedBlockHeader; use common::chain::block::timestamp::BlockTimestamp; use common::chain::{Block, GenBlock}; -use common::primitives::{BlockHeight, Id, Idable, H256}; -use common::Uint256; +use common::primitives::{BlockHeight, H256, Id, Idable}; use serialization::{Decode, Encode}; use static_assertions::assert_not_impl_any; diff --git a/chainstate/types/src/block_index_handle.rs b/chainstate/types/src/block_index_handle.rs index d41690d59d..6e38148334 100644 --- a/chainstate/types/src/block_index_handle.rs +++ b/chainstate/types/src/block_index_handle.rs @@ -15,7 +15,7 @@ use crate::{BlockIndex, GenBlockIndex, PropertyQueryError}; use common::{ - chain::{block::BlockReward, Block, GenBlock}, + chain::{Block, GenBlock, block::BlockReward}, primitives::{BlockHeight, Id}, }; diff --git a/chainstate/types/src/block_status.rs b/chainstate/types/src/block_status.rs index ff95fd1795..97cfd456f7 100644 --- a/chainstate/types/src/block_status.rs +++ b/chainstate/types/src/block_status.rs @@ -176,7 +176,7 @@ const FAIL_BITS_RANGE: Range = Range:: { #[cfg(test)] mod tests { use super::*; - use std::panic::{catch_unwind, AssertUnwindSafe}; + use std::panic::{AssertUnwindSafe, catch_unwind}; #[test] fn test_bit_range_of() { @@ -279,10 +279,12 @@ mod tests { ); // Set a value that is too big for the range. - assert!(catch_unwind(AssertUnwindSafe( - || status.set_bits(0..25, 0b11_11111111_11111111_11111111) - )) - .is_err()); + assert!( + catch_unwind(AssertUnwindSafe( + || status.set_bits(0..25, 0b11_11111111_11111111_11111111) + )) + .is_err() + ); assert_eq!( status.0, 0b11110000_11001100_10101010_11100111_10101010_10101111_11111111_11111111 @@ -359,39 +361,49 @@ mod tests { #[allow(clippy::unusual_byte_groupings)] #[test] fn test_set_field_panic_if_value_too_big() { - assert!(catch_unwind(|| { - let mut status = BlockStatus(0); - status.set_field(BlockStatusBitArea::ValidationStage, 0b1_00000000); - }) - .is_err()); - - assert!(catch_unwind(|| { - let mut status = BlockStatus(0); - status.set_field(BlockStatusBitArea::ValidationFailedBit, 2); - }) - .is_err()); - - assert!(catch_unwind(|| { - let mut status = BlockStatus(0); - status.set_field(BlockStatusBitArea::InvalidParentBit, 2); - }) - .is_err()); - - assert!(catch_unwind(|| { - let mut status = BlockStatus(0); - status.set_field(BlockStatusBitArea::ExplicitlyInvalidatedBit, 2); - }) - .is_err()); - - assert!(catch_unwind(|| { - let mut status = BlockStatus(0); - status.set_field( - BlockStatusBitArea::ReservedArea, - // This is the value from test_set_field but with an additional 1 an the end. - 0b10101010_10101010_10101010_10101010_10101010_10101010_101011, - ); - }) - .is_err()); + assert!( + catch_unwind(|| { + let mut status = BlockStatus(0); + status.set_field(BlockStatusBitArea::ValidationStage, 0b1_00000000); + }) + .is_err() + ); + + assert!( + catch_unwind(|| { + let mut status = BlockStatus(0); + status.set_field(BlockStatusBitArea::ValidationFailedBit, 2); + }) + .is_err() + ); + + assert!( + catch_unwind(|| { + let mut status = BlockStatus(0); + status.set_field(BlockStatusBitArea::InvalidParentBit, 2); + }) + .is_err() + ); + + assert!( + catch_unwind(|| { + let mut status = BlockStatus(0); + status.set_field(BlockStatusBitArea::ExplicitlyInvalidatedBit, 2); + }) + .is_err() + ); + + assert!( + catch_unwind(|| { + let mut status = BlockStatus(0); + status.set_field( + BlockStatusBitArea::ReservedArea, + // This is the value from test_set_field but with an additional 1 an the end. + 0b10101010_10101010_10101010_10101010_10101010_10101010_101011, + ); + }) + .is_err() + ); } #[test] diff --git a/chainstate/types/src/epoch_data_cache.rs b/chainstate/types/src/epoch_data_cache.rs index 9331ec32e3..57195f0f5d 100644 --- a/chainstate/types/src/epoch_data_cache.rs +++ b/chainstate/types/src/epoch_data_cache.rs @@ -17,7 +17,7 @@ use std::{collections::BTreeMap, ops::Deref}; use common::chain::config::EpochIndex; -use crate::{storage_result, EpochData}; +use crate::{EpochData, storage_result}; pub trait EpochStorageRead { fn get_epoch_data(&self, epoch_index: EpochIndex) -> storage_result::Result>; diff --git a/chainstate/types/src/error.rs b/chainstate/types/src/error.rs index 5a0d51e462..94a3582a5d 100644 --- a/chainstate/types/src/error.rs +++ b/chainstate/types/src/error.rs @@ -16,7 +16,7 @@ use thiserror::Error; use common::{ - chain::{tokens::TokenId, Block, GenBlock, OrderId, PoolId}, + chain::{Block, GenBlock, OrderId, PoolId, tokens::TokenId}, primitives::{BlockHeight, Id}, }; @@ -68,7 +68,9 @@ pub enum PropertyQueryError { pub enum GetAncestorError { #[error("Blockchain storage error: {0}")] StorageError(#[from] crate::storage_result::Error), - #[error("Invalid ancestor height: sought ancestor with height {ancestor_height} for block with height {block_height}")] + #[error( + "Invalid ancestor height: sought ancestor with height {ancestor_height} for block with height {block_height}" + )] InvalidAncestorHeight { block_height: BlockHeight, ancestor_height: BlockHeight, diff --git a/chainstate/types/src/gen_block_index.rs b/chainstate/types/src/gen_block_index.rs index fc5ec844f2..182ecb3a52 100644 --- a/chainstate/types/src/gen_block_index.rs +++ b/chainstate/types/src/gen_block_index.rs @@ -16,9 +16,9 @@ use std::sync::Arc; use common::{ - chain::{block::timestamp::BlockTimestamp, ChainConfig, GenBlock, Genesis}, - primitives::{id::WithId, BlockHeight, Id}, Uint256, + chain::{ChainConfig, GenBlock, Genesis, block::timestamp::BlockTimestamp}, + primitives::{BlockHeight, Id, id::WithId}, }; use static_assertions::assert_not_impl_any; diff --git a/chainstate/types/src/pos_randomness.rs b/chainstate/types/src/pos_randomness.rs index c2ee8241bb..57a18afd43 100644 --- a/chainstate/types/src/pos_randomness.rs +++ b/chainstate/types/src/pos_randomness.rs @@ -14,14 +14,14 @@ // limitations under the License. use common::{ - chain::{block::timestamp::BlockTimestamp, config::EpochIndex, Block, ChainConfig}, - primitives::{Id, H256}, + chain::{Block, ChainConfig, block::timestamp::BlockTimestamp, config::EpochIndex}, + primitives::{H256, Id}, }; use crypto::vrf::{VRFPublicKey, VRFReturn}; use serialization::{Decode, Encode}; use thiserror::Error; -use crate::vrf_tools::{verify_vrf_and_get_vrf_output, ProofOfStakeVRFError}; +use crate::vrf_tools::{ProofOfStakeVRFError, verify_vrf_and_get_vrf_output}; #[derive(Error, Debug, PartialEq, Eq, Clone)] pub enum PoSRandomnessError { diff --git a/chainstate/types/src/vrf_tools.rs b/chainstate/types/src/vrf_tools.rs index c9ee4a1268..2b679acafb 100644 --- a/chainstate/types/src/vrf_tools.rs +++ b/chainstate/types/src/vrf_tools.rs @@ -18,8 +18,8 @@ use common::{ primitives::H256, }; use crypto::vrf::{ - transcript::{no_rng::VRFTranscript, traits::SignableTranscript}, VRFError, VRFPublicKey, VRFReturn, + transcript::{no_rng::VRFTranscript, traits::SignableTranscript}, }; use thiserror::Error; diff --git a/common/src/address/dehexify.rs b/common/src/address/dehexify.rs index 3012442edc..a49de47f54 100644 --- a/common/src/address/dehexify.rs +++ b/common/src/address/dehexify.rs @@ -16,7 +16,7 @@ use crypto::vrf::VRFPublicKey; use serialization::json_encoded::JsonEncoded; -use crate::chain::{tokens::TokenId, ChainConfig, DelegationId, Destination, OrderId, PoolId}; +use crate::chain::{ChainConfig, DelegationId, Destination, OrderId, PoolId, tokens::TokenId}; use super::hexified::HexifiedAddress; @@ -51,13 +51,13 @@ mod tests { key::{KeyKind, PrivateKey}, vrf::{VRFKeyKind, VRFPrivateKey, VRFPublicKey}, }; - use test_utils::random::{gen_random_alnum_string, make_seedable_rng, Seed}; + use test_utils::random::{Seed, gen_random_alnum_string, make_seedable_rng}; use crate::{ - address::{hexified::HexifiedAddress, pubkeyhash::PublicKeyHash, Address}, + address::{Address, hexified::HexifiedAddress, pubkeyhash::PublicKeyHash}, chain::{ - config::create_regtest, tokens::TokenId, DelegationId, Destination, DestinationTag, - OrderId, PoolId, + DelegationId, Destination, DestinationTag, OrderId, PoolId, config::create_regtest, + tokens::TokenId, }, primitives::H256, }; diff --git a/common/src/address/hexified.rs b/common/src/address/hexified.rs index 2cf20ec05e..cdb299e348 100644 --- a/common/src/address/hexified.rs +++ b/common/src/address/hexified.rs @@ -15,9 +15,9 @@ use crate::{chain::ChainConfig, primitives::bech32_encoding}; -use super::{traits::Addressable, Address}; +use super::{Address, traits::Addressable}; use regex::Regex; -use serde::{de::Error, Deserialize}; +use serde::{Deserialize, de::Error}; use serialization::DecodeAll; const REGEX_SUFFIX: &str = r"\{0x([0-9a-fA-F]+)\}"; @@ -217,14 +217,14 @@ mod tests { }; use randomness::Rng; use serialization::{Decode, DecodeAll, Encode}; - use test_utils::random::{make_seedable_rng, RngExt as _, Seed}; + use test_utils::random::{RngExt as _, Seed, make_seedable_rng}; use crate::{ address::{ - hexified::HexifiedAddress, pubkeyhash::PublicKeyHash, traits::Addressable, Address, - AddressError, + Address, AddressError, hexified::HexifiedAddress, pubkeyhash::PublicKeyHash, + traits::Addressable, }, - chain::{config::create_regtest, ChainConfig, Destination}, + chain::{ChainConfig, Destination, config::create_regtest}, primitives::H256, }; diff --git a/common/src/address/mod.rs b/common/src/address/mod.rs index f28a911e1f..ab827edc60 100644 --- a/common/src/address/mod.rs +++ b/common/src/address/mod.rs @@ -20,11 +20,11 @@ pub mod rpc; pub mod traits; use crate::chain::ChainConfig; -use crate::primitives::{bech32_encoding, Bech32Error}; +use crate::primitives::{Bech32Error, bech32_encoding}; use std::fmt::Display; use utils::{ ensure, - qrcode::{qrcode_from_str, QrCode, QrCodeError}, + qrcode::{QrCode, QrCodeError, qrcode_from_str}, }; use self::traits::Addressable; diff --git a/common/src/chain/block/block_body/block_merkle.rs b/common/src/chain/block/block_body/block_merkle.rs index c05b5606d8..8fcef4b5a2 100644 --- a/common/src/chain/block/block_body/block_merkle.rs +++ b/common/src/chain/block/block_body/block_merkle.rs @@ -13,14 +13,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -use merkletree_mintlayer::{tree::MerkleTree, MerkleTreeFormError}; +use merkletree_mintlayer::{MerkleTreeFormError, tree::MerkleTree}; use crate::{ chain::SignedTransaction, - primitives::id::{self, Idable, H256}, + primitives::id::{self, H256, Idable}, }; -use super::{merkle_tools::MerkleHasher, BlockBody}; +use super::{BlockBody, merkle_tools::MerkleHasher}; fn tx_hasher(tx: &SignedTransaction) -> H256 { tx.transaction().get_id().to_hash() diff --git a/common/src/chain/block/block_body/merkle_proxy.rs b/common/src/chain/block/block_body/merkle_proxy.rs index 4f436bbde2..1401f185a9 100644 --- a/common/src/chain/block/block_body/merkle_proxy.rs +++ b/common/src/chain/block/block_body/merkle_proxy.rs @@ -21,9 +21,9 @@ use merkletree_mintlayer::{ use crate::primitives::H256; use super::{ + BlockBody, BlockMerkleTreeError, block_merkle::{calculate_tx_merkle_tree, calculate_witness_merkle_tree}, merkle_tools::MerkleHasher, - BlockBody, BlockMerkleTreeError, }; mod private { diff --git a/common/src/chain/block/block_body/merkle_tools.rs b/common/src/chain/block/block_body/merkle_tools.rs index 91eba837cf..836af44bd2 100644 --- a/common/src/chain/block/block_body/merkle_tools.rs +++ b/common/src/chain/block/block_body/merkle_tools.rs @@ -16,7 +16,7 @@ use crypto::hash::StreamHasher; use merkletree_mintlayer::hasher::PairHasher; -use crate::primitives::{id::DefaultHashAlgoStream, H256}; +use crate::primitives::{H256, id::DefaultHashAlgoStream}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct MerkleHasher {} diff --git a/common/src/chain/block/block_body/mod.rs b/common/src/chain/block/block_body/mod.rs index 5d17bc9424..2517637c5c 100644 --- a/common/src/chain/block/block_body/mod.rs +++ b/common/src/chain/block/block_body/mod.rs @@ -22,7 +22,7 @@ use merkletree_mintlayer::{MerkleTreeFormError, MerkleTreeProofExtractionError}; use serialization::{Decode, Encode}; use crate::chain::{ - output_value::OutputValue, output_values_holder::OutputValuesHolder, SignedTransaction, + SignedTransaction, output_value::OutputValue, output_values_holder::OutputValuesHolder, }; use self::merkle_proxy::BlockBodyMerkleProxy; @@ -81,19 +81,19 @@ mod tests { use crypto::key::{KeyKind, PrivateKey}; use randomness::{CryptoRng, Rng, RngExt as _}; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use crate::{ chain::{ + Destination, OutPointSourceId, Transaction, TxInput, TxOutput, block::BlockReward, output_value::OutputValue, signature::{ - inputsig::{standard_signature::StandardInputSignature, InputWitness}, + inputsig::{InputWitness, standard_signature::StandardInputSignature}, sighash::sighashtype::SigHashType, }, - Destination, OutPointSourceId, Transaction, TxInput, TxOutput, }, - primitives::{id::Idable, Amount, Id, H256}, + primitives::{Amount, H256, Id, id::Idable}, }; use super::*; @@ -237,20 +237,28 @@ mod tests { if transactions.is_empty() { // If there are no transactions, the block reward is the root - assert!(block_reward_inclusion_proof - .verify(block_reward_witness_hash, merkle_tree.root()) - .passed_trivially()); - assert!(block_reward_witness_inclusion_proof - .verify(block_reward_witness_hash, witness_merkle_tree.root()) - .passed_trivially()); + assert!( + block_reward_inclusion_proof + .verify(block_reward_witness_hash, merkle_tree.root()) + .passed_trivially() + ); + assert!( + block_reward_witness_inclusion_proof + .verify(block_reward_witness_hash, witness_merkle_tree.root()) + .passed_trivially() + ); assert_eq!(merkle_tree.root(), witness_merkle_tree.root()); } else { - assert!(block_reward_inclusion_proof - .verify(block_reward_witness_hash, merkle_tree.root()) - .passed_decisively()); - assert!(block_reward_witness_inclusion_proof - .verify(block_reward_witness_hash, witness_merkle_tree.root()) - .passed_decisively()); + assert!( + block_reward_inclusion_proof + .verify(block_reward_witness_hash, merkle_tree.root()) + .passed_decisively() + ); + assert!( + block_reward_witness_inclusion_proof + .verify(block_reward_witness_hash, witness_merkle_tree.root()) + .passed_decisively() + ); } // Verify inclusion proofs for transactions @@ -259,12 +267,16 @@ mod tests { let witness_inclusion_proof = witness_merkle_tree.transaction_witness_inclusion_proof(i as u32).unwrap(); - assert!(inclusion_proof - .verify(tx.transaction().get_id().to_hash(), merkle_tree.root()) - .passed_decisively()); - assert!(witness_inclusion_proof - .verify(tx.serialized_hash(), witness_merkle_tree.root()) - .passed_decisively()); + assert!( + inclusion_proof + .verify(tx.transaction().get_id().to_hash(), merkle_tree.root()) + .passed_decisively() + ); + assert!( + witness_inclusion_proof + .verify(tx.serialized_hash(), witness_merkle_tree.root()) + .passed_decisively() + ); } } } diff --git a/common/src/chain/block/block_header.rs b/common/src/chain/block/block_header.rs index f0fc32b2b9..14ee4796b2 100644 --- a/common/src/chain/block/block_header.rs +++ b/common/src/chain/block/block_header.rs @@ -17,9 +17,9 @@ use serialization::{Decode, Encode}; use super::signed_block_header::{BlockHeaderSignature, SignedBlockHeader}; use super::timestamp::BlockTimestamp; -use crate::chain::{block::ConsensusData, Block, GenBlock}; -use crate::primitives::id::{Id, Idable, H256}; -use crate::primitives::{id, VersionTag}; +use crate::chain::{Block, GenBlock, block::ConsensusData}; +use crate::primitives::id::{H256, Id, Idable}; +use crate::primitives::{VersionTag, id}; #[must_use] #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, serialization::Tagged)] diff --git a/common/src/chain/block/block_reward.rs b/common/src/chain/block/block_reward.rs index 28fa5e01b9..60c2843f52 100644 --- a/common/src/chain/block/block_reward.rs +++ b/common/src/chain/block/block_reward.rs @@ -17,8 +17,8 @@ use serialization::{Decode, Encode}; use crate::{ chain::{ - signature::{inputsig::InputWitness, Signable, Transactable}, TxInput, TxOutput, + signature::{Signable, Transactable, inputsig::InputWitness}, }, primitives::id::{self, H256}, }; diff --git a/common/src/chain/block/block_v1.rs b/common/src/chain/block/block_v1.rs index 3846e9a612..b6826f480b 100644 --- a/common/src/chain/block/block_v1.rs +++ b/common/src/chain/block/block_v1.rs @@ -20,7 +20,7 @@ use crate::{ block::{Block, BlockReward, BlockRewardTransactable, ConsensusData}, signed_transaction::SignedTransaction, }, - primitives::{id::Idable, Id, H256}, + primitives::{H256, Id, id::Idable}, }; use super::{ diff --git a/common/src/chain/block/consensus_data.rs b/common/src/chain/block/consensus_data.rs index 0e56637ff0..7d79bd3483 100644 --- a/common/src/chain/block/consensus_data.rs +++ b/common/src/chain/block/consensus_data.rs @@ -14,9 +14,9 @@ // limitations under the License. use crate::{ - chain::{chaintrust, signature::inputsig::InputWitness, PoolId, TxInput}, - primitives::Compact, Uint256, + chain::{PoolId, TxInput, chaintrust, signature::inputsig::InputWitness}, + primitives::Compact, }; use crypto::vrf::VRFReturn; diff --git a/common/src/chain/block/mod.rs b/common/src/chain/block/mod.rs index e7a877074a..eb78b913fa 100644 --- a/common/src/chain/block/mod.rs +++ b/common/src/chain/block/mod.rs @@ -14,12 +14,12 @@ // limitations under the License. pub use crate::chain::{ + GenBlock, block::{ block_header::BlockHeader, block_reward::{BlockReward, BlockRewardTransactable}, consensus_data::ConsensusData, }, - GenBlock, }; pub mod block_body; @@ -43,8 +43,8 @@ use crate::{ output_values_holder::OutputValuesHolder, }, primitives::{ + H256, Id, Idable, VersionTag, id::{HasSubObjWithSameId, WithId}, - Id, Idable, VersionTag, H256, }, }; @@ -260,14 +260,14 @@ impl rpc_description::HasValueHint for Id { mod tests { use crate::{ chain::{ - output_value::OutputValue, signature::inputsig::InputWitness, transaction::Transaction, - Destination, OutPointSourceId, TxInput, TxOutput, + Destination, OutPointSourceId, TxInput, TxOutput, output_value::OutputValue, + signature::inputsig::InputWitness, transaction::Transaction, }, - primitives::{id, Amount}, + primitives::{Amount, id}, }; use super::*; - use randomness::{make_pseudo_rng, RngExt as _}; + use randomness::{RngExt as _, make_pseudo_rng}; use rstest::rstest; use serialization::Encode; use test_utils::random::Seed; diff --git a/common/src/chain/block/signed_block_header.rs b/common/src/chain/block/signed_block_header.rs index ced98b1e82..05d3a156da 100644 --- a/common/src/chain/block/signed_block_header.rs +++ b/common/src/chain/block/signed_block_header.rs @@ -19,7 +19,7 @@ use typename::TypeName; use crate::primitives::id::{Id, Idable}; -use super::{timestamp::BlockTimestamp, Block, BlockHeader, ConsensusData, GenBlock}; +use super::{Block, BlockHeader, ConsensusData, GenBlock, timestamp::BlockTimestamp}; #[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)] pub enum SignedHeaderError { diff --git a/common/src/chain/config/builder.rs b/common/src/chain/config/builder.rs index c56ad43262..4b9399703d 100644 --- a/common/src/chain/config/builder.rs +++ b/common/src/chain/config/builder.rs @@ -16,10 +16,17 @@ use std::{collections::BTreeMap, net::SocketAddr, num::NonZeroU64, sync::Arc, time::Duration}; use crate::{ + Uint256, chain::{ + ChainstateUpgrade, ChainstateUpgradesBuilder, ChangeTokenMetadataUriActivated, CoinUnit, + ConsensusUpgrade, DataDepositFeeVersion, Destination, FrozenTokensValidationVersion, + GenBlock, Genesis, HtlcActivated, NetUpgrades, OrdersActivated, OrdersVersion, + PoSChainConfig, PoSConsensusVersion, PoWChainConfig, RewardDistributionVersion, + SighashInputCommitmentVersion, StakerDestinationUpdateForbidden, TokenIdGenerationVersion, + TokenIssuanceVersion, TokensFeeVersion, config::{ - create_mainnet_genesis, create_testnet_genesis, create_unit_test_genesis, - emission_schedule, ChainConfig, ChainType, EmissionScheduleTabular, + ChainConfig, ChainType, EmissionScheduleTabular, create_mainnet_genesis, + create_testnet_genesis, create_unit_test_genesis, emission_schedule, }, get_initial_randomness, pos::{ @@ -28,25 +35,18 @@ use crate::{ }, pos_initial_difficulty, pow::PoWChainConfigBuilder, - ChainstateUpgrade, ChainstateUpgradesBuilder, ChangeTokenMetadataUriActivated, CoinUnit, - ConsensusUpgrade, DataDepositFeeVersion, Destination, FrozenTokensValidationVersion, - GenBlock, Genesis, HtlcActivated, NetUpgrades, OrdersActivated, OrdersVersion, - PoSChainConfig, PoSConsensusVersion, PoWChainConfig, RewardDistributionVersion, - SighashInputCommitmentVersion, StakerDestinationUpdateForbidden, TokenIdGenerationVersion, - TokenIssuanceVersion, TokensFeeVersion, }, primitives::{ - id::WithId, per_thousand::PerThousand, semver::SemVer, Amount, BlockCount, BlockDistance, - BlockHeight, Id, Idable, H256, + Amount, BlockCount, BlockDistance, BlockHeight, H256, Id, Idable, id::WithId, + per_thousand::PerThousand, semver::SemVer, }, - Uint256, }; use crypto::key::hdkd::child_number::ChildNumber; use super::{ + MagicBytes, checkpoints::Checkpoints, checkpoints_data::{MAINNET_CHECKPOINTS, TESTNET_CHECKPOINTS}, - MagicBytes, }; // Note: the names of the "FORK_HEIGHT" constants below only contain the short description @@ -653,7 +653,7 @@ mod tests { use super::*; use randomness::RngExt; use rstest::rstest; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use crate::chain::config::{ DEFAULT_MAX_FUTURE_BLOCK_TIME_OFFSET_V1, DEFAULT_MAX_FUTURE_BLOCK_TIME_OFFSET_V2, diff --git a/common/src/chain/config/checkpoints.rs b/common/src/chain/config/checkpoints.rs index 360efcd128..95d05dfc79 100644 --- a/common/src/chain/config/checkpoints.rs +++ b/common/src/chain/config/checkpoints.rs @@ -119,7 +119,7 @@ mod tests { use test_utils::{ assert_matches, - random::{make_seedable_rng, RngExt as _, Seed}, + random::{RngExt as _, Seed, make_seedable_rng}, }; use super::*; diff --git a/common/src/chain/config/checkpoints_data/mod.rs b/common/src/chain/config/checkpoints_data/mod.rs index 656fa7e718..2eeafa28c1 100644 --- a/common/src/chain/config/checkpoints_data/mod.rs +++ b/common/src/chain/config/checkpoints_data/mod.rs @@ -17,7 +17,7 @@ use std::{collections::BTreeMap, fmt::Write, str::FromStr}; use crate::{ chain::GenBlock, - primitives::{BlockHeight, Id, H256}, + primitives::{BlockHeight, H256, Id}, }; mod mainnet; diff --git a/common/src/chain/config/mod.rs b/common/src/chain/config/mod.rs index b4811ff9ae..f93ddb2a06 100644 --- a/common/src/chain/config/mod.rs +++ b/common/src/chain/config/mod.rs @@ -33,8 +33,8 @@ use serialization::{Decode, Encode}; use crypto::{ key::{ - hdkd::{child_number::ChildNumber, u31::U31}, PublicKey, + hdkd::{child_number::ChildNumber, u31::U31}, }, vrf::VRFPublicKey, }; @@ -43,24 +43,23 @@ use utils::const_nz_u64; use crate::{ chain::{ - block::timestamp::BlockTimestamp, transaction::Destination, upgrades::NetUpgrades, - GenBlock, Genesis, PoWChainConfig, TxOutput, + GenBlock, Genesis, PoWChainConfig, TxOutput, block::timestamp::BlockTimestamp, + transaction::Destination, upgrades::NetUpgrades, }, primitives::{ + Amount, BlockCount, BlockDistance, BlockHeight, H256, id::{Id, Idable, WithId}, per_thousand::PerThousand, semver::SemVer, - Amount, BlockCount, BlockDistance, BlockHeight, H256, }, }; use super::{ - output_value::OutputValue, stakelock::StakePoolData, ChainstateUpgrade, - ChangeTokenMetadataUriActivated, ConsensusUpgrade, DataDepositFeeVersion, DestinationTag, - FrozenTokensValidationVersion, HtlcActivated, OrdersActivated, OrdersVersion, + ChainstateUpgrade, ChangeTokenMetadataUriActivated, ConsensusUpgrade, DataDepositFeeVersion, + DestinationTag, FrozenTokensValidationVersion, HtlcActivated, OrdersActivated, OrdersVersion, RequiredConsensus, RewardDistributionVersion, SighashInputCommitmentVersion, StakerDestinationUpdateForbidden, TokenIdGenerationVersion, TokenIssuanceVersion, - TokensFeeVersion, + TokensFeeVersion, output_value::OutputValue, stakelock::StakePoolData, }; use self::emission_schedule::{CoinUnit, DEFAULT_INITIAL_MINT}; diff --git a/common/src/chain/config/regtest.rs b/common/src/chain/config/regtest.rs index a113b5347f..e042834d5c 100644 --- a/common/src/chain/config/regtest.rs +++ b/common/src/chain/config/regtest.rs @@ -21,13 +21,13 @@ use std::{ use crate::{ chain::{ + Genesis, PoolId, TxOutput, block::timestamp::BlockTimestamp, - config::{StakePoolData, DEFAULT_INITIAL_MINT, MIN_STAKE_POOL_PLEDGE}, + config::{DEFAULT_INITIAL_MINT, MIN_STAKE_POOL_PLEDGE, StakePoolData}, output_value::OutputValue, transaction::Destination, - Genesis, PoolId, TxOutput, }, - primitives::{per_thousand::PerThousand, Amount}, + primitives::{Amount, per_thousand::PerThousand}, }; use crypto::{ key::{PrivateKey, PublicKey}, diff --git a/common/src/chain/config/regtest_options.rs b/common/src/chain/config/regtest_options.rs index 0a57d8f38d..dedeb2d495 100644 --- a/common/src/chain/config/regtest_options.rs +++ b/common/src/chain/config/regtest_options.rs @@ -18,24 +18,24 @@ use std::{str::FromStr, time::Duration}; use clap::Args; use crate::{ + Uint256, chain::{ + ChainstateUpgradeBuilder, ChainstateUpgradesBuilder, ConsensusUpgrade, Destination, + NetUpgrades, OrdersVersion, PoSChainConfig, PoSConsensusVersion, config::{ + Builder, ChainType, EmissionScheduleTabular, MagicBytes, builder::default_regtest_chainstate_upgrade_at_genesis, regtest::{create_regtest_pos_genesis, create_regtest_pow_genesis}, - Builder, ChainType, EmissionScheduleTabular, MagicBytes, }, pos::{DEFAULT_BLOCK_COUNT_TO_AVERAGE, DEFAULT_MATURITY_BLOCK_COUNT_V0}, - pos_initial_difficulty, ChainstateUpgradeBuilder, ChainstateUpgradesBuilder, - ConsensusUpgrade, Destination, NetUpgrades, OrdersVersion, PoSChainConfig, - PoSConsensusVersion, + pos_initial_difficulty, }, - primitives::{self, per_thousand::PerThousand, semver::SemVer, BlockHeight}, - Uint256, + primitives::{self, BlockHeight, per_thousand::PerThousand, semver::SemVer}, }; -use super::{regtest::GenesisStakingSettings, ChainConfig}; +use super::{ChainConfig, regtest::GenesisStakingSettings}; -use anyhow::{anyhow, ensure, Result}; +use anyhow::{Result, anyhow, ensure}; use paste::paste; #[derive(Args, Clone, Debug, Default)] diff --git a/common/src/chain/currency.rs b/common/src/chain/currency.rs index 344157295a..cb79765dea 100644 --- a/common/src/chain/currency.rs +++ b/common/src/chain/currency.rs @@ -16,9 +16,9 @@ use crate::{ address::{AddressError, RpcAddress}, chain::{ + ChainConfig, output_value::{OutputValue, RpcOutputValue}, tokens::TokenId, - ChainConfig, }, primitives::Amount, }; diff --git a/common/src/chain/genesis.rs b/common/src/chain/genesis.rs index 73d3e8944c..a34a769a76 100644 --- a/common/src/chain/genesis.rs +++ b/common/src/chain/genesis.rs @@ -16,9 +16,9 @@ use serialization::{Decode, Encode}; use typename::TypeName; -use super::block::{timestamp::BlockTimestamp, BlockRewardTransactable}; use super::TxOutput; -use crate::primitives::{id, Id, Idable}; +use super::block::{BlockRewardTransactable, timestamp::BlockTimestamp}; +use crate::primitives::{Id, Idable, id}; /// Genesis defines the initial state of the blockchain #[derive(Eq, PartialEq, Clone, Encode, Decode, Debug, TypeName)] diff --git a/common/src/chain/make_id.rs b/common/src/chain/make_id.rs index 9ee3a5df0e..08300c1b99 100644 --- a/common/src/chain/make_id.rs +++ b/common/src/chain/make_id.rs @@ -35,13 +35,13 @@ use crypto::hash::StreamHasher as _; use crate::primitives::{ - id::{hash_encoded, hash_encoded_to, DefaultHashAlgoStream}, BlockHeight, + id::{DefaultHashAlgoStream, hash_encoded, hash_encoded_to}, }; use super::{ - tokens::TokenId, ChainConfig, DelegationId, OrderId, PoolId, TokenIdGenerationVersion, TxInput, - UtxoOutPoint, + ChainConfig, DelegationId, OrderId, PoolId, TokenIdGenerationVersion, TxInput, UtxoOutPoint, + tokens::TokenId, }; pub fn make_pool_id(inputs: &[TxInput]) -> Result { @@ -172,8 +172,8 @@ mod tests { use crate::{ chain::{ - config, AccountNonce, AccountOutPoint, AccountSpending, ChainstateUpgradeBuilder, - NetUpgrades, OutPointSourceId, TokenIdGenerationVersion, TxInput, UtxoOutPoint, + AccountNonce, AccountOutPoint, AccountSpending, ChainstateUpgradeBuilder, NetUpgrades, + OutPointSourceId, TokenIdGenerationVersion, TxInput, UtxoOutPoint, config, }, primitives::{Amount, BlockHeight, Id}, }; diff --git a/common/src/chain/mod.rs b/common/src/chain/mod.rs index 8585b6a845..7aee88eb75 100644 --- a/common/src/chain/mod.rs +++ b/common/src/chain/mod.rs @@ -40,13 +40,13 @@ pub use currency::{Currency, RpcCurrency}; pub use gen_block::{GenBlock, GenBlockId}; pub use genesis::Genesis; pub use make_id::{ - make_delegation_id, make_order_id, make_pool_id, make_token_id, make_token_id_with_version, - IdCreationError, + IdCreationError, make_delegation_id, make_order_id, make_pool_id, make_token_id, + make_token_id_with_version, }; pub use order::{OrderData, OrderId, RpcOrderInfo}; pub use pos::{ - config::PoSChainConfig, config_builder::PoSChainConfigBuilder, delegation_id::DelegationId, - get_initial_randomness, pool_id::PoolId, pos_initial_difficulty, PoSConsensusVersion, + PoSConsensusVersion, config::PoSChainConfig, config_builder::PoSChainConfigBuilder, + delegation_id::DelegationId, get_initial_randomness, pool_id::PoolId, pos_initial_difficulty, }; pub use pow::{PoWChainConfig, PoWChainConfigBuilder}; pub use upgrades::*; diff --git a/common/src/chain/order/mod.rs b/common/src/chain/order/mod.rs index 34447c5882..0a434ea2ce 100644 --- a/common/src/chain/order/mod.rs +++ b/common/src/chain/order/mod.rs @@ -15,7 +15,7 @@ use serialization::{Decode, Encode}; -use super::{output_value::OutputValue, Destination}; +use super::{Destination, output_value::OutputValue}; mod order_id; pub use order_id::OrderId; diff --git a/common/src/chain/order/order_id.rs b/common/src/chain/order/order_id.rs index 473826aedb..da29dd8487 100644 --- a/common/src/chain/order/order_id.rs +++ b/common/src/chain/order/order_id.rs @@ -17,7 +17,7 @@ use serialization::{DecodeAll, Encode}; use typename::TypeName; use crate::{ - address::{hexified::HexifiedAddress, traits::Addressable, AddressError}, + address::{AddressError, hexified::HexifiedAddress, traits::Addressable}, chain::ChainConfig, primitives::Id, }; diff --git a/common/src/chain/order/rpc.rs b/common/src/chain/order/rpc.rs index b041b8b09a..f40aad487e 100644 --- a/common/src/chain/order/rpc.rs +++ b/common/src/chain/order/rpc.rs @@ -17,8 +17,8 @@ use rpc_description::HasValueHint; use crate::{ chain::{ - output_value::RpcOutputValue, output_values_holder::RpcOutputValuesHolder, AccountNonce, - Destination, + AccountNonce, Destination, output_value::RpcOutputValue, + output_values_holder::RpcOutputValuesHolder, }, primitives::Amount, }; diff --git a/common/src/chain/partially_signed_transaction/additional_info.rs b/common/src/chain/partially_signed_transaction/additional_info.rs index 85d11efd6e..303be49f14 100644 --- a/common/src/chain/partially_signed_transaction/additional_info.rs +++ b/common/src/chain/partially_signed_transaction/additional_info.rs @@ -19,10 +19,10 @@ use serialization::{Decode, Encode}; use crate::{ chain::{ + OrderId, PoolId, output_value::OutputValue, output_values_holder::OutputValuesHolder, signature::sighash::{self}, - OrderId, PoolId, }, primitives::Amount, }; diff --git a/common/src/chain/partially_signed_transaction/mod.rs b/common/src/chain/partially_signed_transaction/mod.rs index f0ab18759d..78425fd1db 100644 --- a/common/src/chain/partially_signed_transaction/mod.rs +++ b/common/src/chain/partially_signed_transaction/mod.rs @@ -19,25 +19,24 @@ use serialization::{Decode, Encode}; use crate::{ chain::{ + ChainConfig, Destination, OrderId, PoolId, SighashInputCommitmentVersion, + SignedTransaction, Transaction, TransactionCreationError, TxInput, TxOutput, htlc::HtlcSecret, output_value::OutputValue, output_values_holder::OutputValuesHolder, partially_signed_transaction::v1::PartiallySignedTransactionV1, signature::{ + Signable, Transactable, inputsig::InputWitness, sighash::{ self, input_commitments::{ - make_sighash_input_commitments_for_transaction_inputs, + SighashInputCommitment, make_sighash_input_commitments_for_transaction_inputs, make_sighash_input_commitments_for_transaction_inputs_at_height, - SighashInputCommitment, }, }, - Signable, Transactable, }, tokens::TokenId, - ChainConfig, Destination, OrderId, PoolId, SighashInputCommitmentVersion, - SignedTransaction, Transaction, TransactionCreationError, TxInput, TxOutput, }, primitives::BlockHeight, }; diff --git a/common/src/chain/partially_signed_transaction/tests.rs b/common/src/chain/partially_signed_transaction/tests.rs index c556493967..fc36f609db 100644 --- a/common/src/chain/partially_signed_transaction/tests.rs +++ b/common/src/chain/partially_signed_transaction/tests.rs @@ -18,22 +18,23 @@ use serialization::hex::{HexDecode, HexEncode as _}; use crate::{ address::pubkeyhash::PublicKeyHash, chain::{ - htlc::{HashedTimelockContract, HtlcSecret, HTLC_SECRET_SIZE}, + Destination, OrderAccountCommand, OrderId, PoolId, Transaction, TxInput, TxOutput, + UtxoOutPoint, + htlc::{HTLC_SECRET_SIZE, HashedTimelockContract, HtlcSecret}, output_value::OutputValue, partially_signed_transaction::{ - v1::PartiallySignedTransactionV1, OrderAdditionalInfo, PartiallySignedTransaction, + OrderAdditionalInfo, PartiallySignedTransaction, PartiallySignedTransactionConsistencyCheck, PoolAdditionalInfo, TxAdditionalInfo, + v1::PartiallySignedTransactionV1, }, signature::{ - inputsig::{standard_signature::StandardInputSignature, InputWitness}, + inputsig::{InputWitness, standard_signature::StandardInputSignature}, sighash::sighashtype::SigHashType, }, timelock::OutputTimeLock, tokens::TokenId, - Destination, OrderAccountCommand, OrderId, PoolId, Transaction, TxInput, TxOutput, - UtxoOutPoint, }, - primitives::{Amount, Id, H256}, + primitives::{Amount, H256, Id}, }; #[test] diff --git a/common/src/chain/partially_signed_transaction/v1.rs b/common/src/chain/partially_signed_transaction/v1.rs index 7fbf89a686..f5ccb90f91 100644 --- a/common/src/chain/partially_signed_transaction/v1.rs +++ b/common/src/chain/partially_signed_transaction/v1.rs @@ -17,14 +17,14 @@ use serialization::{Decode, Encode}; use utils::ensure; use crate::chain::{ + AccountCommand, Destination, OrderAccountCommand, OrderId, SignedTransaction, Transaction, + TxInput, TxOutput, htlc::HtlcSecret, partially_signed_transaction::{ PartiallySignedTransactionConsistencyCheck, PartiallySignedTransactionError, TxAdditionalInfo, }, signature::inputsig::InputWitness, - AccountCommand, Destination, OrderAccountCommand, OrderId, SignedTransaction, Transaction, - TxInput, TxOutput, }; #[derive(Debug, Eq, PartialEq, Clone, Encode, Decode, serde::Serialize)] diff --git a/common/src/chain/pos/config.rs b/common/src/chain/pos/config.rs index 75b3d4e2ec..40d3857f39 100644 --- a/common/src/chain/pos/config.rs +++ b/common/src/chain/pos/config.rs @@ -14,8 +14,8 @@ // limitations under the License. use crate::{ - primitives::{per_thousand::PerThousand, BlockCount}, Uint256, + primitives::{BlockCount, per_thousand::PerThousand}, }; use super::PoSConsensusVersion; diff --git a/common/src/chain/pos/config_builder.rs b/common/src/chain/pos/config_builder.rs index 2433bf13d8..4c550a63d2 100644 --- a/common/src/chain/pos/config_builder.rs +++ b/common/src/chain/pos/config_builder.rs @@ -14,11 +14,11 @@ // limitations under the License. use crate::{ - primitives::{per_thousand::PerThousand, BlockCount}, Uint256, + primitives::{BlockCount, per_thousand::PerThousand}, }; -use super::{config::PoSChainConfig, PoSConsensusVersion}; +use super::{PoSConsensusVersion, config::PoSChainConfig}; pub struct PoSChainConfigBuilder { target_limit: Uint256, diff --git a/common/src/chain/pos/delegation_id.rs b/common/src/chain/pos/delegation_id.rs index d041bdffa3..9227d97081 100644 --- a/common/src/chain/pos/delegation_id.rs +++ b/common/src/chain/pos/delegation_id.rs @@ -17,7 +17,7 @@ use serialization::{DecodeAll, Encode}; use typename::TypeName; use crate::{ - address::{hexified::HexifiedAddress, traits::Addressable, AddressError}, + address::{AddressError, hexified::HexifiedAddress, traits::Addressable}, primitives::Id, }; diff --git a/common/src/chain/pos/mod.rs b/common/src/chain/pos/mod.rs index fbf8bd7d6a..9179a8c01e 100644 --- a/common/src/chain/pos/mod.rs +++ b/common/src/chain/pos/mod.rs @@ -18,11 +18,11 @@ use std::str::FromStr; use serialization::{Decode, Encode}; use crate::{ - primitives::{BlockCount, H256}, Uint256, + primitives::{BlockCount, H256}, }; -use super::{config::ChainType, ChainConfig}; +use super::{ChainConfig, config::ChainType}; pub mod config; pub mod config_builder; diff --git a/common/src/chain/pos/pool_id.rs b/common/src/chain/pos/pool_id.rs index d1961aff28..1517677ae1 100644 --- a/common/src/chain/pos/pool_id.rs +++ b/common/src/chain/pos/pool_id.rs @@ -17,7 +17,7 @@ use serialization::{DecodeAll, Encode}; use typename::TypeName; use crate::{ - address::{hexified::HexifiedAddress, traits::Addressable, AddressError}, + address::{AddressError, hexified::HexifiedAddress, traits::Addressable}, primitives::Id, }; diff --git a/common/src/chain/pow.rs b/common/src/chain/pow.rs index 492ec5352b..2f5626670c 100644 --- a/common/src/chain/pow.rs +++ b/common/src/chain/pow.rs @@ -13,9 +13,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +use crate::Uint256; use crate::chain::config::ChainType; use crate::primitives::BlockCount; -use crate::Uint256; use std::time::Duration; /// Chain Parameters for Proof of Work. @@ -153,9 +153,9 @@ pub(crate) const fn limit(chain_type: ChainType) -> Uint256 { #[cfg(test)] mod tests { - use crate::chain::config::{create_mainnet, ChainType}; - use crate::chain::pow::{allow_min_difficulty_blocks, limit, no_retargeting}; use crate::Uint256; + use crate::chain::config::{ChainType, create_mainnet}; + use crate::chain::pow::{allow_min_difficulty_blocks, limit, no_retargeting}; #[test] fn check_mainnet_powconfig() { diff --git a/common/src/chain/tokens/nft.rs b/common/src/chain/tokens/nft.rs index 2b9f58fc91..30e2775ba9 100644 --- a/common/src/chain/tokens/nft.rs +++ b/common/src/chain/tokens/nft.rs @@ -14,7 +14,7 @@ // limitations under the License. use crypto::key::PublicKey; -use serialization::{extras::non_empty_vec::DataOrNoVec, Decode, Encode}; +use serialization::{Decode, Encode, extras::non_empty_vec::DataOrNoVec}; #[derive( Debug, diff --git a/common/src/chain/tokens/token_id.rs b/common/src/chain/tokens/token_id.rs index 46067f2f4f..2cd35916aa 100644 --- a/common/src/chain/tokens/token_id.rs +++ b/common/src/chain/tokens/token_id.rs @@ -17,7 +17,7 @@ use serialization::{DecodeAll, Encode}; use typename::TypeName; use crate::{ - address::{hexified::HexifiedAddress, traits::Addressable, AddressError}, + address::{AddressError, hexified::HexifiedAddress, traits::Addressable}, chain::ChainConfig, primitives::Id, }; diff --git a/common/src/chain/tokens/tokens_utils.rs b/common/src/chain/tokens/tokens_utils.rs index 0cdef3f398..f1e539cee1 100644 --- a/common/src/chain/tokens/tokens_utils.rs +++ b/common/src/chain/tokens/tokens_utils.rs @@ -16,7 +16,7 @@ use smallvec::SmallVec; use super::{TokenData, TokenId}; -use crate::chain::{output_value::OutputValue, AccountCommand, TxInput, TxOutput}; +use crate::chain::{AccountCommand, TxInput, TxOutput, output_value::OutputValue}; pub fn get_tokens_issuance_count(outputs: &[TxOutput]) -> usize { outputs.iter().filter(|&output| is_token_or_nft_issuance(output)).count() diff --git a/common/src/chain/transaction/account_outpoint.rs b/common/src/chain/transaction/account_outpoint.rs index 42698e0fb4..9034e9c0c0 100644 --- a/common/src/chain/transaction/account_outpoint.rs +++ b/common/src/chain/transaction/account_outpoint.rs @@ -15,8 +15,8 @@ use crate::{ chain::{ - tokens::{IsTokenUnfreezable, TokenId}, AccountNonce, DelegationId, OrderId, + tokens::{IsTokenUnfreezable, TokenId}, }, primitives::Amount, }; diff --git a/common/src/chain/transaction/mod.rs b/common/src/chain/transaction/mod.rs index 56aa63c0a9..afc7f84a9d 100644 --- a/common/src/chain/transaction/mod.rs +++ b/common/src/chain/transaction/mod.rs @@ -20,7 +20,7 @@ use typename::TypeName; use crate::{ chain::{output_value::OutputValue, output_values_holder::OutputValuesHolder}, - primitives::{id::WithId, Id, Idable, H256}, + primitives::{H256, Id, Idable, id::WithId}, text_summary::TextSummary, }; diff --git a/common/src/chain/transaction/output/classic_multisig.rs b/common/src/chain/transaction/output/classic_multisig.rs index 339f9b6704..f6bcabaeeb 100644 --- a/common/src/chain/transaction/output/classic_multisig.rs +++ b/common/src/chain/transaction/output/classic_multisig.rs @@ -116,7 +116,7 @@ mod tests { use crypto::key::{KeyKind, PrivateKey}; use randomness::RngExt; use rstest::rstest; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use super::*; use crate::chain::config::create_mainnet; diff --git a/common/src/chain/transaction/output/htlc.rs b/common/src/chain/transaction/output/htlc.rs index a2aec44c71..01549b74e7 100644 --- a/common/src/chain/transaction/output/htlc.rs +++ b/common/src/chain/transaction/output/htlc.rs @@ -22,7 +22,7 @@ use crypto::hash::{self, hash}; use randomness::{CryptoRng, RngExt as _}; use serialization::{Decode, Encode}; -use super::{timelock::OutputTimeLock, Destination}; +use super::{Destination, timelock::OutputTimeLock}; #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, serde::Serialize, serde::Deserialize)] pub struct HashedTimelockContract { diff --git a/common/src/chain/transaction/output/mod.rs b/common/src/chain/transaction/output/mod.rs index 79faa8e11a..b003b1b5d9 100644 --- a/common/src/chain/transaction/output/mod.rs +++ b/common/src/chain/transaction/output/mod.rs @@ -18,15 +18,15 @@ use crate::{ address::{ - hexified::HexifiedAddress, pubkeyhash::PublicKeyHash, traits::Addressable, Address, - AddressError, + Address, AddressError, hexified::HexifiedAddress, pubkeyhash::PublicKeyHash, + traits::Addressable, }, chain::{ + ChainConfig, DelegationId, PoolId, order::OrderData, output_value::OutputValue, output_values_holder::OutputValuesHolder, tokens::{IsTokenFreezable, NftIssuance, TokenId, TokenIssuance, TokenTotalSupply}, - ChainConfig, DelegationId, PoolId, }, primitives::{Amount, Id}, text_summary::TextSummary, @@ -265,8 +265,7 @@ impl TextSummary for TxOutput { IsTokenFreezable::No => "No".to_string(), IsTokenFreezable::Yes => "Yes".to_string(), }; - let fmt_tkn_iss = |iss: &TokenIssuance| { - match iss { + let fmt_tkn_iss = |iss: &TokenIssuance| match iss { TokenIssuance::V1(iss1) => format!( "TokenIssuance(Ticker({}), Decimals({}), MetadataUri({}), TotalSupply({}), Authority({}), IsFreezable({}))", String::from_utf8_lossy(&iss1.token_ticker), @@ -276,7 +275,6 @@ impl TextSummary for TxOutput { fmt_dest(&iss1.authority), fmt_tkn_frzble(&iss1.is_freezable) ), - } }; let fmt_nft_iss = |iss: &NftIssuance| match iss { NftIssuance::V0(iss1) => { @@ -295,11 +293,8 @@ impl TextSummary for TxOutput { String::from_utf8_lossy( md.additional_metadata_uri.as_ref().as_ref().unwrap_or(&vec![]) ), - String::from_utf8_lossy( - md.media_uri.as_ref().as_ref().unwrap_or(&vec![]) - ), + String::from_utf8_lossy(md.media_uri.as_ref().as_ref().unwrap_or(&vec![])), hex::encode(&md.media_hash), - ) } }; diff --git a/common/src/chain/transaction/output/output_value.rs b/common/src/chain/transaction/output/output_value.rs index d9f039b10d..afafd6758b 100644 --- a/common/src/chain/transaction/output/output_value.rs +++ b/common/src/chain/transaction/output/output_value.rs @@ -17,8 +17,8 @@ use serialization::{Decode, Encode}; use crate::{ chain::{ - tokens::{NftIssuanceV0, TokenData, TokenId, TokenIssuanceV0, TokenTransfer}, Currency, + tokens::{NftIssuanceV0, TokenData, TokenId, TokenIssuanceV0, TokenTransfer}, }, primitives::Amount, }; diff --git a/common/src/chain/transaction/output/stakelock.rs b/common/src/chain/transaction/output/stakelock.rs index a4c9c0474c..41d942aa34 100644 --- a/common/src/chain/transaction/output/stakelock.rs +++ b/common/src/chain/transaction/output/stakelock.rs @@ -16,7 +16,7 @@ use crypto::vrf::VRFPublicKey; use serialization::{Decode, Encode}; -use crate::primitives::{per_thousand::PerThousand, Amount}; +use crate::primitives::{Amount, per_thousand::PerThousand}; use super::Destination; diff --git a/common/src/chain/transaction/printout.rs b/common/src/chain/transaction/printout.rs index ace5e66d63..a59ba23bc6 100644 --- a/common/src/chain/transaction/printout.rs +++ b/common/src/chain/transaction/printout.rs @@ -15,7 +15,7 @@ use crate::{ chain::ChainConfig, - primitives::{Idable, H256}, + primitives::{H256, Idable}, text_summary::TextSummary, }; @@ -66,11 +66,13 @@ mod tests { vrf::{VRFKeyKind, VRFPrivateKey}, }; use serialization::extras::non_empty_vec::DataOrNoVec; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use crate::{ address::Address, chain::{ + AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, DelegationId, + Destination, OutPointSourceId, PoolId, Transaction, TxInput, TxOutput, UtxoOutPoint, block::timestamp::BlockTimestamp, config::create_mainnet, output_value::OutputValue, @@ -80,10 +82,8 @@ mod tests { IsTokenFreezable, Metadata, NftIssuance, NftIssuanceV0, TokenCreator, TokenId, TokenIssuance, TokenIssuanceV1, TokenTotalSupply, }, - AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, DelegationId, - Destination, OutPointSourceId, PoolId, Transaction, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, Id, H256}, + primitives::{Amount, H256, Id, per_thousand::PerThousand}, time_getter::TimeGetter, }; diff --git a/common/src/chain/transaction/signature/inputsig/arbitrary_message/mod.rs b/common/src/chain/transaction/signature/inputsig/arbitrary_message/mod.rs index ef3c63fea8..c8ebb73398 100644 --- a/common/src/chain/transaction/signature/inputsig/arbitrary_message/mod.rs +++ b/common/src/chain/transaction/signature/inputsig/arbitrary_message/mod.rs @@ -22,20 +22,20 @@ use crypto::key::SigAuxDataProvider; use serialization::Encode; use crate::{ - chain::{signature::DestinationSigError, ChainConfig, Destination}, - primitives::{id::default_hash, H256}, + chain::{ChainConfig, Destination, signature::DestinationSigError}, + primitives::{H256, id::default_hash}, }; use super::{ authorize_pubkey_spend::{ - sign_public_key_spending, verify_public_key_spending, AuthorizedPublicKeySpend, + AuthorizedPublicKeySpend, sign_public_key_spending, verify_public_key_spending, }, authorize_pubkeyhash_spend::{ - sign_public_key_hash_spending, sign_public_key_hash_spending_unchecked, - verify_public_key_hash_spending, AuthorizedPublicKeyHashSpend, + AuthorizedPublicKeyHashSpend, sign_public_key_hash_spending, + sign_public_key_hash_spending_unchecked, verify_public_key_hash_spending, }, classical_multisig::authorize_classical_multisig::{ - verify_classical_multisig_spending, AuthorizedClassicalMultisigSpend, + AuthorizedClassicalMultisigSpend, verify_classical_multisig_spending, }, }; @@ -43,7 +43,9 @@ use super::{ pub enum SignArbitraryMessageError { #[error("Destination signature error: {0}")] DestinationSigError(#[from] DestinationSigError), - #[error("AnyoneCanSpend should not use standard signatures, so producing a signature for it is not possible")] + #[error( + "AnyoneCanSpend should not use standard signatures, so producing a signature for it is not possible" + )] AttemptedToProduceSignatureForAnyoneCanSpend, #[error("Classical multisig signature attempted in uni-party function")] AttemptedToProduceClassicalMultisigSignatureInUnipartySignatureCode, diff --git a/common/src/chain/transaction/signature/inputsig/arbitrary_message/tests.rs b/common/src/chain/transaction/signature/inputsig/arbitrary_message/tests.rs index d919b0fe99..490f3491f7 100644 --- a/common/src/chain/transaction/signature/inputsig/arbitrary_message/tests.rs +++ b/common/src/chain/transaction/signature/inputsig/arbitrary_message/tests.rs @@ -18,7 +18,7 @@ use std::borrow::Cow; use rstest::rstest; use chain::signature::{ - inputsig::{standard_signature::StandardInputSignature, InputWitness}, + inputsig::{InputWitness, standard_signature::StandardInputSignature}, sighash::input_commitments::SighashInputCommitment, sighash::{sighashtype::SigHashType, signature_hash}, tests::utils::verify_signature, @@ -32,13 +32,13 @@ use randomness::RngExt; use serialization::DecodeAll; use test_utils::{ assert_matches, - random::{flip_random_bit, with_random_bit_flipped, Seed}, + random::{Seed, flip_random_bit, with_random_bit_flipped}, }; use crate::{ address::pubkeyhash::PublicKeyHash, chain::{self, Destination, SignedTransaction}, - primitives::{id::DefaultHashAlgoStream, Id}, + primitives::{Id, id::DefaultHashAlgoStream}, }; use super::*; diff --git a/common/src/chain/transaction/signature/inputsig/authorize_pubkey_spend.rs b/common/src/chain/transaction/signature/inputsig/authorize_pubkey_spend.rs index f267b424e4..9cee3e2532 100644 --- a/common/src/chain/transaction/signature/inputsig/authorize_pubkey_spend.rs +++ b/common/src/chain/transaction/signature/inputsig/authorize_pubkey_spend.rs @@ -80,11 +80,11 @@ mod test { use crate::{ address::pubkeyhash::PublicKeyHash, chain::{ - signature::{sighash::signature_hash, StandardInputSignature}, + Destination, + signature::{StandardInputSignature, sighash::signature_hash}, transaction::signature::tests::utils::{ generate_input_commitments, generate_unsigned_tx, sig_hash_types, }, - Destination, }, }; diff --git a/common/src/chain/transaction/signature/inputsig/authorize_pubkeyhash_spend.rs b/common/src/chain/transaction/signature/inputsig/authorize_pubkeyhash_spend.rs index 1497489418..a96d23ffbe 100644 --- a/common/src/chain/transaction/signature/inputsig/authorize_pubkeyhash_spend.rs +++ b/common/src/chain/transaction/signature/inputsig/authorize_pubkeyhash_spend.rs @@ -109,11 +109,11 @@ mod test { use test_utils::random::Seed; use crate::chain::{ - signature::{sighash::signature_hash, StandardInputSignature}, + Destination, + signature::{StandardInputSignature, sighash::signature_hash}, transaction::signature::tests::utils::{ generate_input_commitments, generate_unsigned_tx, sig_hash_types, }, - Destination, }; use super::*; diff --git a/common/src/chain/transaction/signature/inputsig/classical_multisig/authorize_classical_multisig.rs b/common/src/chain/transaction/signature/inputsig/classical_multisig/authorize_classical_multisig.rs index 4f25b5d35e..d7038fac22 100644 --- a/common/src/chain/transaction/signature/inputsig/classical_multisig/authorize_classical_multisig.rs +++ b/common/src/chain/transaction/signature/inputsig/classical_multisig/authorize_classical_multisig.rs @@ -21,12 +21,12 @@ use serialization::{Decode, DecodeAll, Encode}; use crate::{ address::pubkeyhash::PublicKeyHash, chain::{ + ChainConfig, classic_multisig::{ClassicMultisigChallenge, ClassicMultisigChallengeError}, signature::{ - inputsig::classical_multisig::multisig_partial_signature::PartiallySignedMultisigChallenge, DestinationSigError, + inputsig::classical_multisig::multisig_partial_signature::PartiallySignedMultisigChallenge, }, - ChainConfig, }, primitives::H256, }; @@ -229,7 +229,7 @@ pub fn sign_classical_multisig_spending( key_index, challenge.public_keys().len(), ), - ) + ); } }; @@ -273,7 +273,7 @@ mod tests { use randomness::{RngExt as _, SliceRandom}; use rstest::rstest; use std::cmp::Ordering; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use crate::chain::config::create_mainnet; diff --git a/common/src/chain/transaction/signature/inputsig/classical_multisig/encode_decode_multisig_spend.rs b/common/src/chain/transaction/signature/inputsig/classical_multisig/encode_decode_multisig_spend.rs index 24a59878f1..ff5e0f002e 100644 --- a/common/src/chain/transaction/signature/inputsig/classical_multisig/encode_decode_multisig_spend.rs +++ b/common/src/chain/transaction/signature/inputsig/classical_multisig/encode_decode_multisig_spend.rs @@ -16,15 +16,15 @@ use serialization::Encode; use crate::chain::{ + TxOutput, signature::{ + DestinationSigError, inputsig::{ authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, standard_signature::StandardInputSignature, }, sighash::sighashtype::SigHashType, - DestinationSigError, }, - TxOutput, }; use super::authorize_classical_multisig::AuthorizedClassicalMultisigSpend; diff --git a/common/src/chain/transaction/signature/inputsig/classical_multisig/multisig_partial_signature.rs b/common/src/chain/transaction/signature/inputsig/classical_multisig/multisig_partial_signature.rs index f7b294ecee..91341490e4 100644 --- a/common/src/chain/transaction/signature/inputsig/classical_multisig/multisig_partial_signature.rs +++ b/common/src/chain/transaction/signature/inputsig/classical_multisig/multisig_partial_signature.rs @@ -14,8 +14,8 @@ // limitations under the License. use crate::chain::{ - classic_multisig::{ClassicMultisigChallenge, ClassicMultisigChallengeError}, ChainConfig, + classic_multisig::{ClassicMultisigChallenge, ClassicMultisigChallengeError}, }; use super::authorize_classical_multisig::AuthorizedClassicalMultisigSpend; @@ -155,7 +155,7 @@ mod tests { use crypto::key::{KeyKind, PrivateKey, Signature}; use randomness::{CryptoRng, IndexedMutRandom as _, Rng, RngExt as _, SliceRandom}; use serialization::{DecodeAll, Encode}; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use crate::{chain::config::create_mainnet, primitives::H256}; diff --git a/common/src/chain/transaction/signature/inputsig/htlc.rs b/common/src/chain/transaction/signature/inputsig/htlc.rs index 343b2e9005..871827c5e4 100644 --- a/common/src/chain/transaction/signature/inputsig/htlc.rs +++ b/common/src/chain/transaction/signature/inputsig/htlc.rs @@ -19,15 +19,15 @@ use serialization::Encode; use standard_signature::StandardInputSignature; use crate::chain::{ - htlc::HtlcSecret, signature::sighash::input_commitments::SighashInputCommitment, ChainConfig, - Destination, Transaction, + ChainConfig, Destination, Transaction, htlc::HtlcSecret, + signature::sighash::input_commitments::SighashInputCommitment, }; use super::{ - super::sighash::sighashtype::SigHashType, + super::sighash::sighashtype::SigHashType, DestinationSigError, Signable, authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, classical_multisig::authorize_classical_multisig::AuthorizedClassicalMultisigSpend, - standard_signature, DestinationSigError, Signable, + standard_signature, }; #[allow(clippy::too_many_arguments)] diff --git a/common/src/chain/transaction/signature/inputsig/standard_signature.rs b/common/src/chain/transaction/signature/inputsig/standard_signature.rs index 8b3539cb96..b7827d5b44 100644 --- a/common/src/chain/transaction/signature/inputsig/standard_signature.rs +++ b/common/src/chain/transaction/signature/inputsig/standard_signature.rs @@ -20,28 +20,28 @@ use serialization::{Decode, DecodeAll, Encode}; use crate::{ chain::{ + ChainConfig, Destination, Transaction, signature::{ + DestinationSigError, Signable, sighash::{ input_commitments::SighashInputCommitment, sighashtype::SigHashType, signature_hash, }, - DestinationSigError, Signable, }, - ChainConfig, Destination, Transaction, }, primitives::H256, }; use super::{ authorize_pubkey_spend::{ - sign_public_key_spending, verify_public_key_spending, AuthorizedPublicKeySpend, + AuthorizedPublicKeySpend, sign_public_key_spending, verify_public_key_spending, }, authorize_pubkeyhash_spend::{ - sign_public_key_hash_spending, verify_public_key_hash_spending, - AuthorizedPublicKeyHashSpend, + AuthorizedPublicKeyHashSpend, sign_public_key_hash_spending, + verify_public_key_hash_spending, }, classical_multisig::{ authorize_classical_multisig::{ - verify_classical_multisig_spending, AuthorizedClassicalMultisigSpend, + AuthorizedClassicalMultisigSpend, verify_classical_multisig_spending, }, multisig_partial_signature::PartiallySignedMultisigChallenge, }, @@ -159,10 +159,10 @@ impl StandardInputSignature { match verification_result { SigsVerifyResult::CompleteAndValid => (), SigsVerifyResult::Incomplete => { - return Err(DestinationSigError::IncompleteClassicalMultisigAuthorization) + return Err(DestinationSigError::IncompleteClassicalMultisigAuthorization); } SigsVerifyResult::Invalid => { - return Err(DestinationSigError::InvalidClassicalMultisigAuthorization) + return Err(DestinationSigError::InvalidClassicalMultisigAuthorization); } } @@ -224,12 +224,12 @@ mod test { use crate::{ address::pubkeyhash::PublicKeyHash, chain::{ + Destination, config::create_mainnet, - signature::{sighash::signature_hash, DestinationSigError}, + signature::{DestinationSigError, sighash::signature_hash}, transaction::signature::tests::utils::{ generate_input_commitments, generate_unsigned_tx, sig_hash_types, }, - Destination, }, }; diff --git a/common/src/chain/transaction/signature/mod.rs b/common/src/chain/transaction/signature/mod.rs index 8193a1a050..633da718a9 100644 --- a/common/src/chain/transaction/signature/mod.rs +++ b/common/src/chain/transaction/signature/mod.rs @@ -24,12 +24,12 @@ use super::{Destination, TxOutput}; use self::{ inputsig::{ + InputWitness, classical_multisig::{ authorize_classical_multisig::ClassicalMultisigSigningError, multisig_partial_signature::PartiallySignedMultisigStructureError, }, standard_signature::StandardInputSignature, - InputWitness, }, sighash::{input_commitments::SighashInputCommitment, signature_hash}, }; @@ -75,7 +75,9 @@ pub enum DestinationSigError { SpendeePrivatePublicKeyMismatch, #[error("AnyoneCanSpend should not use standard signatures, this place should be unreachable")] AttemptedToVerifyStandardSignatureForAnyoneCanSpend, - #[error("AnyoneCanSpend should not use standard signatures, so producing a signature for it is not possible")] + #[error( + "AnyoneCanSpend should not use standard signatures, so producing a signature for it is not possible" + )] AttemptedToProduceSignatureForAnyoneCanSpend, #[error("Classical multisig signature attempted in uni-party function")] AttemptedToProduceClassicalMultisigSignatureInUnipartySignatureCode, @@ -146,7 +148,7 @@ pub fn verify_signature( | Destination::ScriptHash(_) | Destination::ClassicMultisig(_) => match input_witness { EvaluatedInputWitness::NoSignature(_) => { - return Err(DestinationSigError::SignatureNotFound) + return Err(DestinationSigError::SignatureNotFound); } EvaluatedInputWitness::Standard(witness) => { let sighash = @@ -157,7 +159,7 @@ pub fn verify_signature( Destination::AnyoneCanSpend => match input_witness { EvaluatedInputWitness::NoSignature(_) => {} EvaluatedInputWitness::Standard(_) => { - return Err(DestinationSigError::SignatureNotNeeded) + return Err(DestinationSigError::SignatureNotNeeded); } }, } diff --git a/common/src/chain/transaction/signature/sighash/hashable.rs b/common/src/chain/transaction/signature/sighash/hashable.rs index 1c302eb46e..fb07f7f711 100644 --- a/common/src/chain/transaction/signature/sighash/hashable.rs +++ b/common/src/chain/transaction/signature/sighash/hashable.rs @@ -17,10 +17,10 @@ use utils::ensure; use crate::{ chain::{ - signature::{sighash::sighashtype, DestinationSigError}, TxInput, TxOutput, + signature::{DestinationSigError, sighash::sighashtype}, }, - primitives::id::{hash_encoded_to, DefaultHashAlgoStream}, + primitives::id::{DefaultHashAlgoStream, hash_encoded_to}, }; use super::SighashInputCommitment; @@ -137,17 +137,17 @@ mod tests { use crypto::hash::StreamHasher; use randomness::{CryptoRng, Rng, RngExt as _}; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use crate::{ chain::{ + OutPointSourceId, signature::{ - sighash::{sighashtype::SigHashType, SighashInputCommitment}, + sighash::{SighashInputCommitment, sighashtype::SigHashType}, tests::utils::{generate_input_commitments, generate_inputs_utxos, sig_hash_types}, }, - OutPointSourceId, }, - primitives::{Id, H256}, + primitives::{H256, Id}, }; use super::*; @@ -194,14 +194,16 @@ mod tests { let index_to_hash = rng.random_range(0..inputs.len()); // Invalid input index - assert!(hashable_inputs - .signature_hash( - &mut stream, - SigHashType::all(), - &inputs[index_to_hash], - index_to_hash, - ) - .is_ok()); + assert!( + hashable_inputs + .signature_hash( + &mut stream, + SigHashType::all(), + &inputs[index_to_hash], + index_to_hash, + ) + .is_ok() + ); // Valid case assert_eq!( diff --git a/common/src/chain/transaction/signature/sighash/input_commitments/info_providers.rs b/common/src/chain/transaction/signature/sighash/input_commitments/info_providers.rs index 44ad0b6417..039612c30d 100644 --- a/common/src/chain/transaction/signature/sighash/input_commitments/info_providers.rs +++ b/common/src/chain/transaction/signature/sighash/input_commitments/info_providers.rs @@ -16,7 +16,7 @@ use std::{borrow::Cow, collections::BTreeMap}; use crate::{ - chain::{output_value::OutputValue, OrderId, PoolId, TxOutput, UtxoOutPoint}, + chain::{OrderId, PoolId, TxOutput, UtxoOutPoint, output_value::OutputValue}, primitives::Amount, }; diff --git a/common/src/chain/transaction/signature/sighash/input_commitments/mod.rs b/common/src/chain/transaction/signature/sighash/input_commitments/mod.rs index 53f5753f0b..fc9417d7f5 100644 --- a/common/src/chain/transaction/signature/sighash/input_commitments/mod.rs +++ b/common/src/chain/transaction/signature/sighash/input_commitments/mod.rs @@ -24,8 +24,8 @@ use utils::cow_utils::CowUtils as _; use crate::{ chain::{ - output_value::OutputValue, AccountCommand, ChainConfig, OrderAccountCommand, OrderId, - PoolId, SighashInputCommitmentVersion, TxInput, TxOutput, UtxoOutPoint, + AccountCommand, ChainConfig, OrderAccountCommand, OrderId, PoolId, + SighashInputCommitmentVersion, TxInput, TxOutput, UtxoOutPoint, output_value::OutputValue, }, primitives::{Amount, BlockHeight}, }; diff --git a/common/src/chain/transaction/signature/sighash/mod.rs b/common/src/chain/transaction/signature/sighash/mod.rs index a05006ebaf..667b65a491 100644 --- a/common/src/chain/transaction/signature/sighash/mod.rs +++ b/common/src/chain/transaction/signature/sighash/mod.rs @@ -22,8 +22,8 @@ pub mod input_commitments; pub mod sighashtype; use crate::primitives::{ - id::{hash_encoded_to, DefaultHashAlgoStream}, H256, + id::{DefaultHashAlgoStream, hash_encoded_to}, }; use self::hashable::{SignatureHashableElement, SignatureHashableInputs}; diff --git a/common/src/chain/transaction/signature/tests/mixed_sighash_types.rs b/common/src/chain/transaction/signature/tests/mixed_sighash_types.rs index 3336c82883..960f8f3bbd 100644 --- a/common/src/chain/transaction/signature/tests/mixed_sighash_types.rs +++ b/common/src/chain/transaction/signature/tests/mixed_sighash_types.rs @@ -21,7 +21,7 @@ use test_utils::random::Seed; use super::utils::*; use crate::chain::config::create_mainnet; -use crate::chain::{signature::inputsig::InputWitness, Destination}; +use crate::chain::{Destination, signature::inputsig::InputWitness}; // Create a transaction with a different signature hash type for every input. // This test takes a long time to finish, so it is ignored by default. diff --git a/common/src/chain/transaction/signature/tests/mod.rs b/common/src/chain/transaction/signature/tests/mod.rs index bb68702f1f..38f3981228 100644 --- a/common/src/chain/transaction/signature/tests/mod.rs +++ b/common/src/chain/transaction/signature/tests/mod.rs @@ -26,16 +26,16 @@ use test_utils::random::Seed; use crate::{ chain::{ - config::create_mainnet, output_value::OutputValue, ChainConfig, Destination, - OutPointSourceId, Transaction, TxInput, TxOutput, TxOutputTag, + ChainConfig, Destination, OutPointSourceId, Transaction, TxInput, TxOutput, TxOutputTag, + config::create_mainnet, output_value::OutputValue, }, - primitives::{Amount, Id, H256}, + primitives::{Amount, H256, Id}, }; use super::{ - inputsig::{standard_signature::StandardInputSignature, InputWitness}, - sighash::{input_commitments::SighashInputCommitment, sighashtype::SigHashType}, DestinationSigError, + inputsig::{InputWitness, standard_signature::StandardInputSignature}, + sighash::{input_commitments::SighashInputCommitment, sighashtype::SigHashType}, }; use self::utils::*; diff --git a/common/src/chain/transaction/signature/tests/sign_and_mutate.rs b/common/src/chain/transaction/signature/tests/sign_and_mutate.rs index 1f82205c58..970346c94b 100644 --- a/common/src/chain/transaction/signature/tests/sign_and_mutate.rs +++ b/common/src/chain/transaction/signature/tests/sign_and_mutate.rs @@ -19,18 +19,18 @@ use test_utils::random::Seed; use crate::{ chain::{ + AccountCommand, AccountOutPoint, AccountSpending, ChainConfig, DelegationId, Destination, + OrderAccountCommand, OrderId, OutPointSourceId, Transaction, TxInput, TxOutput, + UtxoOutPoint, config::create_mainnet, signature::{ - sighash::sighashtype::{OutputsMode, SigHashType}, DestinationSigError, + sighash::sighashtype::{OutputsMode, SigHashType}, }, signed_transaction::SignedTransaction, tokens::TokenId, - AccountCommand, AccountOutPoint, AccountSpending, ChainConfig, DelegationId, Destination, - OrderAccountCommand, OrderId, OutPointSourceId, Transaction, TxInput, TxOutput, - UtxoOutPoint, }, - primitives::{Amount, Id, H256}, + primitives::{Amount, H256, Id}, }; use crypto::key::{KeyKind, PrivateKey}; use randomness::{CryptoRng, Rng, RngExt as _}; diff --git a/common/src/chain/transaction/signature/tests/sign_and_verify.rs b/common/src/chain/transaction/signature/tests/sign_and_verify.rs index 521c8cb062..ae2708d681 100644 --- a/common/src/chain/transaction/signature/tests/sign_and_verify.rs +++ b/common/src/chain/transaction/signature/tests/sign_and_verify.rs @@ -24,14 +24,14 @@ use super::utils::*; use crate::{ address::pubkeyhash::PublicKeyHash, chain::{ + Destination, config::create_mainnet, signature::{ - sighash::sighashtype::{OutputsMode, SigHashType}, DestinationSigError, + sighash::sighashtype::{OutputsMode, SigHashType}, }, - Destination, }, - primitives::{Id, H256}, + primitives::{H256, Id}, }; // Generate a transaction with a different number of inputs and outputs, then sign it as a whole. diff --git a/common/src/chain/transaction/signature/tests/utils.rs b/common/src/chain/transaction/signature/tests/utils.rs index 2c64a319f4..12a0f4a3e1 100644 --- a/common/src/chain/transaction/signature/tests/utils.rs +++ b/common/src/chain/transaction/signature/tests/utils.rs @@ -22,23 +22,24 @@ use crypto::{ key::{KeyKind, PrivateKey, PublicKey}, vrf::{VRFKeyKind, VRFPrivateKey, VRFPublicKey}, }; -use randomness::{seq::IteratorRandom as _, CryptoRng, Rng, RngExt as _}; +use randomness::{CryptoRng, Rng, RngExt as _, seq::IteratorRandom as _}; use script::Script; use test_utils::{random::gen_random_bytes, random_ascii_alphanumeric_string}; use crate::{ address::pubkeyhash::PublicKeyHash, chain::{ - self, + self, AccountNonce, AccountSpending, ChainConfig, DelegationId, Destination, OrderData, + PoolId, Transaction, TransactionCreationError, TxInput, TxOutput, TxOutputTag, htlc::{HashedTimelockContract, HtlcSecretHash}, output_value::OutputValue, signature::{ - inputsig::{standard_signature::StandardInputSignature, InputWitness}, + DestinationSigError, EvaluatedInputWitness, Signable, + inputsig::{InputWitness, standard_signature::StandardInputSignature}, sighash::{ input_commitments::{SighashInputCommitment, SighashInputCommitmentTag}, sighashtype::SigHashType, }, - DestinationSigError, EvaluatedInputWitness, Signable, }, signed_transaction::SignedTransaction, stakelock::StakePoolData, @@ -47,10 +48,8 @@ use crate::{ IsTokenFreezable, Metadata, NftIssuance, NftIssuanceV0, TokenId, TokenIssuance, TokenIssuanceV1, TokenTotalSupply, }, - AccountNonce, AccountSpending, ChainConfig, DelegationId, Destination, OrderData, PoolId, - Transaction, TransactionCreationError, TxInput, TxOutput, TxOutputTag, }, - primitives::{amount::UnsignedIntType, per_thousand::PerThousand, Amount, Id, H256}, + primitives::{Amount, H256, Id, amount::UnsignedIntType, per_thousand::PerThousand}, }; fn make_random_output_value(rng: &mut impl CryptoRng) -> OutputValue { diff --git a/common/src/chain/transaction/signed_transaction.rs b/common/src/chain/transaction/signed_transaction.rs index ac63708da9..66cf4cc031 100644 --- a/common/src/chain/transaction/signed_transaction.rs +++ b/common/src/chain/transaction/signed_transaction.rs @@ -14,13 +14,13 @@ // limitations under the License. use super::{ - signature::{inputsig::InputWitness, Signable, Transactable}, Transaction, TransactionSize, TxOutput, + signature::{Signable, Transactable, inputsig::InputWitness}, }; use crate::{ chain::{ - output_value::OutputValue, output_values_holder::OutputValuesHolder, - TransactionCreationError, TxInput, + TransactionCreationError, TxInput, output_value::OutputValue, + output_values_holder::OutputValuesHolder, }, primitives::id::{self, H256}, }; @@ -150,14 +150,14 @@ impl OutputValuesHolder for SignedTransaction { mod tests { use crate::primitives::Amount; use rstest::rstest; - use test_utils::random::{make_seedable_rng, RngExt as _, Seed}; + use test_utils::random::{RngExt as _, Seed, make_seedable_rng}; use super::*; - use crate::chain::output_value::OutputValue; use crate::chain::TxInput; - use crate::primitives::id::Id; + use crate::chain::output_value::OutputValue; use crate::primitives::H256; + use crate::primitives::id::Id; #[test] fn require_inputs_witnesses_same_size() { @@ -193,14 +193,16 @@ mod tests { } { let tx = Transaction::new(0x00, ins1, vec![]).unwrap(); - assert!(SignedTransaction::new( - tx.clone(), - vec![ - InputWitness::NoSignature(Some(vec![0x01, 0x05, 0x09])), - InputWitness::NoSignature(Some(vec![0x91, 0x55, 0x19, 0x00])), - ], - ) - .is_ok()); + assert!( + SignedTransaction::new( + tx.clone(), + vec![ + InputWitness::NoSignature(Some(vec![0x01, 0x05, 0x09])), + InputWitness::NoSignature(Some(vec![0x91, 0x55, 0x19, 0x00])), + ], + ) + .is_ok() + ); assert_eq!( SignedTransaction::new( tx.clone(), diff --git a/common/src/chain/transaction/signed_transaction_intent.rs b/common/src/chain/transaction/signed_transaction_intent.rs index e16a58550d..6c308d2a93 100644 --- a/common/src/chain/transaction/signed_transaction_intent.rs +++ b/common/src/chain/transaction/signed_transaction_intent.rs @@ -19,16 +19,16 @@ use utils::ensure; use crate::{ chain::{ + ChainConfig, Destination, Transaction, signature::inputsig::arbitrary_message::{ self, ArbitraryMessageSignature, ArbitraryMessageSignatureRef, }, - ChainConfig, Destination, Transaction, }, primitives::{Id, Idable as _}, }; use super::signature::{ - inputsig::arbitrary_message::SignArbitraryMessageError, DestinationSigError, + DestinationSigError, inputsig::arbitrary_message::SignArbitraryMessageError, }; /// `SignedTransactionIntent` acts as a proof that a certain transaction was created with the specific intent in mind. @@ -274,13 +274,13 @@ mod tests { use randomness::RngExt; use test_utils::{ assert_matches, - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, random_ascii_alphanumeric_string, }; use crate::{ address::pubkeyhash::PublicKeyHash, - chain::{config, Destination, OutPointSourceId, Transaction, TxInput}, + chain::{Destination, OutPointSourceId, Transaction, TxInput, config}, primitives::H256, }; @@ -293,8 +293,7 @@ mod tests { .unwrap(), ); let message = SignedTransactionIntent::get_message_to_sign("test intent", &tx_id); - let expected_message = - ""; + let expected_message = ""; assert_eq!(message, expected_message); } diff --git a/common/src/chain/transaction/transaction_v1.rs b/common/src/chain/transaction/transaction_v1.rs index b68055d6e6..9c6999a407 100644 --- a/common/src/chain/transaction/transaction_v1.rs +++ b/common/src/chain/transaction/transaction_v1.rs @@ -13,11 +13,11 @@ // See the License for the specific language governing permissions and // limitations under the License. +pub use crate::chain::transaction::TransactionCreationError; pub use crate::chain::transaction::input::*; pub use crate::chain::transaction::output::*; -pub use crate::chain::transaction::TransactionCreationError; use crate::primitives::H256; -use crate::primitives::{id, Id, Idable, VersionTag}; +use crate::primitives::{Id, Idable, VersionTag, id}; use serialization::{Decode, Encode, Tagged}; use super::Transaction; diff --git a/common/src/chain/transaction/utxo_outpoint.rs b/common/src/chain/transaction/utxo_outpoint.rs index 9d5d25362b..6ff8f6fa2b 100644 --- a/common/src/chain/transaction/utxo_outpoint.rs +++ b/common/src/chain/transaction/utxo_outpoint.rs @@ -13,7 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::chain::{transaction::Transaction, Block, GenBlock, Genesis}; +use crate::chain::{Block, GenBlock, Genesis, transaction::Transaction}; use crate::primitives::Id; use serialization::{Decode, Encode}; diff --git a/common/src/chain/upgrades/consensus_upgrade.rs b/common/src/chain/upgrades/consensus_upgrade.rs index b65ff31ab1..6a0250e6d6 100644 --- a/common/src/chain/upgrades/consensus_upgrade.rs +++ b/common/src/chain/upgrades/consensus_upgrade.rs @@ -13,13 +13,13 @@ // See the License for the specific language governing permissions and // limitations under the License. +use crate::Uint256; use crate::chain::config::ChainType; use crate::chain::pos::{DEFAULT_BLOCK_COUNT_TO_AVERAGE, DEFAULT_MATURITY_BLOCK_COUNT_V0}; use crate::chain::pow::limit; -use crate::chain::{pos_initial_difficulty, PoSChainConfig, PoSConsensusVersion}; +use crate::chain::{PoSChainConfig, PoSConsensusVersion, pos_initial_difficulty}; use crate::primitives::per_thousand::PerThousand; use crate::primitives::{BlockHeight, Compact}; -use crate::Uint256; use super::NetUpgrades; diff --git a/common/src/chain/upgrades/netupgrade.rs b/common/src/chain/upgrades/netupgrade.rs index 793c229393..bd53f736f2 100644 --- a/common/src/chain/upgrades/netupgrade.rs +++ b/common/src/chain/upgrades/netupgrade.rs @@ -79,12 +79,12 @@ impl NetUpgrades { #[cfg(test)] mod tests { use super::*; + use crate::Uint256; use crate::chain::upgrades::netupgrade::NetUpgrades; use crate::chain::{ ConsensusUpgrade, PoSChainConfigBuilder, PoSStatus, PoWStatus, RequiredConsensus, }; use crate::primitives::BlockHeight; - use crate::Uint256; #[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)] pub enum MockVersion { diff --git a/common/src/lib.rs b/common/src/lib.rs index c617543393..e386c6b722 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -41,10 +41,10 @@ mod tests { use crate::{ address::pubkeyhash::PublicKeyHash, chain::{ - tokens::TokenId, Block, DelegationId, Destination, GenBlock, OrderId, PoolId, - Transaction, + Block, DelegationId, Destination, GenBlock, OrderId, PoolId, Transaction, + tokens::TokenId, }, - primitives::{Id, H256}, + primitives::{H256, Id}, }; #[ctor::ctor] diff --git a/common/src/primitives/amount/rpc.rs b/common/src/primitives/amount/rpc.rs index 238307f98b..31c7b533fd 100644 --- a/common/src/primitives/amount/rpc.rs +++ b/common/src/primitives/amount/rpc.rs @@ -14,8 +14,8 @@ // limitations under the License. use crate::{ - chain::{ChainConfig, Currency}, TokenDecimalsProvider, TokenDecimalsUnavailableError, + chain::{ChainConfig, Currency}, }; use super::{Amount, DecimalAmount, RpcAmountInSerde, RpcAmountOutSerde}; diff --git a/common/src/primitives/amount/tests.rs b/common/src/primitives/amount/tests.rs index 366c89ae5c..92d742e45f 100644 --- a/common/src/primitives/amount/tests.rs +++ b/common/src/primitives/amount/tests.rs @@ -17,7 +17,7 @@ use super::{signed::SignedIntType, *}; use randomness::RngExt; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; #[test] fn creation() { diff --git a/common/src/primitives/bech32_encoding/error.rs b/common/src/primitives/bech32_encoding/error.rs index 17943fbb05..e8ada14bd1 100644 --- a/common/src/primitives/bech32_encoding/error.rs +++ b/common/src/primitives/bech32_encoding/error.rs @@ -14,9 +14,8 @@ // limitations under the License. use bech32::{ - self, + self, DecodeError, EncodeError, primitives::{decode::CheckedHrpstringError, hrp}, - DecodeError, EncodeError, }; #[derive(thiserror::Error, PartialEq, Eq, PartialOrd, Ord, Debug, Clone)] diff --git a/common/src/primitives/bech32_encoding/mod.rs b/common/src/primitives/bech32_encoding/mod.rs index acd4b25240..6947562d8c 100644 --- a/common/src/primitives/bech32_encoding/mod.rs +++ b/common/src/primitives/bech32_encoding/mod.rs @@ -14,7 +14,7 @@ // limitations under the License. mod error; -use bech32::{primitives::decode::CheckedHrpstring, Bech32m, Hrp}; +use bech32::{Bech32m, Hrp, primitives::decode::CheckedHrpstring}; pub use error::*; pub fn bech32m_decode(s: impl AsRef) -> Result { diff --git a/common/src/primitives/bech32_encoding/tests.rs b/common/src/primitives/bech32_encoding/tests.rs index e66b0dbd89..1cea2328a7 100644 --- a/common/src/primitives/bech32_encoding/tests.rs +++ b/common/src/primitives/bech32_encoding/tests.rs @@ -15,9 +15,9 @@ use bitcoin_bech32::WitnessProgram; use hex::FromHex; -use randomness::{distributions::Alphanumeric, make_pseudo_rng, Rng, RngExt as _}; +use randomness::{Rng, RngExt as _, distributions::Alphanumeric, make_pseudo_rng}; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use super::Bech32Error; @@ -204,7 +204,8 @@ fn check_arbitraty_data_convertion() { )] #[trace] #[case( - "hrp10gs8jgrcypmjqa3qw5s8ggrnypezqufqwqsx7grwypkjqmpqdvsx5grfyp5zqeeqvcsx2gryyp3jqc3qvyq7p8jc","7a2079207820772076207520742073207220712070206f206e206d206c206b206a206920682067206620652064206320622061" + "hrp10gs8jgrcypmjqa3qw5s8ggrnypezqufqwqsx7grwypkjqmpqdvsx5grfyp5zqeeqvcsx2gryyp3jqc3qvyq7p8jc", + "7a2079207820772076207520742073207220712070206f206e206d206c206b206a206920682067206620652064206320622061" )] #[trace] #[case("hrp1xyerxdp4xcmnswfs3y3n8w", "31323334353637383930")] diff --git a/common/src/primitives/height.rs b/common/src/primitives/height.rs index 6dcde4fb1a..6a0d64c8db 100644 --- a/common/src/primitives/height.rs +++ b/common/src/primitives/height.rs @@ -315,8 +315,8 @@ mod tests { fn blockheight_json() { fn check(height: BlockHeight) { use serde_test::{ - assert_tokens, Token::{NewtypeStruct, U64}, + assert_tokens, }; // Block height serializes to just a number, represented by a newtype struct assert_tokens( diff --git a/common/src/primitives/id/mod.rs b/common/src/primitives/id/mod.rs index 0fd19c1594..cda40234e7 100644 --- a/common/src/primitives/id/mod.rs +++ b/common/src/primitives/id/mod.rs @@ -20,7 +20,7 @@ mod with_id; use std::fmt::{Debug, Display, LowerHex, UpperHex}; -use generic_array::{typenum, GenericArray}; +use generic_array::{GenericArray, typenum}; use ref_cast::RefCast; use crypto::hash::StreamHasher; @@ -354,7 +354,7 @@ mod tests { #[test] fn hashes_stream_and_msg_identical() { - use randomness::{make_pseudo_rng, RngExt as _}; + use randomness::{RngExt as _, make_pseudo_rng}; let random_bytes = make_pseudo_rng().random::<[u8; H256::len_bytes()]>(); let h1 = default_hash(random_bytes); diff --git a/common/src/primitives/mod.rs b/common/src/primitives/mod.rs index 0eb924a5db..3d31deb0bb 100644 --- a/common/src/primitives/mod.rs +++ b/common/src/primitives/mod.rs @@ -31,7 +31,7 @@ pub use amount::{Amount, DecimalAmount, DisplayAmount}; pub use bech32_encoding::Bech32Error; pub use compact::Compact; pub use height::{BlockCount, BlockDistance, BlockHeight}; -pub use id::{Id, Idable, H256}; +pub use id::{H256, Id, Idable}; pub use version_tag::VersionTag; use crate::chain::{output_value::OutputValue, tokens::TokenId}; diff --git a/common/src/primitives/time.rs b/common/src/primitives/time.rs index c81f9505f3..f6f06f3717 100644 --- a/common/src/primitives/time.rs +++ b/common/src/primitives/time.rs @@ -193,7 +193,7 @@ mod tests { use logging::log; use randomness::RngExt as _; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use super::*; diff --git a/common/src/primitives_converters.rs b/common/src/primitives_converters.rs index 6e20760897..7af3ea8496 100644 --- a/common/src/primitives_converters.rs +++ b/common/src/primitives_converters.rs @@ -16,6 +16,9 @@ use crate::{ address::pubkeyhash::PublicKeyHash, chain::{ + AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, DelegationId, Destination, + GenBlock, OrderAccountCommand, OrderData, OrderId, OutPointSourceId, PoolId, Transaction, + TxInput, TxOutput, UtxoOutPoint, htlc::HashedTimelockContract, output_value::OutputValue, signature::sighash::input_commitments::SighashInputCommitment, @@ -25,14 +28,11 @@ use crate::{ IsTokenFreezable, IsTokenUnfreezable, NftIssuance, TokenId, TokenIssuance, TokenTotalSupply, }, - AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, DelegationId, Destination, - GenBlock, OrderAccountCommand, OrderData, OrderId, OutPointSourceId, PoolId, Transaction, - TxInput, TxOutput, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, Id, H256}, + primitives::{Amount, H256, Id, per_thousand::PerThousand}, }; use crypto::{ - key::{secp256k1::Secp256k1PublicKey, KeyKind, PublicKey}, + key::{KeyKind, PublicKey, secp256k1::Secp256k1PublicKey}, vrf::{SchnorrkelPublicKey, VRFKeyKind, VRFPublicKey}, }; use script::Script; diff --git a/common/src/size_estimation/mod.rs b/common/src/size_estimation/mod.rs index 97dbf9a51b..b522ddca7e 100644 --- a/common/src/size_estimation/mod.rs +++ b/common/src/size_estimation/mod.rs @@ -22,10 +22,12 @@ use crypto::key::{PredefinedSigAuxDataProvider, PrivateKey, PublicKey, Signature use serialization::{CompactLen, Encode}; use crate::chain::{ + Destination, SignedTransaction, Transaction, TxInput, TxOutput, classic_multisig::ClassicMultisigChallenge, - htlc::{HtlcSecret, HTLC_SECRET_SIZE}, + htlc::{HTLC_SECRET_SIZE, HtlcSecret}, signature::{ inputsig::{ + InputWitness, authorize_hashed_timelock_contract_spend::{ AuthorizedHashedTimelockContractSpend, AuthorizedHashedTimelockContractSpendTag, }, @@ -33,11 +35,9 @@ use crate::chain::{ authorize_pubkeyhash_spend::AuthorizedPublicKeyHashSpend, classical_multisig::authorize_classical_multisig::AuthorizedClassicalMultisigSpend, standard_signature::StandardInputSignature, - InputWitness, }, sighash::sighashtype::SigHashType, }, - Destination, SignedTransaction, Transaction, TxInput, TxOutput, }; /// Wallet errors diff --git a/common/src/size_estimation/tests.rs b/common/src/size_estimation/tests.rs index 3ddea28227..135ebefafb 100644 --- a/common/src/size_estimation/tests.rs +++ b/common/src/size_estimation/tests.rs @@ -23,36 +23,36 @@ use crypto::key::{KeyKind, PrivateKey}; use logging::log; use randomness::RngExt; use serialization::Encode; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use crate::{ address::pubkeyhash::PublicKeyHash, chain::{ + Destination, OutPointSourceId, SignedTransaction, Transaction, TxInput, TxOutput, classic_multisig::ClassicMultisigChallenge, config::create_unit_test_config, htlc::HtlcSecret, output_value::OutputValue, signature::{ inputsig::{ + InputWitness, authorize_hashed_timelock_contract_spend::{ AuthorizedHashedTimelockContractSpend, AuthorizedHashedTimelockContractSpendTag, }, - authorize_pubkey_spend::{sign_public_key_spending, AuthorizedPublicKeySpend}, + authorize_pubkey_spend::{AuthorizedPublicKeySpend, sign_public_key_spending}, authorize_pubkeyhash_spend::sign_public_key_hash_spending, classical_multisig::authorize_classical_multisig::{ - sign_classical_multisig_spending, AuthorizedClassicalMultisigSpend, + AuthorizedClassicalMultisigSpend, sign_classical_multisig_spending, }, standard_signature::StandardInputSignature, - InputWitness, }, sighash::sighashtype::SigHashType, }, - Destination, OutPointSourceId, SignedTransaction, Transaction, TxInput, TxOutput, }, - primitives::{Amount, Id, H256}, + primitives::{Amount, H256, Id}, size_estimation::{ - input_signature_size_from_destination, tx_size_with_num_inputs_and_outputs, - DestinationInfoProvider, MultisigInfo, + DestinationInfoProvider, MultisigInfo, input_signature_size_from_destination, + tx_size_with_num_inputs_and_outputs, }, }; diff --git a/common/src/uint/impls.rs b/common/src/uint/impls.rs index 71b9501247..7860dbc970 100644 --- a/common/src/uint/impls.rs +++ b/common/src/uint/impls.rs @@ -704,7 +704,7 @@ mod tests { use super::*; use crate::uint::BitArray; use randomness::RngExt; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; #[test] pub fn uint256_bits_test() { diff --git a/common/tests/primitives_repo_consistency/main.rs b/common/tests/primitives_repo_consistency/main.rs index 78f6630e43..9234d3e621 100644 --- a/common/tests/primitives_repo_consistency/main.rs +++ b/common/tests/primitives_repo_consistency/main.rs @@ -18,6 +18,8 @@ use strum::IntoEnumIterator as _; use common::{ chain::{ + AccountCommandTag, AccountNonce, AccountSpendingTag, DestinationTag, + OrderAccountCommandTag, OutPointSourceIdTag, TxInputTag, TxOutputTag, block::timestamp::BlockTimestamp, config::{Builder, ChainType}, output_value::OutputValueTag, @@ -27,16 +29,14 @@ use common::{ IsTokenFreezable, IsTokenUnfreezable, NftIssuanceTag, TokenIssuanceTag, TokenTotalSupplyTag, }, - AccountCommandTag, AccountNonce, AccountSpendingTag, DestinationTag, - OrderAccountCommandTag, OutPointSourceIdTag, TxInputTag, TxOutputTag, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight, Id, H256}, + primitives::{Amount, BlockHeight, H256, Id, per_thousand::PerThousand}, primitives_converters::TryConvertInto as _, }; use crypto::{key::KeyKind, vrf::VRFKeyKind}; use randomness::RngExt as _; use serialization::Encode; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use crate::utils::{ make_test_values_for_compact_encoding, diff --git a/common/tests/primitives_repo_consistency/utils/makers.rs b/common/tests/primitives_repo_consistency/utils/makers.rs index dee91aa752..302245b1ba 100644 --- a/common/tests/primitives_repo_consistency/utils/makers.rs +++ b/common/tests/primitives_repo_consistency/utils/makers.rs @@ -20,6 +20,10 @@ use strum::IntoEnumIterator as _; use common::{ address::pubkeyhash::PublicKeyHash, chain::{ + AccountCommand, AccountCommandTag, AccountNonce, AccountOutPoint, AccountSpending, + AccountSpendingTag, Destination, DestinationTag, OrderAccountCommand, + OrderAccountCommandTag, OrderData, OutPointSourceId, OutPointSourceIdTag, TxInput, + TxInputTag, TxOutput, TxOutputTag, UtxoOutPoint, block::timestamp::BlockTimestamp, htlc::{HashedTimelockContract, HtlcSecretHash}, output_value::{OutputValue, OutputValueTag}, @@ -33,12 +37,8 @@ use common::{ NftIssuanceV0, TokenCreator, TokenIssuance, TokenIssuanceTag, TokenIssuanceV1, TokenTotalSupply, TokenTotalSupplyTag, }, - AccountCommand, AccountCommandTag, AccountNonce, AccountOutPoint, AccountSpending, - AccountSpendingTag, Destination, DestinationTag, OrderAccountCommand, - OrderAccountCommandTag, OrderData, OutPointSourceId, OutPointSourceIdTag, TxInput, - TxInputTag, TxOutput, TxOutputTag, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight, H256}, + primitives::{Amount, BlockHeight, H256, per_thousand::PerThousand}, }; use crypto::{ key::{KeyKind, PrivateKey, PublicKey}, diff --git a/common/tests/primitives_repo_consistency/utils/mod.rs b/common/tests/primitives_repo_consistency/utils/mod.rs index d832f008ff..6caadef8ca 100644 --- a/common/tests/primitives_repo_consistency/utils/mod.rs +++ b/common/tests/primitives_repo_consistency/utils/mod.rs @@ -18,7 +18,7 @@ use rstest::rstest; use randomness::{CryptoRng, RngExt as _, SliceRandom}; use serialization::Encode; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use utils::sorted::Sorted; pub mod makers; diff --git a/common/tests/transaction.rs b/common/tests/transaction.rs index 350f3be6cb..e74f5e5a6b 100644 --- a/common/tests/transaction.rs +++ b/common/tests/transaction.rs @@ -13,11 +13,11 @@ // See the License for the specific language governing permissions and // limitations under the License. +use common::chain::DelegationId; use common::chain::signature::inputsig::InputWitness; use common::chain::signed_transaction::SignedTransaction; -use common::chain::DelegationId; use common::chain::{output_value::OutputValue, transaction::*}; -use common::primitives::{Amount, Id, Idable, H256}; +use common::primitives::{Amount, H256, Id, Idable}; use expect_test::expect; #[test] diff --git a/consensus/src/error.rs b/consensus/src/error.rs index c931fb9e6c..cc758b7dff 100644 --- a/consensus/src/error.rs +++ b/consensus/src/error.rs @@ -21,7 +21,7 @@ use common::{ primitives::Id, }; -use crate::{pos::error::ConsensusPoSError, ConsensusPoWError}; +use crate::{ConsensusPoWError, pos::error::ConsensusPoSError}; /// A consensus related error. #[derive(Error, Debug, PartialEq, Eq, Clone)] diff --git a/consensus/src/lib.rs b/consensus/src/lib.rs index 3e8476db7d..7ae49ae625 100644 --- a/consensus/src/lib.rs +++ b/consensus/src/lib.rs @@ -25,16 +25,16 @@ use std::{ops::Deref, sync::Arc}; use chainstate_types::{BlockIndex, BlockIndexHandle, GenBlockIndex}; use common::{ chain::{ + Block, ChainConfig, Destination, GenBlock, PoolId, RequiredConsensus, TxOutput, block::{ + BlockHeader, BlockReward, ConsensusData, signed_block_header::{ BlockHeaderSignature, BlockHeaderSignatureData, SignedBlockHeader, }, timestamp::BlockTimestamp, - BlockHeader, BlockReward, ConsensusData, }, output_value::OutputValue, timelock::OutputTimeLock, - Block, ChainConfig, Destination, GenBlock, PoolId, RequiredConsensus, TxOutput, }, primitives::{BlockHeight, Id}, }; @@ -45,24 +45,24 @@ use utils::atomics::RelaxedAtomicBool; pub use crate::{ error::ConsensusVerificationError, pos::{ + EffectivePoolBalanceError, StakeResult, block_sig::BlockSignatureError, calc_pos_hash_from_prv_key, check_pos_hash, compact_target_to_target, error::ConsensusPoSError, find_timestamp_for_staking, hash_check::calc_and_check_pos_hash, input_data::{ - generate_pos_consensus_data_and_reward, PoSFinalizeBlockInputData, - PoSGenerateBlockInputData, PoSTimestampSearchInputData, + PoSFinalizeBlockInputData, PoSGenerateBlockInputData, PoSTimestampSearchInputData, + generate_pos_consensus_data_and_reward, }, kernel::get_kernel_output, stake, target::{calculate_target_required, calculate_target_required_from_block_index}, - EffectivePoolBalanceError, StakeResult, }, pow::{ - calculate_work_required, check_proof_of_work, - input_data::{generate_pow_consensus_data_and_reward, PoWGenerateBlockInputData}, - mine, ConsensusPoWError, MiningResult, + ConsensusPoWError, MiningResult, calculate_work_required, check_proof_of_work, + input_data::{PoWGenerateBlockInputData, generate_pow_consensus_data_and_reward}, + mine, }, validator::validate_consensus, }; diff --git a/consensus/src/pos/block_sig.rs b/consensus/src/pos/block_sig.rs index 8069a2f07f..711d3b321c 100644 --- a/consensus/src/pos/block_sig.rs +++ b/consensus/src/pos/block_sig.rs @@ -15,8 +15,8 @@ use common::{ chain::{ - block::signed_block_header::{BlockHeaderSignature, SignedBlockHeader}, Block, Destination, + block::signed_block_header::{BlockHeaderSignature, SignedBlockHeader}, }, primitives::{Id, Idable}, }; @@ -43,7 +43,7 @@ pub fn check_block_signature( | Destination::PublicKeyHash(_) | Destination::ScriptHash(_) | Destination::ClassicMultisig(_) => { - return Err(BlockSignatureError::WrongDestination(header.get_id())) + return Err(BlockSignatureError::WrongDestination(header.get_id())); } Destination::PublicKey(pk) => pk, }; @@ -52,7 +52,7 @@ pub fn check_block_signature( let sig_data = match signature_in_header { BlockHeaderSignature::None => { - return Err(BlockSignatureError::BlockSignatureNotFound(header.get_id())) + return Err(BlockSignatureError::BlockSignatureNotFound(header.get_id())); } BlockHeaderSignature::HeaderSignature(sig_data) => sig_data, }; diff --git a/consensus/src/pos/effective_pool_balance.rs b/consensus/src/pos/effective_pool_balance.rs index 0bc13ecc21..dd1017cf04 100644 --- a/consensus/src/pos/effective_pool_balance.rs +++ b/consensus/src/pos/effective_pool_balance.rs @@ -14,8 +14,8 @@ // limitations under the License. use common::{ - primitives::{rational::Rational, Amount}, Uint256, + primitives::{Amount, rational::Rational}, }; use logging::log; use thiserror::Error; @@ -230,7 +230,7 @@ mod tests { use common::{chain::CoinUnit, primitives::Amount}; use randomness::RngExt; use rstest::rstest; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; fn effective_pool_balance_float_impl( pledge_amount: Amount, diff --git a/consensus/src/pos/error.rs b/consensus/src/pos/error.rs index ab4f69b550..016d5cd5c2 100644 --- a/consensus/src/pos/error.rs +++ b/consensus/src/pos/error.rs @@ -17,14 +17,14 @@ use thiserror::Error; use chainstate_types::pos_randomness::PoSRandomnessError; use common::{ - chain::{block::timestamp::BlockTimestamp, Block, PoolId}, - primitives::{Compact, Id}, UintConversionError, + chain::{Block, PoolId, block::timestamp::BlockTimestamp}, + primitives::{Compact, Id}, }; use crate::ChainstateError; -use super::{block_sig::BlockSignatureError, EffectivePoolBalanceError}; +use super::{EffectivePoolBalanceError, block_sig::BlockSignatureError}; #[derive(Error, Debug, PartialEq, Eq, Clone)] pub enum ConsensusPoSError { @@ -39,9 +39,7 @@ pub enum ConsensusPoSError { StakeKernelHashTooHigh, #[error("Epoch data not provided")] NoEpochData, - #[error( - "Stake block timestamp cannot be smaller than the kernel's (kernel: {0} < stake: {1})" - )] + #[error("Stake block timestamp cannot be smaller than the kernel's (kernel: {0} < stake: {1})")] TimestampViolation(BlockTimestamp, BlockTimestamp), #[error("Kernel inputs are empty")] NoKernel, diff --git a/consensus/src/pos/hash_check.rs b/consensus/src/pos/hash_check.rs index 260c2cf466..ca589fd31c 100644 --- a/consensus/src/pos/hash_check.rs +++ b/consensus/src/pos/hash_check.rs @@ -15,9 +15,9 @@ use chainstate_types::pos_randomness::PoSRandomness; use common::{ - chain::{block::timestamp::BlockTimestamp, config::EpochIndex, PoSConsensusVersion}, - primitives::Amount, Uint256, Uint512, + chain::{PoSConsensusVersion, block::timestamp::BlockTimestamp, config::EpochIndex}, + primitives::Amount, }; use crypto::vrf::{VRFPublicKey, VRFReturn}; use utils::ensure; diff --git a/consensus/src/pos/input_data.rs b/consensus/src/pos/input_data.rs index 233505d2d0..24b0dbac9c 100644 --- a/consensus/src/pos/input_data.rs +++ b/consensus/src/pos/input_data.rs @@ -14,30 +14,30 @@ // limitations under the License. use crate::{ - pos::{error::ConsensusPoSError, target::calculate_target_required_from_block_index}, ConsensusCreationError, + pos::{error::ConsensusPoSError, target::calculate_target_required_from_block_index}, }; use chainstate_types::{ - pos_randomness::PoSRandomness, vrf_tools::construct_transcript, BlockIndex, GenBlockIndex, + BlockIndex, GenBlockIndex, pos_randomness::PoSRandomness, vrf_tools::construct_transcript, }; use common::{ chain::{ + ChainConfig, Destination, PoSStatus, PoolId, TxInput, TxOutput, block::{ - consensus_data::PoSData, timestamp::BlockTimestamp, BlockReward, - BlockRewardTransactable, + BlockReward, BlockRewardTransactable, consensus_data::PoSData, + timestamp::BlockTimestamp, }, config::EpochIndex, signature::{ inputsig::{ - authorize_pubkey_spend::sign_public_key_spending, - standard_signature::StandardInputSignature, InputWitness, + InputWitness, authorize_pubkey_spend::sign_public_key_spending, + standard_signature::StandardInputSignature, }, sighash::{ input_commitments::make_sighash_input_commitments_for_kernel_input_utxos, sighashtype::SigHashType, signature_hash, }, }, - ChainConfig, Destination, PoSStatus, PoolId, TxInput, TxOutput, }, primitives::{Amount, BlockHeight}, }; diff --git a/consensus/src/pos/mod.rs b/consensus/src/pos/mod.rs index ac221ccdb5..2e1de27193 100644 --- a/consensus/src/pos/mod.rs +++ b/consensus/src/pos/mod.rs @@ -23,21 +23,21 @@ pub mod target; mod effective_pool_balance; use chainstate_types::{ - pos_randomness::PoSRandomness, vrf_tools::construct_transcript, BlockIndexHandle, - EpochStorageRead, GenBlockIndex, + BlockIndexHandle, EpochStorageRead, GenBlockIndex, pos_randomness::PoSRandomness, + vrf_tools::construct_transcript, }; use common::{ + Uint256, address::Address, chain::{ + ChainConfig, CoinUnit, PoSChainConfig, PoSStatus, TxOutput, block::{ - consensus_data::PoSData, signed_block_header::SignedBlockHeader, - timestamp::BlockTimestamp, BlockHeader, ConsensusData, + BlockHeader, ConsensusData, consensus_data::PoSData, + signed_block_header::SignedBlockHeader, timestamp::BlockTimestamp, }, config::EpochIndex, - ChainConfig, CoinUnit, PoSChainConfig, PoSStatus, TxOutput, }, primitives::{Amount, BlockHeight, Compact, Idable}, - Uint256, }; use crypto::vrf::{VRFPrivateKey, VRFPublicKey, VRFReturn}; use logging::log; @@ -47,12 +47,12 @@ use utils::ensure; use utxo::UtxosView; use crate::{ - pos::{block_sig::check_block_signature, error::ConsensusPoSError, kernel::get_kernel_output}, PoSFinalizeBlockInputData, + pos::{block_sig::check_block_signature, error::ConsensusPoSError, kernel::get_kernel_output}, }; pub use effective_pool_balance::{ - effective_pool_balance as calculate_effective_pool_balance, EffectivePoolBalanceError, + EffectivePoolBalanceError, effective_pool_balance as calculate_effective_pool_balance, }; pub use hash_check::check_pos_hash; @@ -182,7 +182,7 @@ where | TxOutput::CreateOrder(_) => { return Err(ConsensusPoSError::InvalidOutputTypeInStakeKernel( header.get_id(), - )) + )); } TxOutput::CreateStakePool(_, stake_pool) => stake_pool.staker().clone(), TxOutput::ProduceBlockFromStake(dest, _) => dest, diff --git a/consensus/src/pos/target.rs b/consensus/src/pos/target.rs index 9f2fdc79f6..91549757c9 100644 --- a/consensus/src/pos/target.rs +++ b/consensus/src/pos/target.rs @@ -17,12 +17,12 @@ use std::num::NonZeroU64; use chainstate_types::{BlockIndex, BlockIndexHandle, GenBlockIndex}; use common::{ + Uint256, Uint512, chain::{ - block::ConsensusData, ChainConfig, GenBlock, GenBlockId, PoSChainConfig, PoSStatus, - RequiredConsensus, + ChainConfig, GenBlock, GenBlockId, PoSChainConfig, PoSStatus, RequiredConsensus, + block::ConsensusData, }, primitives::{BlockDistance, BlockHeight, Compact, Id}, - Uint256, Uint512, }; use utils::ensure; @@ -194,7 +194,9 @@ where PoSStatus::Ongoing(_) => { /*do nothing*/ } }, RequiredConsensus::PoW(_) | RequiredConsensus::IgnoreConsensus => { - panic!("Prev block's consensus status must be PoS because we are in Ongoing PoS net version") + panic!( + "Prev block's consensus status must be PoS because we are in Ongoing PoS net version" + ) } }; @@ -233,17 +235,17 @@ mod tests { }; use common::{ chain::{ - block::{consensus_data::PoSData, timestamp::BlockTimestamp, BlockReward}, - config::Builder as ConfigBuilder, Block, ConsensusUpgrade, GenBlock, Genesis, NetUpgrades, PoSChainConfigBuilder, PoolId, + block::{BlockReward, consensus_data::PoSData, timestamp::BlockTimestamp}, + config::Builder as ConfigBuilder, }, - primitives::{per_thousand::PerThousand, Idable, H256}, + primitives::{H256, Idable, per_thousand::PerThousand}, }; - use crypto::vrf::{transcript::no_rng::VRFTranscript, VRFKeyKind, VRFPrivateKey}; + use crypto::vrf::{VRFKeyKind, VRFPrivateKey, transcript::no_rng::VRFTranscript}; use itertools::Itertools; use randomness::{CryptoRng, RngExt as _}; use rstest::rstest; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use super::*; @@ -918,9 +920,11 @@ mod tests { let mut tip_height = BlockHeight::one(); let pos_status = get_pos_status(&chain_config, tip_height.next_height()); - println!("Test settings:\n block_count_to_average_for_blocktime: {},\n difficulty_change_limit: {:?}", - pos_status.get_chain_config().block_count_to_average_for_blocktime(), - pos_status.get_chain_config().difficulty_change_limit()); + println!( + "Test settings:\n block_count_to_average_for_blocktime: {},\n difficulty_change_limit: {:?}", + pos_status.get_chain_config().block_count_to_average_for_blocktime(), + pos_status.get_chain_config().difficulty_change_limit() + ); for slot in 121..1_000_000 { let tip = block_index_handle.get_block_index_by_height(tip_height).unwrap(); diff --git a/consensus/src/pow/helpers.rs b/consensus/src/pow/helpers.rs index 4acd073749..cb00b68d11 100644 --- a/consensus/src/pow/helpers.rs +++ b/consensus/src/pow/helpers.rs @@ -17,9 +17,9 @@ use std::num::NonZeroU64; use chainstate_types::{BlockIndex, GenBlockIndex}; use common::{ + Uint256, chain::block::timestamp::BlockTimestamp, primitives::{BlockHeight, Compact}, - Uint256, }; use crate::pow::error::ConsensusPoWError; diff --git a/consensus/src/pow/input_data.rs b/consensus/src/pow/input_data.rs index 790eb16c66..7738d52dab 100644 --- a/consensus/src/pow/input_data.rs +++ b/consensus/src/pow/input_data.rs @@ -17,10 +17,10 @@ use crate::pow::{calculate_work_required, error::ConsensusPoWError}; use chainstate_types::{BlockIndex, GenBlockIndex}; use common::{ chain::{ - block::{consensus_data::PoWData, timestamp::BlockTimestamp, BlockReward}, + ChainConfig, Destination, PoWStatus, TxOutput, + block::{BlockReward, consensus_data::PoWData, timestamp::BlockTimestamp}, output_value::OutputValue, timelock::OutputTimeLock, - ChainConfig, Destination, PoWStatus, TxOutput, }, primitives::BlockHeight, }; diff --git a/consensus/src/pow/mod.rs b/consensus/src/pow/mod.rs index 3a982a50da..ff80dcf04a 100644 --- a/consensus/src/pow/mod.rs +++ b/consensus/src/pow/mod.rs @@ -15,7 +15,7 @@ pub use self::{ error::ConsensusPoWError, - work::{calculate_work_required, check_pow_consensus, check_proof_of_work, mine, MiningResult}, + work::{MiningResult, calculate_work_required, check_pow_consensus, check_proof_of_work, mine}, }; mod error; @@ -26,8 +26,8 @@ mod work; use std::{num::NonZeroU64, time::Duration}; use common::{ - chain::{ChainConfig, PoWChainConfig}, Uint256, + chain::{ChainConfig, PoWChainConfig}, }; struct PoW(PoWChainConfig); diff --git a/consensus/src/pow/work.rs b/consensus/src/pow/work.rs index 2784b82b0c..c517bb958d 100644 --- a/consensus/src/pow/work.rs +++ b/consensus/src/pow/work.rs @@ -19,23 +19,23 @@ use std::sync::Arc; use chainstate_types::{BlockIndex, BlockIndexHandle, GenBlockIndex}; use common::{ + Uint256, chain::{ + GenBlockId, PoWStatus, block::consensus_data::PoWData, - block::{timestamp::BlockTimestamp, BlockHeader, ConsensusData}, + block::{BlockHeader, ConsensusData, timestamp::BlockTimestamp}, config::ChainConfig, - GenBlockId, PoWStatus, }, - primitives::{BlockHeight, Compact, Idable, H256}, - Uint256, + primitives::{BlockHeight, Compact, H256, Idable}, }; use utils::atomics::RelaxedAtomicBool; use crate::{ get_ancestor_from_block_index_handle, pow::{ + PoW, error::ConsensusPoWError, helpers::{calculate_new_target, due_for_retarget, get_starting_block_time, special_rules}, - PoW, }, }; diff --git a/consensus/src/validator.rs b/consensus/src/validator.rs index 862e2b5914..abed33a3f7 100644 --- a/consensus/src/validator.rs +++ b/consensus/src/validator.rs @@ -16,9 +16,9 @@ use chainstate_types::{BlockIndexHandle, EpochStorageRead}; use common::{ chain::{ - block::{signed_block_header::SignedBlockHeader, BlockHeader, ConsensusData}, - config::ChainConfig, PoSStatus, PoWStatus, RequiredConsensus, + block::{BlockHeader, ConsensusData, signed_block_header::SignedBlockHeader}, + config::ChainConfig, }, primitives::Idable, }; diff --git a/crypto/src/ephemeral_e2e/mod.rs b/crypto/src/ephemeral_e2e/mod.rs index 3291e32cb1..a491695e6e 100644 --- a/crypto/src/ephemeral_e2e/mod.rs +++ b/crypto/src/ephemeral_e2e/mod.rs @@ -17,7 +17,7 @@ pub mod error; use zeroize::Zeroize; -use randomness::{adapters::Rng08Adapter, CryptoRng}; +use randomness::{CryptoRng, adapters::Rng08Adapter}; use serialization::{Decode, DecodeAll, Encode}; use crate::symkey; @@ -156,7 +156,7 @@ mod tests { use rstest::rstest; use randomness::RngExt as _; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use super::*; diff --git a/crypto/src/hash/internal.rs b/crypto/src/hash/internal.rs index 84466ed70b..4a154eb5f2 100644 --- a/crypto/src/hash/internal.rs +++ b/crypto/src/hash/internal.rs @@ -17,7 +17,7 @@ // but this saves us from adding digest manually to cargo // and managing a different version pub use blake2::digest::{ - generic_array::GenericArray, Digest, FixedOutputReset, OutputSizeUser, Reset, Update, + Digest, FixedOutputReset, OutputSizeUser, Reset, Update, generic_array::GenericArray, }; pub fn hash>( diff --git a/crypto/src/hash/mod.rs b/crypto/src/hash/mod.rs index 78afa63750..3677f85d7c 100644 --- a/crypto/src/hash/mod.rs +++ b/crypto/src/hash/mod.rs @@ -15,7 +15,7 @@ mod internal; -use generic_array::{sequence::Split, typenum, ArrayLength, GenericArray}; +use generic_array::{ArrayLength, GenericArray, sequence::Split, typenum}; use internal::InternalStreamHasher; pub trait Hasher { diff --git a/crypto/src/kdf/mod.rs b/crypto/src/kdf/mod.rs index 240a2b4d71..1e85f7827c 100644 --- a/crypto/src/kdf/mod.rs +++ b/crypto/src/kdf/mod.rs @@ -178,7 +178,7 @@ pub fn verify_password( #[cfg(test)] pub mod test { use rstest::rstest; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use super::*; @@ -214,26 +214,32 @@ pub mod test { assert!( verify_password(password, &password_hash, SliceEqualityCheckMethod::Normal).unwrap() ); - assert!(verify_password( - password, - &password_hash, - SliceEqualityCheckMethod::TimingResistant - ) - .unwrap()); + assert!( + verify_password( + password, + &password_hash, + SliceEqualityCheckMethod::TimingResistant + ) + .unwrap() + ); let wrong_password = b"RandomWrong____password?"; - assert!(!verify_password( - wrong_password, - &password_hash, - SliceEqualityCheckMethod::Normal - ) - .unwrap()); - assert!(!verify_password( - wrong_password, - &password_hash, - SliceEqualityCheckMethod::TimingResistant - ) - .unwrap()); + assert!( + !verify_password( + wrong_password, + &password_hash, + SliceEqualityCheckMethod::Normal + ) + .unwrap() + ); + assert!( + !verify_password( + wrong_password, + &password_hash, + SliceEqualityCheckMethod::TimingResistant + ) + .unwrap() + ); } #[rstest] @@ -256,12 +262,14 @@ pub mod test { assert!( verify_password(password, &password_hash, SliceEqualityCheckMethod::Normal).unwrap() ); - assert!(verify_password( - password, - &password_hash, - SliceEqualityCheckMethod::TimingResistant - ) - .unwrap()); + assert!( + verify_password( + password, + &password_hash, + SliceEqualityCheckMethod::TimingResistant + ) + .unwrap() + ); let challenge = password_hash.into_challenge(); diff --git a/crypto/src/key/extended.rs b/crypto/src/key/extended.rs index d9e5f0baf2..8185f7bcd0 100644 --- a/crypto/src/key/extended.rs +++ b/crypto/src/key/extended.rs @@ -23,7 +23,7 @@ use crate::key::secp256k1::extended_keys::{ Secp256k1ExtendedPrivateKey, Secp256k1ExtendedPublicKey, }; use crate::key::{PrivateKey, PublicKey}; -use randomness::{make_true_rng, CryptoRng}; +use randomness::{CryptoRng, make_true_rng}; use super::hdkd::chain_code::ChainCode; @@ -192,7 +192,7 @@ mod test { use rstest::rstest; use randomness::RngExt as _; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use crate::key::hdkd::derivation_path::DerivationPath; diff --git a/crypto/src/key/hdkd/child_number.rs b/crypto/src/key/hdkd/child_number.rs index bb9197f778..d5dee3c542 100644 --- a/crypto/src/key/hdkd/child_number.rs +++ b/crypto/src/key/hdkd/child_number.rs @@ -130,8 +130,8 @@ mod test { use randomness::Rng; use rstest::rstest; use std::str::FromStr; - use test_utils::random::make_seedable_rng; use test_utils::random::Seed; + use test_utils::random::make_seedable_rng; fn examine_child_number(num: ChildNumber, encoded_num: u32, is_hardened: bool) { assert_eq!(num.is_normal(), !is_hardened); diff --git a/crypto/src/key/hdkd/derivation_path.rs b/crypto/src/key/hdkd/derivation_path.rs index e999e6a806..2f8ce2c84e 100644 --- a/crypto/src/key/hdkd/derivation_path.rs +++ b/crypto/src/key/hdkd/derivation_path.rs @@ -140,7 +140,7 @@ mod tests { use super::*; use randomness::Rng; use rstest::rstest; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use test_utils::{assert_encoded_eq, decode_from_hex}; #[rstest] diff --git a/crypto/src/key/mod.rs b/crypto/src/key/mod.rs index c0ef4fc508..0985f4d44b 100644 --- a/crypto/src/key/mod.rs +++ b/crypto/src/key/mod.rs @@ -20,12 +20,12 @@ mod key_holder; pub mod secp256k1; pub mod signature; -use randomness::{make_true_rng, CryptoRng}; -use serialization::{hex_encoded::HexEncoded, Decode, Encode}; +use randomness::{CryptoRng, make_true_rng}; +use serialization::{Decode, Encode, hex_encoded::HexEncoded}; use crate::key::{ - secp256k1::{Secp256k1PrivateKey, Secp256k1PublicKey}, Signature::Secp256k1Schnorr, + secp256k1::{Secp256k1PrivateKey, Secp256k1PublicKey}, }; use self::key_holder::{PrivateKeyHolder, PublicKeyHolder}; @@ -176,7 +176,7 @@ mod test { use rstest::rstest; use randomness::RngExt as _; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use super::*; diff --git a/crypto/src/key/secp256k1/extended_keys.rs b/crypto/src/key/secp256k1/extended_keys.rs index 00acafb5f9..aba0647734 100644 --- a/crypto/src/key/secp256k1/extended_keys.rs +++ b/crypto/src/key/secp256k1/extended_keys.rs @@ -19,7 +19,7 @@ use hmac::{Hmac, Mac}; use secp256k1; use sha2::Sha512; -use randomness::{adapters::Rng08Adapter, CryptoRng}; +use randomness::{CryptoRng, adapters::Rng08Adapter}; use serialization::{Decode, Encode}; use crate::{ @@ -359,8 +359,14 @@ mod test { Secp256k1ExtendedPrivateKey::new_master(&mnemonic.to_seed_normalized("")).unwrap(); let master_pub_key = Secp256k1ExtendedPublicKey::from_private_key(&master_key); assert_eq!(master_key.chain_code, master_pub_key.chain_code); - assert_encoded_eq(&master_key, "007923408dadd3c7b56eed15567707ae5e5dca089de972e07f3b860450e2a3b70e1837c1be8e2995ec11cda2b066151be2cfb48adf9e47b151d46adab3a21cdf67"); - assert_encoded_eq(&master_pub_key, "007923408dadd3c7b56eed15567707ae5e5dca089de972e07f3b860450e2a3b70e03d902f35f560e0470c63313c7369168d9d7df2d49bf295fd9fb7cb109ccee0494"); + assert_encoded_eq( + &master_key, + "007923408dadd3c7b56eed15567707ae5e5dca089de972e07f3b860450e2a3b70e1837c1be8e2995ec11cda2b066151be2cfb48adf9e47b151d46adab3a21cdf67", + ); + assert_encoded_eq( + &master_pub_key, + "007923408dadd3c7b56eed15567707ae5e5dca089de972e07f3b860450e2a3b70e03d902f35f560e0470c63313c7369168d9d7df2d49bf295fd9fb7cb109ccee0494", + ); let path = DerivationPath::from_str(path).unwrap(); assert_encoded_eq(&path, path_encoded); diff --git a/crypto/src/key/secp256k1/mod.rs b/crypto/src/key/secp256k1/mod.rs index 319e2eb486..5f08cf2d55 100644 --- a/crypto/src/key/secp256k1/mod.rs +++ b/crypto/src/key/secp256k1/mod.rs @@ -18,7 +18,7 @@ pub mod extended_keys; use secp256k1; use zeroize::Zeroize; -use randomness::{adapters::Rng08Adapter, CryptoRng}; +use randomness::{CryptoRng, adapters::Rng08Adapter}; use serialization::{Decode, Encode}; use crate::{ @@ -210,7 +210,7 @@ mod test { use randomness::RngExt as _; use serialization::{DecodeAll, Encode}; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use super::*; @@ -350,19 +350,84 @@ mod test { } #[rstest] - #[case("02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9", "0000000000000000000000000000000000000000000000000000000000000000", "e907831f80848d1069a5371b402410364bdf1c5f8307b0084c55f1ce2dca821525f66a4a85ea8b71e482a74f382d2ce5ebeee8fdb2172f477df4900d310536c0", true)] - #[case("02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", "6896bd60eeae296db48a229ff71dfe071bde413e6d43f917dc8dcf8c78de33418906d11ac976abccb20b091292bff4ea897efcb639ea871cfa95f6de339e4b0a", true)] - #[case("02dd308afec5777e13121fa72b9cc1b7cc0139715309b086c960e18fd969774eb8", "7e2d58d8b3bcdf1abadec7829054f90dda9805aab56c77333024b9d0a508b75c", "5831aaeed7b44bb74e5eab94ba9d4294c49bcf2a60728d8b4c200f50dd313c1bab745879a5ad954a72c45a91c3a51d3c7adea98d82f8481e0e1e03674a6f3fb7", true)] - #[case("0325d1dff95105f5253c4022f628a996ad3a0d95fbf21d468a1b33f8c160d8f517", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "7eb0509757e246f19449885651611cb965ecc1a187dd51b64fda1edc9637d5ec97582b9cb13db3933705b32ba982af5af25fd78881ebb32771fc5922efc66ea3", true)] - #[case("02d69c3509bb99e412e68b0fe8544e72837dfa30746d8be2aa65975f29d22dc7b9", "4df3c3f68fcc83b27e9d42c90431a72499f17875c81a599b566c9889b9696703", "00000000000000000000003b78ce563f89a0ed9414f5aa28ad0d96d6795f9c6376afb1548af603b3eb45c9f8207dee1060cb71c04e80f593060b07d28308d7f4", true)] - #[case("02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", "fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a14602975563cc27944640ac607cd107ae10923d9ef7a73c643e166be5ebeafa34b1ac553e2", false)] - #[case("02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", "1fa62e331edbc21c394792d2ab1100a7b432b013df3f6ff4f99fcb33e0e1515f28890b3edb6e7189b630448b515ce4f8622a954cfe545735aaea5134fccdb2bd", false)] - #[case("02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", "6cff5c3ba86c69ea4b7376f31a9bcb4f74c1976089b2d9963da2e5543e177769961764b3aa9b2ffcb6ef947b6887a226e8d7c93e00c5ed0c1834ff0d0c2e6da6", false)] - #[case("02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", "0000000000000000000000000000000000000000000000000000000000000000123dda8328af9c23a94c1feecfd123ba4fb73476f0d594dcb65c6425bd186051", false)] - #[case("02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", "00000000000000000000000000000000000000000000000000000000000000017615fbaf5ae28864013c099742deadb4dba87f11ac6754f93780d5a1837cf197", false)] - #[case("02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", "4a298dacae57395a15d0795ddbfd1dcb564da82b0f269bc70a74f8220429ba1d69e89b4c5564d00349106b8497785dd7d1d713a8ae82b32fa79d5f7fc407d39b", false)] - #[case("02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f69e89b4c5564d00349106b8497785dd7d1d713a8ae82b32fa79d5f7fc407d39b", false)] - #[case("02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", "6cff5c3ba86c69ea4b7376f31a9bcb4f74c1976089b2d9963da2e5543e177769fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", false)] + #[case( + "02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9", + "0000000000000000000000000000000000000000000000000000000000000000", + "e907831f80848d1069a5371b402410364bdf1c5f8307b0084c55f1ce2dca821525f66a4a85ea8b71e482a74f382d2ce5ebeee8fdb2172f477df4900d310536c0", + true + )] + #[case( + "02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", + "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", + "6896bd60eeae296db48a229ff71dfe071bde413e6d43f917dc8dcf8c78de33418906d11ac976abccb20b091292bff4ea897efcb639ea871cfa95f6de339e4b0a", + true + )] + #[case( + "02dd308afec5777e13121fa72b9cc1b7cc0139715309b086c960e18fd969774eb8", + "7e2d58d8b3bcdf1abadec7829054f90dda9805aab56c77333024b9d0a508b75c", + "5831aaeed7b44bb74e5eab94ba9d4294c49bcf2a60728d8b4c200f50dd313c1bab745879a5ad954a72c45a91c3a51d3c7adea98d82f8481e0e1e03674a6f3fb7", + true + )] + #[case( + "0325d1dff95105f5253c4022f628a996ad3a0d95fbf21d468a1b33f8c160d8f517", + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + "7eb0509757e246f19449885651611cb965ecc1a187dd51b64fda1edc9637d5ec97582b9cb13db3933705b32ba982af5af25fd78881ebb32771fc5922efc66ea3", + true + )] + #[case( + "02d69c3509bb99e412e68b0fe8544e72837dfa30746d8be2aa65975f29d22dc7b9", + "4df3c3f68fcc83b27e9d42c90431a72499f17875c81a599b566c9889b9696703", + "00000000000000000000003b78ce563f89a0ed9414f5aa28ad0d96d6795f9c6376afb1548af603b3eb45c9f8207dee1060cb71c04e80f593060b07d28308d7f4", + true + )] + #[case( + "02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", + "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", + "fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a14602975563cc27944640ac607cd107ae10923d9ef7a73c643e166be5ebeafa34b1ac553e2", + false + )] + #[case( + "02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", + "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", + "1fa62e331edbc21c394792d2ab1100a7b432b013df3f6ff4f99fcb33e0e1515f28890b3edb6e7189b630448b515ce4f8622a954cfe545735aaea5134fccdb2bd", + false + )] + #[case( + "02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", + "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", + "6cff5c3ba86c69ea4b7376f31a9bcb4f74c1976089b2d9963da2e5543e177769961764b3aa9b2ffcb6ef947b6887a226e8d7c93e00c5ed0c1834ff0d0c2e6da6", + false + )] + #[case( + "02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", + "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", + "0000000000000000000000000000000000000000000000000000000000000000123dda8328af9c23a94c1feecfd123ba4fb73476f0d594dcb65c6425bd186051", + false + )] + #[case( + "02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", + "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", + "00000000000000000000000000000000000000000000000000000000000000017615fbaf5ae28864013c099742deadb4dba87f11ac6754f93780d5a1837cf197", + false + )] + #[case( + "02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", + "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", + "4a298dacae57395a15d0795ddbfd1dcb564da82b0f269bc70a74f8220429ba1d69e89b4c5564d00349106b8497785dd7d1d713a8ae82b32fa79d5f7fc407d39b", + false + )] + #[case( + "02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", + "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", + "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f69e89b4c5564d00349106b8497785dd7d1d713a8ae82b32fa79d5f7fc407d39b", + false + )] + #[case( + "02dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659", + "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89", + "6cff5c3ba86c69ea4b7376f31a9bcb4f74c1976089b2d9963da2e5543e177769fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", + false + )] fn signature_verification( #[case] pk: &str, #[case] msg_hash: &str, diff --git a/crypto/src/key/signature/mod.rs b/crypto/src/key/signature/mod.rs index 366fc0f646..40265d2e0e 100644 --- a/crypto/src/key/signature/mod.rs +++ b/crypto/src/key/signature/mod.rs @@ -17,7 +17,7 @@ use secp256k1; use std::io::BufWriter; use num_derive::FromPrimitive; -use serialization::{hex_encoded::HexEncoded, Decode, DecodeAll, Encode}; +use serialization::{Decode, DecodeAll, Encode, hex_encoded::HexEncoded}; use super::SignatureError; @@ -111,8 +111,8 @@ mod test { use crate::key::{KeyKind, PrivateKey, PublicKey}; use hex::FromHex; use rstest::rstest; - use test_utils::random::make_seedable_rng; use test_utils::random::Seed; + use test_utils::random::make_seedable_rng; #[rstest] #[trace] diff --git a/crypto/src/util/eq.rs b/crypto/src/util/eq.rs index 7ce3d249e2..1c52dd4c6d 100644 --- a/crypto/src/util/eq.rs +++ b/crypto/src/util/eq.rs @@ -52,7 +52,7 @@ pub mod test { use rstest::rstest; use randomness::RngExt; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use super::*; diff --git a/crypto/src/util/mod.rs b/crypto/src/util/mod.rs index c538d2e938..2627632316 100644 --- a/crypto/src/util/mod.rs +++ b/crypto/src/util/mod.rs @@ -13,13 +13,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -use generic_array::{sequence::Split, typenum::U32, GenericArray}; +use generic_array::{GenericArray, sequence::Split, typenum::U32}; use hmac::{Hmac, Mac}; use sha2::Sha512; use zeroize::Zeroize; use crate::key::hdkd::{ - chain_code::{ChainCode, CHAINCODE_LENGTH}, + chain_code::{CHAINCODE_LENGTH, ChainCode}, derivable::DerivationError, }; @@ -60,7 +60,7 @@ mod test { use super::*; use randomness::RngExt; use rstest::rstest; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; #[rstest] #[trace] diff --git a/crypto/src/vrf/mod.rs b/crypto/src/vrf/mod.rs index fd4ee98f2f..4de87f2fcc 100644 --- a/crypto/src/vrf/mod.rs +++ b/crypto/src/vrf/mod.rs @@ -16,8 +16,8 @@ use hmac::{Hmac, Mac}; use sha2::Sha512; -use randomness::{make_true_rng, CryptoRng}; -use serialization::{hex_encoded::HexEncoded, Decode, Encode}; +use randomness::{CryptoRng, make_true_rng}; +use serialization::{Decode, Encode, hex_encoded::HexEncoded}; use crate::{ key::hdkd::{ @@ -341,8 +341,8 @@ mod tests { use hex::FromHex; use rstest::rstest; use serialization::DecodeAll; - use test_utils::random::make_seedable_rng; use test_utils::random::Seed; + use test_utils::random::make_seedable_rng; use self::transcript::no_rng::VRFTranscript; diff --git a/crypto/src/vrf/schnorrkel/data.rs b/crypto/src/vrf/schnorrkel/data.rs index 92c95fed7c..9c7b23f4ca 100644 --- a/crypto/src/vrf/schnorrkel/data.rs +++ b/crypto/src/vrf/schnorrkel/data.rs @@ -15,12 +15,12 @@ use generic_array::{ArrayLength, GenericArray}; use schnorrkel::{ - vrf::{VRFInOut, VRFPreOut, VRFProof}, PublicKey, + vrf::{VRFInOut, VRFPreOut, VRFProof}, }; -use serialization::{hex_encoded::HexEncoded, Decode, Encode}; +use serialization::{Decode, Encode, hex_encoded::HexEncoded}; -use crate::vrf::{transcript::traits::SignableTranscript, VRFError, VRFPublicKey}; +use crate::vrf::{VRFError, VRFPublicKey, transcript::traits::SignableTranscript}; const VRF_OUTPUT_LABEL: &[u8] = b"MintlayerVRFOutput!"; @@ -148,9 +148,9 @@ impl SchnorrkelVRFReturn { #[cfg(test)] mod tests { use hex::FromHex; - use schnorrkel::{signing_context, Keypair, PublicKey, SecretKey}; + use schnorrkel::{Keypair, PublicKey, SecretKey, signing_context}; - use randomness::{adapters::Rng08Adapter, make_pseudo_rng, make_true_rng, RngExt as _}; + use randomness::{RngExt as _, adapters::Rng08Adapter, make_pseudo_rng, make_true_rng}; use serialization::{DecodeAll, Encode}; use super::*; diff --git a/crypto/src/vrf/schnorrkel/mod.rs b/crypto/src/vrf/schnorrkel/mod.rs index 221170a019..c7f13ba6ed 100644 --- a/crypto/src/vrf/schnorrkel/mod.rs +++ b/crypto/src/vrf/schnorrkel/mod.rs @@ -13,16 +13,16 @@ // See the License for the specific language governing permissions and // limitations under the License. -use schnorrkel::{derive::Derivation, Keypair}; +use schnorrkel::{Keypair, derive::Derivation}; -use randomness::{adapters::Rng08Adapter, CryptoRng}; +use randomness::{CryptoRng, adapters::Rng08Adapter}; use serialization::{Decode, Encode}; use crate::key::hdkd::{ chain_code::ChainCode, child_number::ChildNumber, derivable::DerivationError, }; -use super::{primitives::VRFReturn, transcript::traits::SignableTranscript, VRFError}; +use super::{VRFError, primitives::VRFReturn, transcript::traits::SignableTranscript}; use self::data::SchnorrkelVRFReturn; @@ -216,10 +216,10 @@ impl Decode for SchnorrkelPrivateKey { mod tests { use super::*; use hex::FromHex; - use randomness::{make_true_rng, Rng}; - use schnorrkel::{signing_context, Keypair}; + use randomness::{Rng, make_true_rng}; + use schnorrkel::{Keypair, signing_context}; use serialization::{DecodeAll, Encode}; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; #[test] fn key_serialization() { @@ -310,9 +310,18 @@ mod tests { fn vrf_from_bytes() { // Verify that [SchnorrkelPrivateKey::new_from_bytes] returns the same result to prevent future regressions let keys = [ - ("783231456c206e78989c15741764d6c4e7b96e1bac4ea322bfb5df5676876717", "a9246f2ac3b7c3c46bfd903ce077c6033148a13692ccb33a732d9c3616d93a0ca73efa91903bfe5eea90e0d6e684f6e444218baa403aece75c3036a322e845a2"), - ("c247d6edd1b5e32c0750eeb256ef63186c1a7cebf1729249ae31f65f959aa1ae", "3e16bf35d133fd5ae2b59838cc29847aa040f76f37a0445405bcb9238e3ae1049354882edf8916041d23c2d33cbed8e537a23da5bbf5a432f0c1737253f5c188"), - ("440acd9f2e1d3e197f745d11c03cd9b805acfb5c5d5f4dfe0d8a55d1d29efa42", "956c30c899065b7b3e085fe50f6431bce7adcc5dbcc114e7c6ad73c148b30c0f85bc02f31c809a173929dec21c8c2380bdc5fe5cfa37f1a6b8b6af9c0ae95515"), + ( + "783231456c206e78989c15741764d6c4e7b96e1bac4ea322bfb5df5676876717", + "a9246f2ac3b7c3c46bfd903ce077c6033148a13692ccb33a732d9c3616d93a0ca73efa91903bfe5eea90e0d6e684f6e444218baa403aece75c3036a322e845a2", + ), + ( + "c247d6edd1b5e32c0750eeb256ef63186c1a7cebf1729249ae31f65f959aa1ae", + "3e16bf35d133fd5ae2b59838cc29847aa040f76f37a0445405bcb9238e3ae1049354882edf8916041d23c2d33cbed8e537a23da5bbf5a432f0c1737253f5c188", + ), + ( + "440acd9f2e1d3e197f745d11c03cd9b805acfb5c5d5f4dfe0d8a55d1d29efa42", + "956c30c899065b7b3e085fe50f6431bce7adcc5dbcc114e7c6ad73c148b30c0f85bc02f31c809a173929dec21c8c2380bdc5fe5cfa37f1a6b8b6af9c0ae95515", + ), ]; for (bytes_hex, expected) in keys { let bytes = hex::decode(bytes_hex).unwrap(); diff --git a/crypto/src/vrf/transcript/mod.rs b/crypto/src/vrf/transcript/mod.rs index 230d500259..d1b57f6847 100644 --- a/crypto/src/vrf/transcript/mod.rs +++ b/crypto/src/vrf/transcript/mod.rs @@ -22,7 +22,7 @@ mod tests { use rstest::rstest; use randomness::adapters::Rng08Adapter; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use crate::vrf::transcript::with_rng::VRFTranscriptWithRng; diff --git a/crypto/src/vrf/transcript/with_rng.rs b/crypto/src/vrf/transcript/with_rng.rs index 823108fc26..8c4d4221f2 100644 --- a/crypto/src/vrf/transcript/with_rng.rs +++ b/crypto/src/vrf/transcript/with_rng.rs @@ -15,7 +15,7 @@ use std::sync::{Arc, Mutex}; -use randomness::{adapters::Rng08Adapter, CryptoRng}; +use randomness::{CryptoRng, adapters::Rng08Adapter}; use super::{no_rng::VRFTranscript, traits::SignableTranscript}; @@ -88,7 +88,7 @@ mod tests { use rstest::rstest; use randomness::SeedableRng; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use super::*; diff --git a/dns-server/src/crawler_p2p/crawler/address_data.rs b/dns-server/src/crawler_p2p/crawler/address_data.rs index 6ec572b13e..0bd74dcc6e 100644 --- a/dns-server/src/crawler_p2p/crawler/address_data.rs +++ b/dns-server/src/crawler_p2p/crawler/address_data.rs @@ -20,7 +20,7 @@ use common::{ primitives::{ semver::SemVer, time::Time, - user_agent::{mintlayer_core_user_agent, UserAgent}, + user_agent::{UserAgent, mintlayer_core_user_agent}, }, }; use serialization::{Decode, Encode}; diff --git a/dns-server/src/crawler_p2p/crawler/mod.rs b/dns-server/src/crawler_p2p/crawler/mod.rs index 0dfd83d6cb..e01671cc79 100644 --- a/dns-server/src/crawler_p2p/crawler/mod.rs +++ b/dns-server/src/crawler_p2p/crawler/mod.rs @@ -29,7 +29,7 @@ pub mod address_data; use std::{ - collections::{btree_map::Entry, BTreeMap, BTreeSet}, + collections::{BTreeMap, BTreeSet, btree_map::Entry}, sync::Arc, time::Duration, }; @@ -44,7 +44,7 @@ use p2p::{ types::{bannable_address::BannableAddress, peer_id::PeerId, socket_address::SocketAddress}, utils::rate_limiter::RateLimiter, }; -use randomness::{seq::IteratorRandom, Rng}; +use randomness::{Rng, seq::IteratorRandom}; use utils::make_config_setting; use crate::crawler_p2p::crawler::address_data::{AddressStateTransitionTo, SoftwareInfo}; diff --git a/dns-server/src/crawler_p2p/crawler/tests/mock_crawler.rs b/dns-server/src/crawler_p2p/crawler/tests/mock_crawler.rs index 73a446817e..092d97e51d 100644 --- a/dns-server/src/crawler_p2p/crawler/tests/mock_crawler.rs +++ b/dns-server/src/crawler_p2p/crawler/tests/mock_crawler.rs @@ -26,7 +26,7 @@ use p2p::types::{ use randomness::Rng; use crate::crawler_p2p::{ - crawler::{address_data::AddressState, Crawler, CrawlerCommand, CrawlerConfig, CrawlerEvent}, + crawler::{Crawler, CrawlerCommand, CrawlerConfig, CrawlerEvent, address_data::AddressState}, crawler_manager::storage::AddressInfo, }; diff --git a/dns-server/src/crawler_p2p/crawler/tests/mod.rs b/dns-server/src/crawler_p2p/crawler/tests/mod.rs index 72b21badc7..9a465c84a3 100644 --- a/dns-server/src/crawler_p2p/crawler/tests/mod.rs +++ b/dns-server/src/crawler_p2p/crawler/tests/mod.rs @@ -23,7 +23,7 @@ use std::{ use chainstate::ban_score::BanScore; use common::{ - chain::{config::MagicBytes, ChainConfig}, + chain::{ChainConfig, config::MagicBytes}, primitives::{time::Time, user_agent::mintlayer_core_user_agent}, }; use p2p::{ @@ -34,18 +34,18 @@ use p2p::{ types::{peer_id::PeerId, socket_address::SocketAddress}, }; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use randomness::{ - seq::{IndexedRandom as _, IteratorRandom}, RngExt as _, + seq::{IndexedRandom as _, IteratorRandom}, }; use mock_crawler::test_crawler; use crate::crawler_p2p::{crawler::CrawlerEvent, crawler_manager::storage::AddressInfo}; -use super::{address_data::SoftwareInfo, CrawlerConfig}; +use super::{CrawlerConfig, address_data::SoftwareInfo}; #[rstest] #[trace] diff --git a/dns-server/src/crawler_p2p/crawler_manager/mod.rs b/dns-server/src/crawler_p2p/crawler_manager/mod.rs index 485c1b771a..9cffa54f42 100644 --- a/dns-server/src/crawler_p2p/crawler_manager/mod.rs +++ b/dns-server/src/crawler_p2p/crawler_manager/mod.rs @@ -34,16 +34,16 @@ use p2p::{ PingResponse, }, net::{ - types::{ConnectivityEvent, PeerManagerMessageExt, SyncingEvent}, ConnectivityService, NetworkingService, SyncingEventReceiver, + types::{ConnectivityEvent, PeerManagerMessageExt, SyncingEvent}, }, peer_manager::{ ip_or_socket_address_to_peer_address, - peerdb_common::{storage::update_db, StorageVersion, TransactionRo, TransactionRw}, + peerdb_common::{StorageVersion, TransactionRo, TransactionRw, storage::update_db}, }, types::{ - bannable_address::BannableAddress, peer_address::PeerAddress, peer_id::PeerId, - socket_address::SocketAddress, IsGlobalIp, + IsGlobalIp, bannable_address::BannableAddress, peer_address::PeerAddress, peer_id::PeerId, + socket_address::SocketAddress, }, }; use randomness::make_pseudo_rng; diff --git a/dns-server/src/crawler_p2p/crawler_manager/storage.rs b/dns-server/src/crawler_p2p/crawler_manager/storage.rs index 696917c3ab..adb61e397b 100644 --- a/dns-server/src/crawler_p2p/crawler_manager/storage.rs +++ b/dns-server/src/crawler_p2p/crawler_manager/storage.rs @@ -24,7 +24,7 @@ use serialization::{Decode, Encode}; use crate::{crawler_p2p::crawler::address_data::SoftwareInfo, error::DnsServerError}; -use super::{storage_impl::DnsServerStorageImpl, CURRENT_STORAGE_VERSION}; +use super::{CURRENT_STORAGE_VERSION, storage_impl::DnsServerStorageImpl}; #[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] pub struct AddressInfo { diff --git a/dns-server/src/crawler_p2p/crawler_manager/storage_impl.rs b/dns-server/src/crawler_p2p/crawler_manager/storage_impl.rs index b7ecfc0bce..b930eaf348 100644 --- a/dns-server/src/crawler_p2p/crawler_manager/storage_impl.rs +++ b/dns-server/src/crawler_p2p/crawler_manager/storage_impl.rs @@ -21,12 +21,12 @@ use super::storage::{AddressInfo, DnsServerStorage, DnsServerStorageRead, DnsSer use common::primitives::time::Time; use p2p::{ peer_manager::peerdb_common::{ - storage_impl::{StorageImpl, StorageTxRo, StorageTxRw}, StorageVersion, + storage_impl::{StorageImpl, StorageTxRo, StorageTxRw}, }, types::{bannable_address::BannableAddress, socket_address::SocketAddress}, }; -use serialization::{encoded::Encoded, DecodeAll, Encode}; +use serialization::{DecodeAll, Encode, encoded::Encoded}; use storage::MakeMapRef; type ValueId = u32; diff --git a/dns-server/src/crawler_p2p/crawler_manager/tests/mock_manager.rs b/dns-server/src/crawler_p2p/crawler_manager/tests/mock_manager.rs index 45adab2e14..adae8515cb 100644 --- a/dns-server/src/crawler_p2p/crawler_manager/tests/mock_manager.rs +++ b/dns-server/src/crawler_p2p/crawler_manager/tests/mock_manager.rs @@ -32,20 +32,20 @@ use tokio::{ use common::{chain::ChainConfig, primitives::time::Time, time_getter::TimeGetter}; use networking::test_helpers::TestAddressMaker; use p2p::{ + P2pEventHandler, config::{NodeType, P2pConfig}, disconnection_reason::DisconnectionReason, error::{DialError, P2pError}, message::{AnnounceAddrRequest, PeerManagerMessage}, net::{ - types::{ConnectivityEvent, PeerInfo, SyncingEvent}, ConnectivityService, NetworkingService, SyncingEventReceiver, + types::{ConnectivityEvent, PeerInfo, SyncingEvent}, }, test_helpers::TEST_PROTOCOL_VERSION, types::{ bannable_address::BannableAddress, peer_id::PeerId, services::Services, socket_address::SocketAddress, }, - P2pEventHandler, }; use randomness::Rng; use test_utils::BasicTestTimeGetter; @@ -54,10 +54,10 @@ use utils_networking::IpOrSocketAddress; use crate::{ crawler_p2p::{ - crawler::{address_data::SoftwareInfo, CrawlerConfig}, + crawler::{CrawlerConfig, address_data::SoftwareInfo}, crawler_manager::{ - storage::DnsServerStorage, storage_impl::DnsServerStorageImpl, CrawlerManager, - CrawlerManagerConfig, + CrawlerManager, CrawlerManagerConfig, storage::DnsServerStorage, + storage_impl::DnsServerStorageImpl, }, }, dns_server::DnsServerCommand, diff --git a/dns-server/src/crawler_p2p/crawler_manager/tests/mod.rs b/dns-server/src/crawler_p2p/crawler_manager/tests/mod.rs index fe959f62e4..7ce7791e6b 100644 --- a/dns-server/src/crawler_p2p/crawler_manager/tests/mod.rs +++ b/dns-server/src/crawler_p2p/crawler_manager/tests/mod.rs @@ -25,14 +25,14 @@ use p2p::{ }; use p2p_test_utils::{expect_no_recv, expect_recv}; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use crate::{ crawler_p2p::{ - crawler::{address_data::SoftwareInfo, BanDuration, BanThreshold}, + crawler::{BanDuration, BanThreshold, address_data::SoftwareInfo}, crawler_manager::tests::mock_manager::{ - advance_time, assert_banned_addresses, assert_known_addresses, test_crawler, - ErraticNodeConnectError, + ErraticNodeConnectError, advance_time, assert_banned_addresses, assert_known_addresses, + test_crawler, }, }, dns_server::DnsServerCommand, diff --git a/dns-server/src/dns_server/mod.rs b/dns-server/src/dns_server/mod.rs index 96c1591359..bf1e4a916c 100644 --- a/dns-server/src/dns_server/mod.rs +++ b/dns-server/src/dns_server/mod.rs @@ -25,25 +25,25 @@ use futures::never::Never; use hickory_client::{ proto::rr::{LowerName, RrKey}, rr::{ - rdata::{NS, SOA}, Name, RData, RecordSet, RecordType, + rdata::{NS, SOA}, }, }; use hickory_server::{ + ServerFuture, authority::{ AuthLookup, Authority, Catalog, LookupError, LookupOptions, MessageRequest, UpdateResult, ZoneType, }, server::RequestInfo, store::in_memory::InMemoryAuthority, - ServerFuture, }; use itertools::Itertools; use tokio::{net::UdpSocket, sync::mpsc}; use common::{chain::ChainConfig, primitives::per_thousand::PerThousand}; use logging::log; -use randomness::{make_pseudo_rng, IndexedRandom as _, Rng, SliceRandom as _}; +use randomness::{IndexedRandom as _, Rng, SliceRandom as _, make_pseudo_rng}; use utils::{atomics::RelaxedAtomicU32, make_config_setting, tokio_spawn}; use crate::{ diff --git a/dns-server/src/dns_server/tests.rs b/dns-server/src/dns_server/tests.rs index 31e10a5c56..57b8f2474f 100644 --- a/dns-server/src/dns_server/tests.rs +++ b/dns-server/src/dns_server/tests.rs @@ -35,7 +35,7 @@ use test_utils::{assert_matches_return_val, merge_btree_maps, random::Seed}; use crate::{ crawler_p2p::crawler::address_data::SoftwareInfo, - dns_server::{handle_command, AuthorityImpl, DnsServerCommand}, + dns_server::{AuthorityImpl, DnsServerCommand, handle_command}, }; use super::{AuthorityImplConfig, MinSameSoftwareVersionNodesRatio}; diff --git a/logging/src/lib.rs b/logging/src/lib.rs index 52122e7bb2..15a5d9f83a 100644 --- a/logging/src/lib.rs +++ b/logging/src/lib.rs @@ -22,15 +22,15 @@ use std::{ sync::Mutex, }; -use tracing::{level_filters::LevelFilter, Subscriber}; +use tracing::{Subscriber, level_filters::LevelFilter}; use tracing_subscriber::{ - fmt::MakeWriter, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer, Registry, + EnvFilter, Layer, Registry, fmt::MakeWriter, layer::SubscriberExt, util::SubscriberInitExt, }; pub use log; -pub use log_style::{get_log_style_from_env, LogStyleParseError}; pub use log_style::{LogStyle, TextColoring}; -pub use utils::{get_from_env, GetFromEnvError}; +pub use log_style::{LogStyleParseError, get_log_style_from_env}; +pub use utils::{GetFromEnvError, get_from_env}; /// Default value for `RUST_LOG` used by the "simple" log initialization functions. /// diff --git a/logging/src/log_style.rs b/logging/src/log_style.rs index 1867fbde42..988c205d46 100644 --- a/logging/src/log_style.rs +++ b/logging/src/log_style.rs @@ -15,7 +15,7 @@ use thiserror::Error; -use crate::utils::{get_from_env, GetFromEnvError}; +use crate::utils::{GetFromEnvError, get_from_env}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum TextColoring { diff --git a/logging/tests/env_tests.rs b/logging/tests/env_tests.rs index 47bab399a9..67e9282a9f 100644 --- a/logging/tests/env_tests.rs +++ b/logging/tests/env_tests.rs @@ -13,7 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use logging::{get_log_style_from_env, LogStyle, LogStyleParseError, TextColoring}; +use logging::{LogStyle, LogStyleParseError, TextColoring, get_log_style_from_env}; use test_utils::{remove_env_var, set_env_var}; static TEST_ENV_VAR: &str = "LOG_STYLE_TEST_ENV_VAR"; diff --git a/mempool/src/error/ban_score.rs b/mempool/src/error/ban_score.rs index 6fab80f674..761103475d 100644 --- a/mempool/src/error/ban_score.rs +++ b/mempool/src/error/ban_score.rs @@ -14,14 +14,13 @@ // limitations under the License. use chainstate::{ + ChainstateError, ConnectTransactionError, IOPolicyError, TokensError, + TransactionVerifierStorageError, ban_score::BanScore, tx_verifier::{ - self, - transaction_verifier::{error::SignatureDestinationGetterError, RewardDistributionError}, - CheckTransactionError, + self, CheckTransactionError, + transaction_verifier::{RewardDistributionError, error::SignatureDestinationGetterError}, }, - ChainstateError, ConnectTransactionError, IOPolicyError, TokensError, - TransactionVerifierStorageError, }; use common::chain::IdCreationError; diff --git a/mempool/src/error/mod.rs b/mempool/src/error/mod.rs index 4449b74647..89d3fdb7a5 100644 --- a/mempool/src/error/mod.rs +++ b/mempool/src/error/mod.rs @@ -17,10 +17,10 @@ mod ban_score; use thiserror::Error; -use chainstate::{tx_verifier::error::ConnectTransactionError, ChainstateError}; +use chainstate::{ChainstateError, tx_verifier::error::ConnectTransactionError}; use common::{ chain::{Block, GenBlock, Transaction}, - primitives::{amount::DisplayAmount, Id, H256}, + primitives::{H256, Id, amount::DisplayAmount}, }; use crate::pool::fee::Fee; @@ -84,7 +84,9 @@ pub enum MempoolPolicyError { #[error("Transaction exceeds the maximum block size.")] ExceedsMaxBlockSize, - #[error("Replacement transaction has fee lower than the original. Replacement fee is {replacement_fee:?}, original fee {original_fee:?}")] + #[error( + "Replacement transaction has fee lower than the original. Replacement fee is {replacement_fee:?}, original fee {original_fee:?}" + )] ReplacementFeeLowerThanOriginal { replacement_tx: H256, replacement_fee: Fee, @@ -95,13 +97,17 @@ pub enum MempoolPolicyError { #[error("The sum of the fees of this transaction's conflicts overflows.")] ConflictsFeeOverflow, - #[error("Transaction pays a fee that is lower than the fee of its conflicts with their descendants.")] + #[error( + "Transaction pays a fee that is lower than the fee of its conflicts with their descendants." + )] TransactionFeeLowerThanConflictsWithDescendants, #[error("Underflow in computing transaction's additional fees.")] AdditionalFeesUnderflow, - #[error("Transaction does not pay sufficient fees to be relayed (tx_fee: {tx_fee}, min_relay_fee: {min_relay_fee}).")] + #[error( + "Transaction does not pay sufficient fees to be relayed (tx_fee: {tx_fee}, min_relay_fee: {min_relay_fee})." + )] InsufficientFeesToRelay { tx_fee: DisplayAmount, min_relay_fee: DisplayAmount, @@ -182,7 +188,9 @@ pub enum MempoolConflictError { #[error("Transaction conflicts with another, irreplaceable transaction.")] Irreplacable, - #[error("Replacement transaction spends an unconfirmed input which was not spent by any of the original transactions.")] + #[error( + "Replacement transaction spends an unconfirmed input which was not spent by any of the original transactions." + )] SpendsNewUnconfirmed, #[error("Transaction would require too many replacements.")] diff --git a/mempool/src/interface/mempool_interface.rs b/mempool/src/interface/mempool_interface.rs index b12da196b4..885f670e87 100644 --- a/mempool/src/interface/mempool_interface.rs +++ b/mempool/src/interface/mempool_interface.rs @@ -14,11 +14,11 @@ // limitations under the License. use crate::{ + FeeRate, MempoolMaxSize, TxOptions, TxStatus, error::{BlockConstructionError, Error}, event::MempoolEvent, tx_accumulator::{PackingStrategy, TransactionAccumulator}, tx_origin::{LocalTxOrigin, RemoteTxOrigin}, - FeeRate, MempoolMaxSize, TxOptions, TxStatus, }; use common::{ chain::{GenBlock, SignedTransaction, Transaction}, @@ -93,7 +93,7 @@ pub trait MempoolInterface: Send + Sync { /// Get the fee rate at multiple uniformly distributed points along the mempool's transactions fn get_fee_rate_points(&self, num_points: NonZeroUsize) - -> Result, Error>; + -> Result, Error>; /// Notify mempool given peer has disconnected fn notify_peer_disconnected(&mut self, peer_id: p2p_types::PeerId); diff --git a/mempool/src/interface/mempool_interface_impl.rs b/mempool/src/interface/mempool_interface_impl.rs index e86200900f..97bccb0c33 100644 --- a/mempool/src/interface/mempool_interface_impl.rs +++ b/mempool/src/interface/mempool_interface_impl.rs @@ -14,13 +14,13 @@ // limitations under the License. use crate::{ + FeeRate, MempoolInterface, MempoolMaxSize, TxOptions, TxStatus, config::MempoolConfig, error::{BlockConstructionError, Error}, event::MempoolEvent, pool::memory_usage_estimator::StoreMemoryUsageEstimator, tx_accumulator::{PackingStrategy, TransactionAccumulator}, tx_origin::{LocalTxOrigin, RemoteTxOrigin}, - FeeRate, MempoolInterface, MempoolMaxSize, TxOptions, TxStatus, }; use chainstate::ChainstateEventTracingWrapper; use common::{ diff --git a/mempool/src/lib.rs b/mempool/src/lib.rs index d621839487..2ad9bc9f98 100644 --- a/mempool/src/lib.rs +++ b/mempool/src/lib.rs @@ -17,7 +17,7 @@ pub use config::MempoolMaxSize; pub use interface::{MempoolInit, MempoolInterface}; -pub use mempool_types::{tx_options, tx_origin, TxOptions, TxStatus}; +pub use mempool_types::{TxOptions, TxStatus, tx_options, tx_origin}; mod config; pub mod error; @@ -28,7 +28,7 @@ pub mod rpc; pub mod rpc_event; pub mod tx_accumulator; -pub use {config::MempoolConfig, pool::feerate_points::find_interpolated_value, pool::FeeRate}; +pub use {config::MempoolConfig, pool::FeeRate, pool::feerate_points::find_interpolated_value}; pub type MempoolHandle = subsystem::Handle; diff --git a/mempool/src/pool/entry.rs b/mempool/src/pool/entry.rs index 9f4e6103bc..0cf04c5669 100644 --- a/mempool/src/pool/entry.rs +++ b/mempool/src/pool/entry.rs @@ -17,8 +17,8 @@ use std::num::NonZeroUsize; use common::{ chain::{ - tokens::TokenId, AccountCommand, AccountNonce, AccountSpending, DelegationId, OrderId, - SignedTransaction, Transaction, TxInput, UtxoOutPoint, + AccountCommand, AccountNonce, AccountSpending, DelegationId, OrderId, SignedTransaction, + Transaction, TxInput, UtxoOutPoint, tokens::TokenId, }, primitives::{Id, Idable}, }; diff --git a/mempool/src/pool/mod.rs b/mempool/src/pool/mod.rs index 5d759bb253..4c42b17af2 100644 --- a/mempool/src/pool/mod.rs +++ b/mempool/src/pool/mod.rs @@ -18,7 +18,7 @@ use std::{num::NonZeroUsize, sync::Arc}; use chainstate::{ChainstateError, ChainstateEvent}; use common::{ chain::{ChainConfig, GenBlock, SignedTransaction, Transaction}, - primitives::{time::Time, BlockHeight, Id}, + primitives::{BlockHeight, Id, time::Time}, time_getter::TimeGetter, }; use logging::log; @@ -28,7 +28,7 @@ use utils::{ use utils_networking::broadcaster; use crate::{ - config, + MempoolConfig, MempoolMaxSize, TxStatus, config, error::{ BlockConstructionError, Error, MempoolPolicyError, OrphanPoolError, TxValidationError, }, @@ -36,7 +36,6 @@ use crate::{ tx_accumulator::{PackingStrategy, TransactionAccumulator}, tx_options::{TxOptions, TxTrustPolicy}, tx_origin::{RemoteTxOrigin, TxOrigin}, - MempoolConfig, MempoolMaxSize, TxStatus, }; use self::{ @@ -173,7 +172,9 @@ impl Mempool { })); } (MempoolState::AfterIbd(_), true) => { - log::error!("Received chainstate's IBD flag is true while mempool has already switched from IBD"); + log::error!( + "Received chainstate's IBD flag is true while mempool has already switched from IBD" + ); } } diff --git a/mempool/src/pool/orphans/detect.rs b/mempool/src/pool/orphans/detect.rs index f008c0c19d..8ebf2c5ddf 100644 --- a/mempool/src/pool/orphans/detect.rs +++ b/mempool/src/pool/orphans/detect.rs @@ -24,8 +24,8 @@ pub enum OrphanType { impl OrphanType { /// Check an error signifies a potential orphan transaction pub fn from_error(err: ConnectTransactionError) -> Result { - use chainstate::tx_verifier::error::InputCheckErrorPayload as ICE; use ConnectTransactionError as CTE; + use chainstate::tx_verifier::error::InputCheckErrorPayload as ICE; match &err { // Missing UTXO signifies a possible orphan diff --git a/mempool/src/pool/orphans/mod.rs b/mempool/src/pool/orphans/mod.rs index 710c6c02ae..8e39481268 100644 --- a/mempool/src/pool/orphans/mod.rs +++ b/mempool/src/pool/orphans/mod.rs @@ -18,7 +18,7 @@ use std::collections::{BTreeMap, BTreeSet}; use common::{chain::Transaction, primitives::Id}; use logging::log; use mempool_types::TxStatus; -use randomness::{make_pseudo_rng, RngExt as _}; +use randomness::{RngExt as _, make_pseudo_rng}; use utils::{const_value::ConstValue, ensure}; use super::{OrphanPoolError, Time, TxDependency}; diff --git a/mempool/src/pool/orphans/test.rs b/mempool/src/pool/orphans/test.rs index 3e0d328c0d..ae2d003f3d 100644 --- a/mempool/src/pool/orphans/test.rs +++ b/mempool/src/pool/orphans/test.rs @@ -19,12 +19,12 @@ use rstest::rstest; use common::{ chain::{ - signature::inputsig::InputWitness, AccountNonce, AccountSpending, DelegationId, - SignedTransaction, TxInput, + AccountNonce, AccountSpending, DelegationId, SignedTransaction, TxInput, + signature::inputsig::InputWitness, }, primitives::{Amount, H256}, }; -use test_utils::random::{make_seedable_rng, Rng, RngExt as _, Seed}; +use test_utils::random::{Rng, RngExt as _, Seed, make_seedable_rng}; use super::*; diff --git a/mempool/src/pool/tests/mod.rs b/mempool/src/pool/tests/mod.rs index ff322b8d0e..397b24a445 100644 --- a/mempool/src/pool/tests/mod.rs +++ b/mempool/src/pool/tests/mod.rs @@ -19,10 +19,10 @@ use utils::*; use common::{ chain::{ - output_value::OutputValue, signature::inputsig::InputWitness, Destination, - OutPointSourceId, TxInput, TxOutput, + Destination, OutPointSourceId, TxInput, TxOutput, output_value::OutputValue, + signature::inputsig::InputWitness, }, - primitives::{Amount, Id, Idable, H256}, + primitives::{Amount, H256, Id, Idable}, }; mod basic; diff --git a/mempool/src/pool/tests/orders_v1.rs b/mempool/src/pool/tests/orders_v1.rs index 905b68c6f6..7f1ed7e26e 100644 --- a/mempool/src/pool/tests/orders_v1.rs +++ b/mempool/src/pool/tests/orders_v1.rs @@ -14,20 +14,20 @@ // limitations under the License. use chainstate::{ - constraints_value_accumulator, tx_verifier::error::InputCheckErrorPayload, - ConnectTransactionError, + ConnectTransactionError, constraints_value_accumulator, + tx_verifier::error::InputCheckErrorPayload, }; use chainstate_test_framework::{ + TestFrameworkBuilder, helpers::{ calculate_fill_order, issue_and_mint_random_token_from_best_block, make_tx_builder_to_split_utxo, split_utxo, }, - TestFrameworkBuilder, }; use common::chain::{ + ChainstateUpgradeBuilder, OrderAccountCommand, OrderData, OrderId, OrdersVersion, UtxoOutPoint, make_order_id, tokens::{IsTokenFreezable, TokenId, TokenTotalSupply}, - ChainstateUpgradeBuilder, OrderAccountCommand, OrderData, OrderId, OrdersVersion, UtxoOutPoint, }; use mintscript::translate::TranslationError; use test_utils::{assert_matches, assert_matches_return_val}; diff --git a/mempool/src/pool/tests/utils.rs b/mempool/src/pool/tests/utils.rs index a4026a83b5..e08c7d1f84 100644 --- a/mempool/src/pool/tests/utils.rs +++ b/mempool/src/pool/tests/utils.rs @@ -19,7 +19,7 @@ use common::{ primitives::Id, time_getter::TimeGetter, }; -use mempool_types::{tx_origin::TxOrigin, TxOptions, TxStatus}; +use mempool_types::{TxOptions, TxStatus, tx_origin::TxOrigin}; pub use crate::pool::tx_pool::tests::utils::*; pub use rstest::rstest; diff --git a/mempool/src/pool/tx_pool/collect_txs.rs b/mempool/src/pool/tx_pool/collect_txs.rs index 0cd96aec04..f2030ddf50 100644 --- a/mempool/src/pool/tx_pool/collect_txs.rs +++ b/mempool/src/pool/tx_pool/collect_txs.rs @@ -15,13 +15,13 @@ use crate::{ error::{BlockConstructionError, TxValidationError}, - pool::tx_pool::{tx_verifier, TxMempoolEntry, TxPool}, + pool::tx_pool::{TxMempoolEntry, TxPool, tx_verifier}, tx_accumulator::{PackingStrategy, TransactionAccumulator}, }; use std::{ cmp::Ordering, - collections::{binary_heap, btree_map, BTreeMap, BTreeSet, BinaryHeap}, + collections::{BTreeMap, BTreeSet, BinaryHeap, binary_heap, btree_map}, ops::Deref, }; diff --git a/mempool/src/pool/tx_pool/feerate_points.rs b/mempool/src/pool/tx_pool/feerate_points.rs index 366cf4eb66..766cc157c2 100644 --- a/mempool/src/pool/tx_pool/feerate_points.rs +++ b/mempool/src/pool/tx_pool/feerate_points.rs @@ -93,7 +93,7 @@ pub fn generate_equidistant_span(first: usize, last: usize, n: usize) -> Vec TxPool { let (fee, delta) = match self.validate_transaction(&transaction)? { TxValidationOutcome::Valid { fee, delta } => (fee, delta), TxValidationOutcome::Rejected { error } => { - return Ok(TxAdditionAttemptOutcome::Rejected { transaction, error }) + return Ok(TxAdditionAttemptOutcome::Rejected { transaction, error }); } TxValidationOutcome::TipMoved { start_tip, diff --git a/mempool/src/pool/tx_pool/reorg.rs b/mempool/src/pool/tx_pool/reorg.rs index 9aa93f4345..8ace67c7e0 100644 --- a/mempool/src/pool/tx_pool/reorg.rs +++ b/mempool/src/pool/tx_pool/reorg.rs @@ -20,7 +20,7 @@ use std::collections::BTreeSet; use chainstate::chainstate_interface::ChainstateInterface; use common::{ chain::{Block, GenBlock}, - primitives::{time::Time, Id, Idable}, + primitives::{Id, Idable, time::Time}, }; use logging::log; use utils::ensure; diff --git a/mempool/src/pool/tx_pool/rolling_fee_rate.rs b/mempool/src/pool/tx_pool/rolling_fee_rate.rs index 31e28ecf78..fdf7218a1d 100644 --- a/mempool/src/pool/tx_pool/rolling_fee_rate.rs +++ b/mempool/src/pool/tx_pool/rolling_fee_rate.rs @@ -15,7 +15,7 @@ use std::time::Duration; -use common::primitives::{time::Time, Amount}; +use common::primitives::{Amount, time::Time}; use logging::log; use super::FeeRate; diff --git a/mempool/src/pool/tx_pool/store/mem_usage.rs b/mempool/src/pool/tx_pool/store/mem_usage.rs index 1760857020..dbdd7648e8 100644 --- a/mempool/src/pool/tx_pool/store/mem_usage.rs +++ b/mempool/src/pool/tx_pool/store/mem_usage.rs @@ -18,11 +18,11 @@ use std::{cmp, mem}; use common::chain::{ + SignedTransaction, TxInput, TxOutput, htlc::HashedTimelockContract, signature::inputsig::InputWitness, stakelock::StakePoolData, tokens::{NftIssuance, TokenIssuance}, - SignedTransaction, TxInput, TxOutput, }; use logging::log; diff --git a/mempool/src/pool/tx_pool/store/mod.rs b/mempool/src/pool/tx_pool/store/mod.rs index 4749a3ee46..42d40ec6ec 100644 --- a/mempool/src/pool/tx_pool/store/mod.rs +++ b/mempool/src/pool/tx_pool/store/mod.rs @@ -31,7 +31,7 @@ use utils::newtype; use super::{Fee, Time, TxEntry, TxEntryWithFee}; -use crate::{error::MempoolPolicyError, pool::entry::TxDependency, FeeRate}; +use crate::{FeeRate, error::MempoolPolicyError, pool::entry::TxDependency}; pub use mem_usage::Tracked; diff --git a/mempool/src/pool/tx_pool/tests/basic.rs b/mempool/src/pool/tx_pool/tests/basic.rs index 77f07df2c2..f986da2fcf 100644 --- a/mempool/src/pool/tx_pool/tests/basic.rs +++ b/mempool/src/pool/tx_pool/tests/basic.rs @@ -750,14 +750,16 @@ async fn rolling_fee(#[case] seed: Seed) -> anyhow::Result<()> { tx_pool.add_transaction_test(child_2_high_fee.clone())?.assert_in_mempool(); assert!(tx_pool.contains_transaction(&child_2_high_fee_id)); - assert!(tx_pool - .chainstate_handle() - .call({ - let outpt = child_2_high_fee_outpt.clone(); - move |c| c.utxo(&outpt).unwrap().is_none() - }) - .await - .unwrap()); + assert!( + tx_pool + .chainstate_handle() + .call({ + let outpt = child_2_high_fee_outpt.clone(); + move |c| c.utxo(&outpt).unwrap().is_none() + }) + .await + .unwrap() + ); // TODO The commented out part only applies if RBF is active @@ -779,11 +781,13 @@ async fn rolling_fee(#[case] seed: Seed) -> anyhow::Result<()> { tx_pool.on_new_tip(block_id, BlockHeight::new(1)).unwrap(); assert!(!tx_pool.contains_transaction(&child_2_high_fee_id)); - assert!(tx_pool - .chainstate_handle() - .call(move |c| c.utxo(&child_2_high_fee_outpt).unwrap().is_some()) - .await - .unwrap()); + assert!( + tx_pool + .chainstate_handle() + .call(move |c| c.utxo(&child_2_high_fee_outpt).unwrap().is_some()) + .await + .unwrap() + ); // Because the rolling fee is only updated when we attempt to add a tx to the mempool we need // to submit a "dummy" tx to trigger these updates. diff --git a/mempool/src/pool/tx_pool/tests/mod.rs b/mempool/src/pool/tx_pool/tests/mod.rs index d6923720b5..3bcc8ce3f3 100644 --- a/mempool/src/pool/tx_pool/tests/mod.rs +++ b/mempool/src/pool/tx_pool/tests/mod.rs @@ -16,24 +16,24 @@ use crate::{ config::*, pool::{ - tx_pool::{memory_usage_estimator::StoreMemoryUsageEstimator, *}, OrphanType, TxOptions, TxOrigin, TxStatus, + tx_pool::{memory_usage_estimator::StoreMemoryUsageEstimator, *}, }, }; use ::utils::atomics::SeqCstAtomicU64; use chainstate::{ - make_chainstate, BlockSource, ChainstateConfig, DefaultTransactionVerificationStrategy, - MaxTipAge, + BlockSource, ChainstateConfig, DefaultTransactionVerificationStrategy, MaxTipAge, + make_chainstate, }; use common::{ chain::{ - block::{timestamp::BlockTimestamp, Block, BlockReward, ConsensusData}, + OutPointSourceId, Transaction, UtxoOutPoint, + block::{Block, BlockReward, ConsensusData, timestamp::BlockTimestamp}, config::ChainConfig, output_value::OutputValue, signature::inputsig::InputWitness, transaction::{Destination, TxInput, TxOutput}, - OutPointSourceId, Transaction, UtxoOutPoint, }, primitives::{Id, Idable}, }; diff --git a/mempool/src/pool/tx_pool/tests/utils.rs b/mempool/src/pool/tx_pool/tests/utils.rs index 98ad4cea9e..d6db83f82d 100644 --- a/mempool/src/pool/tx_pool/tests/utils.rs +++ b/mempool/src/pool/tx_pool/tests/utils.rs @@ -13,19 +13,19 @@ // See the License for the specific language governing permissions and // limitations under the License. -use common::chain::output_value::OutputValue; use common::chain::UtxoOutPoint; +use common::chain::output_value::OutputValue; use common::primitives::H256; // Re-export various testing utils from other crates pub use chainstate_test_framework::{ - anyonecanspend_address, empty_witness, TestFramework, TransactionBuilder, + TestFramework, TransactionBuilder, anyonecanspend_address, empty_witness, }; pub use logging::log; pub use rstest::rstest; pub use test_utils::{ mock_time_getter::mocked_time_getter_seconds, - random::{make_seedable_rng, CryptoRng, RngExt as _, Seed}, + random::{CryptoRng, RngExt as _, Seed, make_seedable_rng}, }; pub use memory_usage_estimator::StoreMemoryUsageEstimator; diff --git a/mempool/src/pool/tx_pool/tx_verifier/chainstate_handle.rs b/mempool/src/pool/tx_pool/tx_verifier/chainstate_handle.rs index cf1781552b..de862db16b 100644 --- a/mempool/src/pool/tx_pool/tx_verifier/chainstate_handle.rs +++ b/mempool/src/pool/tx_pool/tx_verifier/chainstate_handle.rs @@ -16,19 +16,19 @@ use std::collections::{BTreeMap, BTreeSet}; use chainstate::{ + ChainstateError, chainstate_interface::ChainstateInterface, tx_verifier::{ - transaction_verifier::{CachedBlockUndo, CachedUtxosBlockUndo}, TransactionSource, TransactionVerifierStorageRef, + transaction_verifier::{CachedBlockUndo, CachedUtxosBlockUndo}, }, - ChainstateError, }; -use chainstate_types::{storage_result, TipStorageTag}; +use chainstate_types::{TipStorageTag, storage_result}; use common::{ chain::{ - tokens::{TokenAuxiliaryData, TokenId}, AccountNonce, AccountType, DelegationId, GenBlock, OrderId, PoolId, Transaction, UtxoOutPoint, + tokens::{TokenAuxiliaryData, TokenId}, }, primitives::{Amount, Id}, }; diff --git a/mempool/src/pool/work_queue/mod.rs b/mempool/src/pool/work_queue/mod.rs index d64f9df858..c03929f471 100644 --- a/mempool/src/pool/work_queue/mod.rs +++ b/mempool/src/pool/work_queue/mod.rs @@ -15,7 +15,7 @@ //! Per-peer work processing schedule queue and related tools. -use std::collections::{btree_map, BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, btree_map}; use p2p_types::PeerId; use randomness::{self, RngExt as _, SliceRandom}; diff --git a/mempool/src/pool/work_queue/test.rs b/mempool/src/pool/work_queue/test.rs index 32929b81cb..b9397bf9e2 100644 --- a/mempool/src/pool/work_queue/test.rs +++ b/mempool/src/pool/work_queue/test.rs @@ -17,7 +17,7 @@ use rstest::rstest; use logging::log; use randomness::{Rng, RngExt as _}; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use super::*; diff --git a/mempool/src/rpc.rs b/mempool/src/rpc.rs index 41adfb59c1..f6bac8a738 100644 --- a/mempool/src/rpc.rs +++ b/mempool/src/rpc.rs @@ -21,11 +21,11 @@ use common::{ chain::{GenBlock, SignedTransaction, Transaction}, primitives::Id, }; -use mempool_types::{tx_options::TxOptionsOverrides, tx_origin::LocalTxOrigin, TxOptions}; +use mempool_types::{TxOptions, tx_options::TxOptionsOverrides, tx_origin::LocalTxOrigin}; use serialization::hex_encoded::HexEncoded; use utils::tap_log::TapLog; -use crate::{rpc_event::RpcEvent, FeeRate, MempoolMaxSize, TxStatus}; +use crate::{FeeRate, MempoolMaxSize, TxStatus, rpc_event::RpcEvent}; use rpc::RpcResult; diff --git a/mempool/src/tx_accumulator/mod.rs b/mempool/src/tx_accumulator/mod.rs index 39cad052bd..37bb7bd99f 100644 --- a/mempool/src/tx_accumulator/mod.rs +++ b/mempool/src/tx_accumulator/mod.rs @@ -14,7 +14,7 @@ // limitations under the License. use common::{ - chain::{block::timestamp::BlockTimestamp, GenBlock, SignedTransaction}, + chain::{GenBlock, SignedTransaction, block::timestamp::BlockTimestamp}, primitives::{Amount, Id}, }; use rpc::description::HasValueHint; diff --git a/mintscript/src/checker/mod.rs b/mintscript/src/checker/mod.rs index 6955fdcecb..30fa7ff764 100644 --- a/mintscript/src/checker/mod.rs +++ b/mintscript/src/checker/mod.rs @@ -17,7 +17,7 @@ mod hashlock; mod signature; mod timelock; -use common::chain::{signature::EvaluatedInputWitness, timelock::OutputTimeLock, Destination}; +use common::chain::{Destination, signature::EvaluatedInputWitness, timelock::OutputTimeLock}; pub use hashlock::HashlockError; use hashlock::{HashlockChecker, NoOpHashlockChecker, StandardHashlockChecker}; diff --git a/mintscript/src/checker/signature.rs b/mintscript/src/checker/signature.rs index 981a7a5a60..bdd54009be 100644 --- a/mintscript/src/checker/signature.rs +++ b/mintscript/src/checker/signature.rs @@ -14,11 +14,11 @@ // limitations under the License. use common::chain::{ + ChainConfig, Destination, signature::{ - sighash::input_commitments::SighashInputCommitment, DestinationSigError, - EvaluatedInputWitness, Transactable, + DestinationSigError, EvaluatedInputWitness, Transactable, + sighash::input_commitments::SighashInputCommitment, }, - ChainConfig, Destination, }; pub trait SignatureChecker { diff --git a/mintscript/src/script/mod.rs b/mintscript/src/script/mod.rs index 82d02755bc..68992832be 100644 --- a/mintscript/src/script/mod.rs +++ b/mintscript/src/script/mod.rs @@ -16,7 +16,7 @@ mod display; mod verify; -use common::chain::{signature::EvaluatedInputWitness, timelock::OutputTimeLock, Destination}; +use common::chain::{Destination, signature::EvaluatedInputWitness, timelock::OutputTimeLock}; use utils::ensure; pub use verify::{ScriptError, ScriptErrorOf, ScriptResult, ScriptVisitor}; diff --git a/mintscript/src/script/verify.rs b/mintscript/src/script/verify.rs index 50e071b3a7..0953ee9477 100644 --- a/mintscript/src/script/verify.rs +++ b/mintscript/src/script/verify.rs @@ -15,7 +15,7 @@ //! Script verification / evaluation -use common::chain::{signature::EvaluatedInputWitness, timelock::OutputTimeLock, Destination}; +use common::chain::{Destination, signature::EvaluatedInputWitness, timelock::OutputTimeLock}; use super::{HashChallenge, WitnessScript}; diff --git a/mintscript/src/tests/mod.rs b/mintscript/src/tests/mod.rs index 09dca89326..c791c96d42 100644 --- a/mintscript/src/tests/mod.rs +++ b/mintscript/src/tests/mod.rs @@ -15,22 +15,22 @@ use common::{ chain::{ + AccountCommand, AccountOutPoint, ChainConfig, DelegationId, Destination, OutPointSourceId, + PoolId, SignedTransaction, Transaction, TxInput, TxOutput, UtxoOutPoint, block::timestamp::BlockTimestamp, output_value::OutputValue, signature::{ - inputsig::{standard_signature::StandardInputSignature, InputWitness}, + inputsig::{InputWitness, standard_signature::StandardInputSignature}, sighash::{input_commitments::SighashInputCommitment, sighashtype::SigHashType}, }, timelock::OutputTimeLock, tokens::TokenId, - AccountCommand, AccountOutPoint, ChainConfig, DelegationId, Destination, OutPointSourceId, - PoolId, SignedTransaction, Transaction, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{Amount, BlockHeight, Id, H256}, + primitives::{Amount, BlockHeight, H256, Id}, }; use crypto::key::{KeyKind, PrivateKey, PublicKey}; use test_utils::random::{ - make_seedable_rng, randomness::SliceRandom, CryptoRng, RngExt as _, Seed, TestRng, + CryptoRng, RngExt as _, Seed, TestRng, make_seedable_rng, randomness::SliceRandom, }; use utxo::{Utxo, UtxoSource}; diff --git a/mintscript/src/tests/translate/mod.rs b/mintscript/src/tests/translate/mod.rs index a52804d75c..223a359d86 100644 --- a/mintscript/src/tests/translate/mod.rs +++ b/mintscript/src/tests/translate/mod.rs @@ -20,11 +20,12 @@ use strum::IntoEnumIterator as _; use ::utils::concatln; use common::{ chain::{ + AccountNonce, AccountSpending, OrderAccountCommand, OrderData, OrderId, block::BlockRewardTransactable, htlc::{HashedTimelockContract, HtlcSecret, HtlcSecretHash}, signature::inputsig::authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, stakelock::StakePoolData, - tokens, AccountNonce, AccountSpending, OrderAccountCommand, OrderData, OrderId, + tokens, }, primitives::per_thousand::PerThousand, }; diff --git a/mintscript/src/translate.rs b/mintscript/src/translate.rs index 3b0942d49f..79c9375fde 100644 --- a/mintscript/src/translate.rs +++ b/mintscript/src/translate.rs @@ -14,21 +14,22 @@ // limitations under the License. use common::chain::{ + AccountCommand, AccountOutPoint, AccountSpending, DelegationId, Destination, + OrderAccountCommand, OrderId, PoolId, SignedTransaction, TxOutput, UtxoOutPoint, block::BlockRewardTransactable, signature::{ + DestinationSigError, EvaluatedInputWitness, inputsig::{ + InputWitness, authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, - standard_signature::StandardInputSignature, InputWitness, + standard_signature::StandardInputSignature, }, - DestinationSigError, EvaluatedInputWitness, }, tokens::TokenId, - AccountCommand, AccountOutPoint, AccountSpending, DelegationId, Destination, - OrderAccountCommand, OrderId, PoolId, SignedTransaction, TxOutput, UtxoOutPoint, }; use utxo::UtxoSource; -use crate::{script::HashChallenge, WitnessScript}; +use crate::{WitnessScript, script::HashChallenge}; /// An error that can happen during translation of an input to a script #[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)] @@ -149,7 +150,7 @@ impl TranslateInput for SignedTransaction { InputWitness::NoSignature(_) => { return Err(TranslationError::SignatureError( DestinationSigError::SignatureNotFound, - )) + )); } InputWitness::Standard(sig) => { let htlc_spend = AuthorizedHashedTimelockContractSpend::from_data( @@ -390,7 +391,7 @@ impl TranslateInput for SignatureOnlyTx { InputWitness::NoSignature(_) => { return Err(TranslationError::SignatureError( DestinationSigError::SignatureNotFound, - )) + )); } InputWitness::Standard(sig) => { let htlc_spend = AuthorizedHashedTimelockContractSpend::from_data( diff --git a/mocks/src/chainstate.rs b/mocks/src/chainstate.rs index aad5a77096..c7d1c3ddab 100644 --- a/mocks/src/chainstate.rs +++ b/mocks/src/chainstate.rs @@ -25,13 +25,13 @@ use chainstate::{ use chainstate_types::{BlockIndex, EpochData, GenBlockIndex}; use common::{ chain::{ + AccountNonce, AccountType, ChainConfig, Currency, DelegationId, OrderId, PoolId, + RpcOrderInfo, TxInput, UtxoOutPoint, block::{ - signed_block_header::SignedBlockHeader, timestamp::BlockTimestamp, Block, BlockReward, - GenBlock, + Block, BlockReward, GenBlock, signed_block_header::SignedBlockHeader, + timestamp::BlockTimestamp, }, tokens::{RPCTokenInfo, TokenAuxiliaryData, TokenId}, - AccountNonce, AccountType, ChainConfig, Currency, DelegationId, OrderId, PoolId, - RpcOrderInfo, TxInput, UtxoOutPoint, }, primitives::{Amount, BlockHeight, Id}, }; diff --git a/mocks/src/mempool.rs b/mocks/src/mempool.rs index cf8b07841d..2d2a217b61 100644 --- a/mocks/src/mempool.rs +++ b/mocks/src/mempool.rs @@ -22,11 +22,11 @@ use common::{ primitives::Id, }; use mempool::{ + FeeRate, MempoolInterface, MempoolMaxSize, TxOptions, TxStatus, error::{BlockConstructionError, Error}, event::MempoolEvent, tx_accumulator::{PackingStrategy, TransactionAccumulator}, tx_origin::{LocalTxOrigin, RemoteTxOrigin}, - FeeRate, MempoolInterface, MempoolMaxSize, TxOptions, TxStatus, }; mockall::mock! { diff --git a/networking/src/transport/impls/channel.rs b/networking/src/transport/impls/channel.rs index b4ce8ffb42..e1b7d15d81 100644 --- a/networking/src/transport/impls/channel.rs +++ b/networking/src/transport/impls/channel.rs @@ -17,8 +17,8 @@ use std::{ collections::BTreeMap, net::{IpAddr, Ipv4Addr, SocketAddr}, sync::{ - atomic::{AtomicU32 as StdAtomicU32, Ordering}, Mutex, + atomic::{AtomicU32 as StdAtomicU32, Ordering}, }, }; @@ -28,7 +28,7 @@ use once_cell::sync::Lazy; use tokio::{ io::{AsyncRead, AsyncWrite, DuplexStream}, sync::{ - mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}, + mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}, oneshot::{self, Sender}, }, }; @@ -36,9 +36,9 @@ use tokio::{ use utils::sync::atomic::AtomicU16; use crate::{ + Result, error::NetworkingError, transport::{ConnectedSocketInfo, PeerStream, TransportListener, TransportSocket}, - Result, }; /// The default value for how much bytes is allowed for write (without reading on the other side). @@ -313,11 +313,15 @@ pub enum MpscChannelTransportError { NoListener(SocketAddr), #[error("Listener for address {0} dropped unexpectedly")] ListenerDroppedUnexpectedly(SocketAddr), - #[error("Unknown connection initiator dropped unexpectedly when listening to addresses {listening_addresses:?}")] + #[error( + "Unknown connection initiator dropped unexpectedly when listening to addresses {listening_addresses:?}" + )] UnknownConnectorDroppedUnexpectedly { listening_addresses: Vec, }, - #[error("Connection initiator dropped unexpectedly, local_address = {local_address}, remote_address = {remote_address}")] + #[error( + "Connection initiator dropped unexpectedly, local_address = {local_address}, remote_address = {remote_address}" + )] ConnectorDroppedUnexpectedly { local_address: SocketAddr, remote_address: SocketAddr, @@ -329,7 +333,7 @@ mod tests { use std::net::SocketAddrV4; use randomness::RngExt; - use test_utils::random::{gen_random_bytes, Seed}; + use test_utils::random::{Seed, gen_random_bytes}; use crate::transport::new_message_stream; diff --git a/networking/src/transport/impls/socks5.rs b/networking/src/transport/impls/socks5.rs index a26964ce09..2098959406 100644 --- a/networking/src/transport/impls/socks5.rs +++ b/networking/src/transport/impls/socks5.rs @@ -21,9 +21,9 @@ use tokio::net::TcpStream; use tokio_socks::tcp::Socks5Stream; use crate::{ + Result, error::NetworkingError, transport::{ConnectedSocketInfo, PeerStream, TransportListener, TransportSocket}, - Result, }; // TODO: Add tests. A typical way to test this is to create a forwarding proxy with a socks interface diff --git a/networking/src/transport/impls/stream_adapter/identity.rs b/networking/src/transport/impls/stream_adapter/identity.rs index ae5aed905d..5782e74d54 100644 --- a/networking/src/transport/impls/stream_adapter/identity.rs +++ b/networking/src/transport/impls/stream_adapter/identity.rs @@ -13,7 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use futures::future::{ready, BoxFuture}; +use futures::future::{BoxFuture, ready}; use crate::{ transport::{ConnectedSocketInfo, PeerStream}, diff --git a/networking/src/transport/impls/stream_adapter/wrapped_transport/tests.rs b/networking/src/transport/impls/stream_adapter/wrapped_transport/tests.rs index f766630483..6f56d1d35b 100644 --- a/networking/src/transport/impls/stream_adapter/wrapped_transport/tests.rs +++ b/networking/src/transport/impls/stream_adapter/wrapped_transport/tests.rs @@ -20,25 +20,26 @@ use std::{ }; use async_trait::async_trait; -use futures::{future::BoxFuture, StreamExt}; +use futures::{StreamExt, future::BoxFuture}; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, time::timeout, }; use test_utils::{ - random::{gen_random_bytes, Seed}, BasicTestTimeGetter, + random::{Seed, gen_random_bytes}, }; use utils::tokio_spawn_in_current_tracing_span; use crate::{ test_helpers::{TestTransportChannel, TestTransportMaker, TestTransportTcp}, transport::{ + ChannelListener, IdentityStreamAdapter, MpscChannelTransport, NoiseEncryptionAdapter, + NoiseEncryptionAdapterMaker, PeerStream, TcpTransportSocket, TransportListener, + TransportSocket, impls::stream_adapter::wrapped_transport::wrapped_listener::MAX_CONCURRENT_HANDSHAKES, - new_message_stream, ChannelListener, IdentityStreamAdapter, MpscChannelTransport, - NoiseEncryptionAdapter, NoiseEncryptionAdapterMaker, PeerStream, TcpTransportSocket, - TransportListener, TransportSocket, + new_message_stream, }, }; diff --git a/networking/src/transport/impls/stream_adapter/wrapped_transport/wrapped_listener.rs b/networking/src/transport/impls/stream_adapter/wrapped_transport/wrapped_listener.rs index 98ee84509b..f6ed143611 100644 --- a/networking/src/transport/impls/stream_adapter/wrapped_transport/wrapped_listener.rs +++ b/networking/src/transport/impls/stream_adapter/wrapped_transport/wrapped_listener.rs @@ -22,9 +22,9 @@ use futures::{ }; use crate::{ - transport::{impls::stream_adapter::traits::StreamAdapter, TransportListener, TransportSocket}, - types::ConnectionDirection, Result, + transport::{TransportListener, TransportSocket, impls::stream_adapter::traits::StreamAdapter}, + types::ConnectionDirection, }; // TODO: Move this constant to some configuration + should be used diff --git a/networking/src/transport/impls/stream_adapter/wrapped_transport/wrapped_socket.rs b/networking/src/transport/impls/stream_adapter/wrapped_transport/wrapped_socket.rs index dc229b32c5..a30ac63ca1 100644 --- a/networking/src/transport/impls/stream_adapter/wrapped_transport/wrapped_socket.rs +++ b/networking/src/transport/impls/stream_adapter/wrapped_transport/wrapped_socket.rs @@ -21,9 +21,9 @@ use futures::future::BoxFuture; use super::wrapped_listener::AdaptedListener; use crate::{ - transport::{impls::stream_adapter::traits::StreamAdapter, TransportSocket}, - types::ConnectionDirection, Result, + transport::{TransportSocket, impls::stream_adapter::traits::StreamAdapter}, + types::ConnectionDirection, }; /// Transport layer that wraps a lower-level transport layer (can be seen like an onion with multiple layer) diff --git a/networking/src/transport/impls/tcp.rs b/networking/src/transport/impls/tcp.rs index 981beec974..f803638981 100644 --- a/networking/src/transport/impls/tcp.rs +++ b/networking/src/transport/impls/tcp.rs @@ -16,13 +16,13 @@ use std::net::SocketAddr; use async_trait::async_trait; -use futures::{future::BoxFuture, stream::FuturesUnordered, StreamExt}; +use futures::{StreamExt, future::BoxFuture, stream::FuturesUnordered}; use tokio::net::{TcpListener, TcpStream}; use utils::tap_log::TapLog; use crate::{ - transport::{ConnectedSocketInfo, PeerStream, TransportListener, TransportSocket}, Result, + transport::{ConnectedSocketInfo, PeerStream, TransportListener, TransportSocket}, }; #[derive(Debug)] @@ -152,7 +152,7 @@ impl ConnectedSocketInfo for TcpTransportStream { #[cfg(test)] mod tests { use serialization::Encode; - use test_utils::random::{gen_random_bytes, Seed}; + use test_utils::random::{Seed, gen_random_bytes}; use crate::{ test_helpers::{TestTransportMaker, TestTransportTcp}, diff --git a/networking/src/transport/message_codec.rs b/networking/src/transport/message_codec.rs index 4f51f7fd05..bbced08a2d 100644 --- a/networking/src/transport/message_codec.rs +++ b/networking/src/transport/message_codec.rs @@ -19,8 +19,8 @@ use bytes::{Buf, BytesMut}; use tokio_util::codec::{Decoder, Encoder}; use crate::{ - error::{MessageCodecError, NetworkingError}, Result, + error::{MessageCodecError, NetworkingError}, }; use serialization::{DecodeAll, Encode}; diff --git a/networking/src/transport/message_stream.rs b/networking/src/transport/message_stream.rs index d678f9473d..80742badac 100644 --- a/networking/src/transport/message_stream.rs +++ b/networking/src/transport/message_stream.rs @@ -120,7 +120,7 @@ where #[cfg(test)] mod tests { use randomness::RngExt; - use test_utils::random::{gen_random_bytes, make_seedable_rng, Seed}; + use test_utils::random::{Seed, gen_random_bytes, make_seedable_rng}; use super::*; diff --git a/networking/src/transport/mod.rs b/networking/src/transport/mod.rs index cf36e637ce..aa02bb4bf0 100644 --- a/networking/src/transport/mod.rs +++ b/networking/src/transport/mod.rs @@ -23,7 +23,7 @@ use impls::{channel, socks5, stream_adapter, tcp}; pub use self::{ channel::{ChannelListener, ChannelStream, MpscChannelTransport, MpscChannelTransportError}, message_codec::MessageCodec, - message_stream::{new_message_stream, MessageReader, MessageWriter}, + message_stream::{MessageReader, MessageWriter, new_message_stream}, socks5::Socks5TransportSocket, stream_adapter::{ identity::IdentityStreamAdapter, diff --git a/node-gui/backend/src/account_id.rs b/node-gui/backend/src/account_id.rs index 45b15b2061..e767e59747 100644 --- a/node-gui/backend/src/account_id.rs +++ b/node-gui/backend/src/account_id.rs @@ -14,7 +14,7 @@ // limitations under the License. use crypto::key::hdkd::u31::U31; -use serde::{de::Error, Deserialize, Serialize}; +use serde::{Deserialize, Serialize, de::Error}; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct AccountId(U31); diff --git a/node-gui/backend/src/backend_impl.rs b/node-gui/backend/src/backend_impl.rs index 97baf0daea..d069fc4e45 100644 --- a/node-gui/backend/src/backend_impl.rs +++ b/node-gui/backend/src/backend_impl.rs @@ -15,7 +15,7 @@ use std::{collections::BTreeMap, fmt::Debug, path::PathBuf, str::FromStr, sync::Arc}; -use futures::{stream::FuturesOrdered, TryStreamExt}; +use futures::{TryStreamExt, stream::FuturesOrdered}; use tokio::{ sync::mpsc::{UnboundedReceiver, UnboundedSender}, task::JoinHandle, @@ -24,7 +24,7 @@ use tokio::{ use common::{ address::{Address, RpcAddress}, chain::{ChainConfig, GenBlock, SignedTransaction}, - primitives::{per_thousand::PerThousand, BlockHeight, Id}, + primitives::{BlockHeight, Id, per_thousand::PerThousand}, }; use crypto::key::hdkd::{child_number::ChildNumber, u31::U31}; use logging::log; @@ -32,21 +32,20 @@ use node_comm::rpc_client::ColdWalletClient; use node_lib::node_controller::NodeController; use serialization::hex_encoded::HexEncoded; use utils::tokio_spawn; -use wallet::{account::transaction_list::TransactionList, wallet::Error, WalletError}; +use wallet::{WalletError, account::transaction_list::TransactionList, wallet::Error}; use wallet_cli_commands::{ - get_repl_command, parse_input, CommandHandler, ConsoleCommand, ManageableWalletCommand, - WalletCommand, + CommandHandler, ConsoleCommand, ManageableWalletCommand, WalletCommand, get_repl_command, + parse_input, }; use wallet_controller::{ - make_cold_wallet_rpc_client, + ControllerConfig, NodeInterface, UtxoState, WalletHandlesClient, make_cold_wallet_rpc_client, types::{Balances, WalletCreationOptions, WalletExtraInfo, WalletTypeArgs}, - ControllerConfig, NodeInterface, UtxoState, WalletHandlesClient, }; use wallet_rpc_client::handles_client::WalletRpcHandlesClient; -use wallet_rpc_lib::{types::HardwareWalletType, EventStream, WalletRpc, WalletService}; +use wallet_rpc_lib::{EventStream, WalletRpc, WalletService, types::HardwareWalletType}; use wallet_types::{ - scan_blockchain::ScanBlockchain, wallet_type::WalletType, with_locked::WithLocked, - ImportOrCreate, + ImportOrCreate, scan_blockchain::ScanBlockchain, wallet_type::WalletType, + with_locked::WithLocked, }; use super::{ @@ -344,14 +343,14 @@ impl Backend { } #[cfg(feature = "trezor")] (WalletType::Trezor, ColdHotNodeController::Cold) => { - return Err(BackendError::HardwareWalletNotSupportedInColdMode) + return Err(BackendError::HardwareWalletNotSupportedInColdMode); } #[cfg(feature = "ledger")] (WalletType::Ledger, ColdHotNodeController::Cold) => { - return Err(BackendError::HardwareWalletNotSupportedInColdMode) + return Err(BackendError::HardwareWalletNotSupportedInColdMode); } (WalletType::Hot, ColdHotNodeController::Cold) => { - return Err(BackendError::HotNotSupported) + return Err(BackendError::HotNotSupported); } }; @@ -432,7 +431,7 @@ impl Backend { | wallet_controller::types::CreatedWallet::NewlyGeneratedMnemonic(_) => {} #[cfg(feature = "trezor")] wallet_controller::types::CreatedWallet::TrezorDeviceSelection(found_devices) => { - return Err(BackendError::MultipleTrezorDevicesFound(found_devices)) + return Err(BackendError::MultipleTrezorDevicesFound(found_devices)); } } tokio_spawn( @@ -579,14 +578,14 @@ impl Backend { } #[cfg(feature = "trezor")] (WalletType::Trezor, ColdHotNodeController::Cold) => { - return Err(BackendError::HardwareWalletNotSupportedInColdMode) + return Err(BackendError::HardwareWalletNotSupportedInColdMode); } #[cfg(feature = "ledger")] (WalletType::Ledger, ColdHotNodeController::Cold) => { - return Err(BackendError::HardwareWalletNotSupportedInColdMode) + return Err(BackendError::HardwareWalletNotSupportedInColdMode); } (WalletType::Hot, ColdHotNodeController::Cold) => { - return Err(BackendError::HotNotSupported) + return Err(BackendError::HotNotSupported); } }; @@ -649,7 +648,7 @@ impl Backend { | wallet_controller::types::OpenedWallet::Opened => {} #[cfg(feature = "trezor")] wallet_controller::types::OpenedWallet::TrezorDeviceSelection(found_devices) => { - return Err(BackendError::MultipleTrezorDevicesFound(found_devices)) + return Err(BackendError::MultipleTrezorDevicesFound(found_devices)); } } tokio_spawn( diff --git a/node-gui/backend/src/chainstate_event_handler.rs b/node-gui/backend/src/chainstate_event_handler.rs index 18990d922d..9574008c65 100644 --- a/node-gui/backend/src/chainstate_event_handler.rs +++ b/node-gui/backend/src/chainstate_event_handler.rs @@ -16,7 +16,7 @@ use std::sync::Arc; use anyhow::Context as _; -use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; +use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; use chainstate::ChainstateEvent; use utils::tap_log::TapLog; diff --git a/node-gui/backend/src/error.rs b/node-gui/backend/src/error.rs index fd47f11926..d59afb29fd 100644 --- a/node-gui/backend/src/error.rs +++ b/node-gui/backend/src/error.rs @@ -38,7 +38,9 @@ pub enum BackendError { InvalidPledgeAmount(String), #[error("Invalid cost per block amount: {0}")] InvalidCostPerBlockAmount(String), - #[error("Failed to parse margin per thousand: {0}. The decimal must be in the range [0.001,1.000] or [0.1%,100%]")] + #[error( + "Failed to parse margin per thousand: {0}. The decimal must be in the range [0.001,1.000] or [0.1%,100%]" + )] InvalidMarginPerThousand(String), #[error("Unsupported operation by a cold wallet")] ColdWallet, diff --git a/node-gui/backend/src/lib.rs b/node-gui/backend/src/lib.rs index ea3a0f8f48..5ec14f902f 100644 --- a/node-gui/backend/src/lib.rs +++ b/node-gui/backend/src/lib.rs @@ -25,7 +25,7 @@ mod wallet_events; use std::{fmt::Debug, sync::Arc}; use anyhow::anyhow; -use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; +use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; use chainstate::ChainInfo; use common::{ diff --git a/node-gui/backend/src/messages.rs b/node-gui/backend/src/messages.rs index b706460c03..d6c08d1c0d 100644 --- a/node-gui/backend/src/messages.rs +++ b/node-gui/backend/src/messages.rs @@ -35,7 +35,7 @@ use wallet::account::transaction_list::TransactionList; use wallet_cli_commands::ConsoleCommand; use wallet_controller::types::{Balances, WalletExtraInfo, WalletTypeArgs}; use wallet_rpc_lib::types::PoolInfo; -use wallet_types::{wallet_type::WalletType, ImportOrCreate}; +use wallet_types::{ImportOrCreate, wallet_type::WalletType}; use super::{AccountId, BackendError}; diff --git a/node-gui/backend/src/p2p_event_handler.rs b/node-gui/backend/src/p2p_event_handler.rs index 5d8971e5df..97e8f9bbf8 100644 --- a/node-gui/backend/src/p2p_event_handler.rs +++ b/node-gui/backend/src/p2p_event_handler.rs @@ -16,9 +16,9 @@ use std::sync::Arc; use anyhow::Context; -use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; +use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; -use p2p::{interface::p2p_interface::P2pInterface, P2pEvent}; +use p2p::{P2pEvent, interface::p2p_interface::P2pInterface}; use subsystem::Handle; use utils::tap_log::TapLog; diff --git a/node-gui/src/main.rs b/node-gui/src/main.rs index 4fbd2310c9..9aac38e553 100644 --- a/node-gui/src/main.rs +++ b/node-gui/src/main.rs @@ -22,10 +22,10 @@ use std::{convert::identity, env}; use heck::ToUpperCamelCase as _; use iced::{ + Element, Length, Settings, Size, Subscription, Task, Theme, advanced::graphics::core::window, executor, font, - widget::{column, row, text, tooltip, Text}, - Element, Length, Settings, Size, Subscription, Task, Theme, + widget::{Text, column, row, text, tooltip}, }; use iced_aw::widgets::spinner::Spinner; use tokio::sync::mpsc::UnboundedReceiver; @@ -33,14 +33,13 @@ use tokio::sync::mpsc::UnboundedReceiver; use common::chain::config::ChainType; use main_window::{MainWindow, MainWindowMessage}; use node_gui_backend::{ + BackendControls, BackendSender, InitNetwork, NodeInitializationOutcome, WalletMode, messages::{BackendEvent, BackendRequest}, - node_initialize, BackendControls, BackendSender, InitNetwork, NodeInitializationOutcome, - WalletMode, + node_initialize, }; -use node_lib::{NodeType, CLEAN_DATA_OPTION_LONG_NAME}; +use node_lib::{CLEAN_DATA_OPTION_LONG_NAME, NodeType}; -const COLD_WALLET_TOOLTIP_TEXT: &str = - "Start the wallet in Cold mode without connecting to the network or any nodes. The Cold mode is made to run the wallet on an air-gapped machine without internet connection for storage of keys of high-value. For example, pool decommission keys."; +const COLD_WALLET_TOOLTIP_TEXT: &str = "Start the wallet in Cold mode without connecting to the network or any nodes. The Cold mode is made to run the wallet on an air-gapped machine without internet connection for storage of keys of high-value. For example, pool decommission keys."; const HOT_WALLET_TOOLTIP_TEXT: &str = "Start the wallet in Hot mode and connect to the network."; const MAIN_NETWORK_TOOLTIP: &str = "The 'Mainnet' is the main network that has coins with value."; diff --git a/node-gui/src/main_window/main_menu.rs b/node-gui/src/main_window/main_menu.rs index 4f931b2b70..b77ba76e14 100644 --- a/node-gui/src/main_window/main_menu.rs +++ b/node-gui/src/main_window/main_menu.rs @@ -14,9 +14,8 @@ // limitations under the License. use iced::{ - alignment, + Color, Element, Length, Theme, alignment, widget::{button, container, text}, - Color, Element, Length, Theme, }; use iced_aw::menu::{Item, Menu, MenuBar}; use wallet_types::wallet_type::WalletType; diff --git a/node-gui/src/main_window/main_widget/mod.rs b/node-gui/src/main_window/main_widget/mod.rs index 827310c96e..ec2f532396 100644 --- a/node-gui/src/main_window/main_widget/mod.rs +++ b/node-gui/src/main_window/main_widget/mod.rs @@ -16,7 +16,7 @@ pub mod tabs; use iced::{Element, Task}; -use node_gui_backend::{messages::WalletId, BackendSender}; +use node_gui_backend::{BackendSender, messages::WalletId}; use wallet_types::wallet_type::WalletType; use crate::WalletMode; diff --git a/node-gui/src/main_window/main_widget/tabs/cold_wallet.rs b/node-gui/src/main_window/main_widget/tabs/cold_wallet.rs index 1048645c55..1f9344197d 100644 --- a/node-gui/src/main_window/main_widget/tabs/cold_wallet.rs +++ b/node-gui/src/main_window/main_widget/tabs/cold_wallet.rs @@ -15,8 +15,8 @@ use common::chain::ChainConfig; use iced::{ - widget::{column, Text}, Element, Length, + widget::{Text, column}, }; use iced_aw::tab_bar::TabLabel; @@ -50,7 +50,9 @@ impl Tab for ColdWalletTab { fn content(&self, node_state: &NodeState) -> Element<'_, Self::Message> { let network_type = get_network_type_capitalized(node_state.chain_config()); - let msg = format!("Running in cold wallet mode on {network_type}\nOpen a wallet from the file menu to start"); + let msg = format!( + "Running in cold wallet mode on {network_type}\nOpen a wallet from the file menu to start" + ); column![Text::new(msg).size(16)] .padding(10) .spacing(15) diff --git a/node-gui/src/main_window/main_widget/tabs/mod.rs b/node-gui/src/main_window/main_widget/tabs/mod.rs index 8c29a05a8d..bc4d1ca7e6 100644 --- a/node-gui/src/main_window/main_widget/tabs/mod.rs +++ b/node-gui/src/main_window/main_widget/tabs/mod.rs @@ -18,9 +18,9 @@ use iced_aw::{TabLabel, Tabs}; use strum::EnumCount; use wallet_types::wallet_type::WalletType; -use node_gui_backend::{messages::WalletId, BackendSender}; +use node_gui_backend::{BackendSender, messages::WalletId}; -use crate::{main_window::NodeState, WalletMode}; +use crate::{WalletMode, main_window::NodeState}; use self::{ cold_wallet::ColdWalletTab, diff --git a/node-gui/src/main_window/main_widget/tabs/networking.rs b/node-gui/src/main_window/main_widget/tabs/networking.rs index 5d563bade8..edfb4ecd29 100644 --- a/node-gui/src/main_window/main_widget/tabs/networking.rs +++ b/node-gui/src/main_window/main_widget/tabs/networking.rs @@ -16,10 +16,10 @@ use std::fmt::Debug; use iced::{ - widget::{column, container, Text}, Element, Length, Task, + widget::{Text, column, container}, }; -use iced_aw::{tab_bar::TabLabel, Grid, GridRow}; +use iced_aw::{Grid, GridRow, tab_bar::TabLabel}; use crate::main_window::NodeState; diff --git a/node-gui/src/main_window/main_widget/tabs/settings.rs b/node-gui/src/main_window/main_widget/tabs/settings.rs index aa224433d5..5e00adb453 100644 --- a/node-gui/src/main_window/main_widget/tabs/settings.rs +++ b/node-gui/src/main_window/main_widget/tabs/settings.rs @@ -14,8 +14,8 @@ // limitations under the License. use iced::{ - widget::{column, Column, Container, Radio, Text}, Element, Length, Task, + widget::{Column, Container, Radio, Text, column}, }; use iced_aw::tab_bar::TabLabel; diff --git a/node-gui/src/main_window/main_widget/tabs/summary.rs b/node-gui/src/main_window/main_widget/tabs/summary.rs index 6993f9f57d..e7ea2aee15 100644 --- a/node-gui/src/main_window/main_widget/tabs/summary.rs +++ b/node-gui/src/main_window/main_widget/tabs/summary.rs @@ -17,12 +17,12 @@ use std::fmt::Debug; use common::chain::ChainConfig; use iced::{ - widget::{column, tooltip, Text}, Element, Length, Task, + widget::{Text, column, tooltip}, }; -use iced_aw::{tab_bar::TabLabel, Grid, GridRow}; +use iced_aw::{Grid, GridRow, tab_bar::TabLabel}; -use crate::main_window::{print_block_timestamp, NodeState}; +use crate::main_window::{NodeState, print_block_timestamp}; use super::{Tab, TabsMessage}; diff --git a/node-gui/src/main_window/main_widget/tabs/wallet/addresses.rs b/node-gui/src/main_window/main_widget/tabs/wallet/addresses.rs index d762445994..a75a493958 100644 --- a/node-gui/src/main_window/main_widget/tabs/wallet/addresses.rs +++ b/node-gui/src/main_window/main_widget/tabs/wallet/addresses.rs @@ -14,8 +14,8 @@ // limitations under the License. use iced::{ - widget::{button, column, row, tooltip, Text}, Element, + widget::{Text, button, column, row, tooltip}, }; use iced_aw::{Grid, GridRow}; diff --git a/node-gui/src/main_window/main_widget/tabs/wallet/console.rs b/node-gui/src/main_window/main_widget/tabs/wallet/console.rs index 2b6db59d50..94938fa252 100644 --- a/node-gui/src/main_window/main_widget/tabs/wallet/console.rs +++ b/node-gui/src/main_window/main_widget/tabs/wallet/console.rs @@ -14,14 +14,14 @@ // limitations under the License. use iced::{ - widget::{button, column, row, scrollable::Id, tooltip, Scrollable, Text}, Element, Length, + widget::{Scrollable, Text, button, column, row, scrollable::Id, tooltip}, }; use node_gui_backend::messages::WalletInfo; use crate::main_window::main_widget::tabs::wallet::{ - status_bar::estimate_status_bar_height, STATUS_BAR_SEPARATOR_HEIGHT, + STATUS_BAR_SEPARATOR_HEIGHT, status_bar::estimate_status_bar_height, }; use super::{ConsoleState, WalletMessage}; diff --git a/node-gui/src/main_window/main_widget/tabs/wallet/delegation.rs b/node-gui/src/main_window/main_widget/tabs/wallet/delegation.rs index 0ffd8d42db..57e6a1e254 100644 --- a/node-gui/src/main_window/main_widget/tabs/wallet/delegation.rs +++ b/node-gui/src/main_window/main_widget/tabs/wallet/delegation.rs @@ -16,8 +16,8 @@ use std::collections::BTreeMap; use iced::{ - widget::{button, column, row, text_input, tooltip, tooltip::Position, Space, Text}, Element, Length, + widget::{Space, Text, button, column, row, text_input, tooltip, tooltip::Position}, }; use iced_aw::{Grid, GridRow}; @@ -30,7 +30,7 @@ use node_gui_backend::messages::AccountInfo; use crate::main_window::print_coin_amount; -use super::{stake::MATURITY_PERIOD_TOOLTIP_TEXT, WalletMessage}; +use super::{WalletMessage, stake::MATURITY_PERIOD_TOOLTIP_TEXT}; const POOL_ID_TOOLTIP_TEXT: &str = "The pool address of the pool that will get the delegation and stake the coins."; @@ -46,8 +46,7 @@ const SEND_DELEGATION_ID_TOOLTIP_TEXT: &str = const CREATE_DELEGATION_BUTTON_TOOLTIP_TEXT: &str = "Before delegating your coins, you create an account that you own, which you can fund with coins (and withdraw from). \ Once this is created, you can delegate coins to it for staking. If the pool is decommissioned, it is your responsibility to withdraw the coins and move them to another pool."; -const WITHDRAW_BUTTON_TOOLTIP_TEXT: &str = - "Withdrawing coins from delegation means they won't be staked anymore. The coins will be locked for the maturity period before they can be normally used."; +const WITHDRAW_BUTTON_TOOLTIP_TEXT: &str = "Withdrawing coins from delegation means they won't be staked anymore. The coins will be locked for the maturity period before they can be normally used."; #[allow(clippy::too_many_arguments)] pub fn view_delegation( diff --git a/node-gui/src/main_window/main_widget/tabs/wallet/left_panel.rs b/node-gui/src/main_window/main_widget/tabs/wallet/left_panel.rs index 1edc54e6a9..3a5fd75b10 100644 --- a/node-gui/src/main_window/main_widget/tabs/wallet/left_panel.rs +++ b/node-gui/src/main_window/main_widget/tabs/wallet/left_panel.rs @@ -14,11 +14,11 @@ // limitations under the License. use iced::{ - widget::{button, column, pick_list, progress_bar, row, text, tooltip, Column, Text}, Alignment, Element, Length, + widget::{Column, Text, button, column, pick_list, progress_bar, row, text, tooltip}, }; -use node_gui_backend::{messages::WalletInfo, AccountId}; +use node_gui_backend::{AccountId, messages::WalletInfo}; use wallet_types::wallet_type::WalletType; use crate::main_window::NodeState; @@ -38,8 +38,7 @@ const DELEGATION_TOOLTIP_TEXT: &str = "Delegation is part of staking, where if y and you won't have to keep your node running."; const CONSOLE_TOOLTIP_TEXT: &str = "Console for using low-level functions of the wallet."; -const NEW_ACCOUNT_TOOLTIP_TEXT: &str = - "Accounts provide a way to completely separate keys and operations. \ +const NEW_ACCOUNT_TOOLTIP_TEXT: &str = "Accounts provide a way to completely separate keys and operations. \ For example, you can have an account for personal use, and an account for work. \ Each account will have a completely different set of keys."; diff --git a/node-gui/src/main_window/main_widget/tabs/wallet/mod.rs b/node-gui/src/main_window/main_widget/tabs/wallet/mod.rs index af94bbd818..d198dc9f02 100644 --- a/node-gui/src/main_window/main_widget/tabs/wallet/mod.rs +++ b/node-gui/src/main_window/main_widget/tabs/wallet/mod.rs @@ -28,22 +28,22 @@ pub use console::CONSOLE_OUTPUT_ID; use std::collections::BTreeMap; use iced::{ + Element, Length, Task, widget::{ - column, container, horizontal_rule, pane_grid, row, - scrollable::{snap_to, Id}, - vertical_rule, PaneGrid, Scrollable, Text, + PaneGrid, Scrollable, Text, column, container, horizontal_rule, pane_grid, row, + scrollable::{Id, snap_to}, + vertical_rule, }, - Element, Length, Task, }; use iced_aw::tab_bar::TabLabel; use common::chain::DelegationId; use node_gui_backend::{ + AccountId, BackendSender, messages::{ BackendRequest, CreateDelegationRequest, DecommissionPoolRequest, DelegateStakingRequest, SendDelegateToAddressRequest, SendRequest, StakeRequest, WalletId, }, - AccountId, BackendSender, }; use wallet_controller::DEFAULT_ACCOUNT_INDEX; use wallet_types::wallet_type::WalletType; diff --git a/node-gui/src/main_window/main_widget/tabs/wallet/send.rs b/node-gui/src/main_window/main_widget/tabs/wallet/send.rs index 882c203af5..2cd9527cd5 100644 --- a/node-gui/src/main_window/main_widget/tabs/wallet/send.rs +++ b/node-gui/src/main_window/main_widget/tabs/wallet/send.rs @@ -15,8 +15,8 @@ use common::primitives::DecimalAmount; use iced::{ - widget::{column, text_input, Text}, Element, + widget::{Text, column, text_input}, }; use super::WalletMessage; diff --git a/node-gui/src/main_window/main_widget/tabs/wallet/stake.rs b/node-gui/src/main_window/main_widget/tabs/wallet/stake.rs index 30506ffdaa..e35f3f3b1b 100644 --- a/node-gui/src/main_window/main_widget/tabs/wallet/stake.rs +++ b/node-gui/src/main_window/main_widget/tabs/wallet/stake.rs @@ -14,8 +14,8 @@ // limitations under the License. use iced::{ - widget::{button, column, row, text_input, tooltip, tooltip::Position, Text}, Alignment, Element, Length, + widget::{Text, button, column, row, text_input, tooltip, tooltip::Position}, }; use iced_aw::{Grid, GridRow}; @@ -35,7 +35,7 @@ pub const MATURITY_PERIOD_TOOLTIP_TEXT: &str = "Any amount in a staking pool, wh For delegations, any amount taken out of a delegation will be locked for the maturity period. The locking is done automatically \ at the consensus level."; -const PLEDGE_AMOUNT_TOOLTIP_TEXT: &str ="The amount to be pledged to the pool. There is a minimum to be accepted. \ +const PLEDGE_AMOUNT_TOOLTIP_TEXT: &str = "The amount to be pledged to the pool. There is a minimum to be accepted. \ This amount, and the rewards gained by the pool, CANNOT be taken out without decommissioning the pool. \ If you'd like to withdraw rewards, consider creating a pool and delegating to yourself. \ Delegators have no restrictions on withdrawals. \ @@ -57,14 +57,12 @@ const CREATE_STAKING_POOL_TOOLTIP_TEXT: &str = "A staking pool locks the pledge which will earn you extra rewards for staking their coins. Once a pool is created, it will be assigned a pool id, which can be used \ by other delegators to delegate to you."; -const START_STAKING_TOOLTIP_TEXT: &str = - "If you have created pools, this will activate staking. The node must be kept running, in order to assist the network in creating blocks and earn rewards."; +const START_STAKING_TOOLTIP_TEXT: &str = "If you have created pools, this will activate staking. The node must be kept running, in order to assist the network in creating blocks and earn rewards."; const DECOMMISSION_POOL_ADDRESS_TOOLTIP_TEXT: &str = "The address of the pool that will be decommissioned. Make sure to stop staking before going through with this."; const DECOMMISSION_COINS_DESTINATION_ADDRESS_TOOLTIP_TEXT: &str = "The output address where the coins will be sent after decommissioning the pool."; -const DECOMMISSION_POOL_TOOLTIP_TEXT: &str = - "This will decommission the staking pool and lock the pledge amount for the maturity period (see above to learn how long). Locking implies that the coins cannot be moved until the lock period is over. This is needed for blockchain security reasons. Please STOP STAKING before doing this, otherwise decommissioning won't work. DO NOT use an exchange address for this. Most exchanges cannot handle locked outputs."; +const DECOMMISSION_POOL_TOOLTIP_TEXT: &str = "This will decommission the staking pool and lock the pledge amount for the maturity period (see above to learn how long). Locking implies that the coins cannot be moved until the lock period is over. This is needed for blockchain security reasons. Please STOP STAKING before doing this, otherwise decommissioning won't work. DO NOT use an exchange address for this. Most exchanges cannot handle locked outputs."; #[allow(clippy::too_many_arguments)] pub fn view_stake( diff --git a/node-gui/src/main_window/main_widget/tabs/wallet/status_bar.rs b/node-gui/src/main_window/main_widget/tabs/wallet/status_bar.rs index 9fc4ed9911..da75bee697 100644 --- a/node-gui/src/main_window/main_widget/tabs/wallet/status_bar.rs +++ b/node-gui/src/main_window/main_widget/tabs/wallet/status_bar.rs @@ -16,9 +16,8 @@ use iced::Element; #[cfg(any(feature = "trezor", feature = "ledger"))] use iced::{ - font, - widget::{container, rich_text, row, span, Container, Row}, - Alignment, Font, Length, Padding, Theme, + Alignment, Font, Length, Padding, Theme, font, + widget::{Container, Row, container, rich_text, row, span}, }; use wallet_controller::types::WalletExtraInfo; diff --git a/node-gui/src/main_window/main_widget/tabs/wallet/top_panel.rs b/node-gui/src/main_window/main_widget/tabs/wallet/top_panel.rs index a59a2bb911..4120450dd5 100644 --- a/node-gui/src/main_window/main_widget/tabs/wallet/top_panel.rs +++ b/node-gui/src/main_window/main_widget/tabs/wallet/top_panel.rs @@ -14,8 +14,8 @@ // limitations under the License. use iced::{ - widget::{button, horizontal_space, row, text::LineHeight, tooltip, Text}, Alignment, Element, Length, + widget::{Text, button, horizontal_space, row, text::LineHeight, tooltip}, }; use common::chain::ChainConfig; @@ -41,8 +41,10 @@ pub fn view_top_panel( let password = match wallet_info.encryption { EncryptionState::EnabledLocked => { - row![iced::widget::button(Text::new("Unlock").line_height(LineHeight::Relative(1.0))) - .on_press(WalletMessage::Unlock)] + row![ + iced::widget::button(Text::new("Unlock").line_height(LineHeight::Relative(1.0))) + .on_press(WalletMessage::Unlock) + ] } EncryptionState::EnabledUnlocked => row![ iced::widget::button(Text::new("Lock").line_height(LineHeight::Relative(1.0))) diff --git a/node-gui/src/main_window/main_widget/tabs/wallet/transactions.rs b/node-gui/src/main_window/main_widget/tabs/wallet/transactions.rs index 081f3a94f8..b0df9db7e9 100644 --- a/node-gui/src/main_window/main_widget/tabs/wallet/transactions.rs +++ b/node-gui/src/main_window/main_widget/tabs/wallet/transactions.rs @@ -14,8 +14,8 @@ // limitations under the License. use iced::{ - widget::{button, row, tooltip, tooltip::Position, Column, Text}, Alignment, Element, Length, + widget::{Column, Text, button, row, tooltip, tooltip::Position}, }; use iced_aw::{Grid, GridRow}; diff --git a/node-gui/src/main_window/mod.rs b/node-gui/src/main_window/mod.rs index 2cf24249f8..020f0129cd 100644 --- a/node-gui/src/main_window/mod.rs +++ b/node-gui/src/main_window/mod.rs @@ -17,47 +17,47 @@ use std::{collections::BTreeMap, convert::identity, path::PathBuf, sync::Arc, ti use chainstate::ChainInfo; use common::{ - chain::{block::timestamp::BlockTimestamp, ChainConfig}, - primitives::{per_thousand::PerThousand, semver::SemVer, user_agent::UserAgent, Amount}, + chain::{ChainConfig, block::timestamp::BlockTimestamp}, + primitives::{Amount, per_thousand::PerThousand, semver::SemVer, user_agent::UserAgent}, }; use iced::{ - widget::{center, container, Stack, Text}, Element, Length, Task, + widget::{Stack, Text, center, container}, }; use logging::log; use node_gui_backend::{ + BackendSender, InitializedNode, messages::{ BackendEvent, BackendRequest, EncryptionAction, SignedTransactionWrapper, TransactionInfo, WalletId, WalletInfo, }, - BackendSender, InitializedNode, }; -use p2p::{net::types::services::Services, types::peer_id::PeerId, P2pEvent}; +use p2p::{P2pEvent, net::types::services::Services, types::peer_id::PeerId}; use rfd::AsyncFileDialog; use wallet_cli_commands::ConsoleCommand; use wallet_controller::types::WalletTypeArgs; -use wallet_types::{seed_phrase::StoreSeedPhrase, wallet_type::WalletType, ImportOrCreate}; +use wallet_types::{ImportOrCreate, seed_phrase::StoreSeedPhrase, wallet_type::WalletType}; -#[cfg(any(feature = "trezor", feature = "ledger"))] -use crate::widgets::create_hw_wallet::hw_wallet_create_dialog; #[cfg(any(feature = "trezor", feature = "ledger"))] use crate::widgets::create_hw_wallet::HardwareWalletType; +#[cfg(any(feature = "trezor", feature = "ledger"))] +use crate::widgets::create_hw_wallet::hw_wallet_create_dialog; use crate::{ + WalletMode, main_window::{main_menu::MenuMessage, main_widget::MainWidgetMessage}, widgets::{ confirm_broadcast::new_confirm_broadcast, esc_handler::esc_handler, new_wallet_account::new_wallet_account, opaque::opaque, - popup_dialog::{popup_dialog, Popup}, + popup_dialog::{Popup, popup_dialog}, wallet_mnemonic::wallet_mnemonic_dialog, wallet_set_password::wallet_set_password_dialog, wallet_unlock::wallet_unlock_dialog, }, - WalletMode, }; -use self::main_widget::tabs::{wallet::WalletMessage, TabsMessage}; +use self::main_widget::tabs::{TabsMessage, wallet::WalletMessage}; mod main_menu; mod main_widget; diff --git a/node-gui/src/widgets/confirm_broadcast.rs b/node-gui/src/widgets/confirm_broadcast.rs index 120ea2e600..4e0f10c25c 100644 --- a/node-gui/src/widgets/confirm_broadcast.rs +++ b/node-gui/src/widgets/confirm_broadcast.rs @@ -19,9 +19,9 @@ use std::sync::Arc; use iced::widget::Component; use iced::{ - alignment::Horizontal, - widget::{self, container, Button, Text}, Element, Length, Theme, + alignment::Horizontal, + widget::{self, Button, Text, container}, }; use iced_aw::Card; diff --git a/node-gui/src/widgets/create_hw_wallet.rs b/node-gui/src/widgets/create_hw_wallet.rs index ea3f16dbcb..2ad534601e 100644 --- a/node-gui/src/widgets/create_hw_wallet.rs +++ b/node-gui/src/widgets/create_hw_wallet.rs @@ -17,9 +17,9 @@ use iced::widget::Component; use iced::{ - alignment::Horizontal, - widget::{self, container, text, Button, Text}, Element, Length, Theme, + alignment::Horizontal, + widget::{self, Button, Text, container, text}, }; use iced_aw::Card; diff --git a/node-gui/src/widgets/esc_handler.rs b/node-gui/src/widgets/esc_handler.rs index 43ca2b69d4..781c3bebb7 100644 --- a/node-gui/src/widgets/esc_handler.rs +++ b/node-gui/src/widgets/esc_handler.rs @@ -14,14 +14,14 @@ // limitations under the License. use iced::{ + Element, Event, Length, Rectangle, Size, Vector, advanced::{ - layout, renderer, - widget::{tree, Operation, Tree}, - Clipboard, Layout, Shell, Widget, + Clipboard, Layout, Shell, Widget, layout, renderer, + widget::{Operation, Tree, tree}, }, event, keyboard, mouse::{self}, - overlay, Element, Event, Length, Rectangle, Size, Vector, + overlay, }; /// Wrap an element, capturing Esc key press events and optionally emitting the specified message diff --git a/node-gui/src/widgets/new_wallet_account.rs b/node-gui/src/widgets/new_wallet_account.rs index dbb56dbc7c..f398f25728 100644 --- a/node-gui/src/widgets/new_wallet_account.rs +++ b/node-gui/src/widgets/new_wallet_account.rs @@ -32,9 +32,9 @@ use iced::widget::Component; use iced::{ - alignment::Horizontal, - widget::{self, container, text_input, Button, Text}, Element, Length, Theme, + alignment::Horizontal, + widget::{self, Button, Text, container, text_input}, }; use iced_aw::Card; @@ -88,9 +88,11 @@ impl Component for NewWalletAccount P2pConfigFile { mod tests { use std::io::Write; - use randomness::{distributions::Alphanumeric, make_pseudo_rng, RngExt as _}; + use randomness::{RngExt as _, distributions::Alphanumeric, make_pseudo_rng}; use super::*; diff --git a/node-lib/src/lib.rs b/node-lib/src/lib.rs index 2491f1775e..0bdb1a3df4 100644 --- a/node-lib/src/lib.rs +++ b/node-lib/src/lib.rs @@ -31,12 +31,12 @@ use chainstate_launcher::ChainConfig; pub use config_files::{ NodeConfigFile, NodeTypeConfigFile, RpcConfigFile, StorageBackendConfigFile, }; -pub use node_daemon_runner::{run_node_daemon, ExitCode}; +pub use node_daemon_runner::{ExitCode, run_node_daemon}; pub use options::{ - Command, Options, OptionsWithResolvedCommand, RunOptions, TopLevelOptions, - CLEAN_DATA_OPTION_LONG_NAME, IMPORT_BOOTSTRAP_FILE_OPTION_LONG_NAME, + CLEAN_DATA_OPTION_LONG_NAME, Command, IMPORT_BOOTSTRAP_FILE_OPTION_LONG_NAME, Options, + OptionsWithResolvedCommand, RunOptions, TopLevelOptions, }; -pub use runner::{setup, NodeSetupResult, NodeType}; +pub use runner::{NodeSetupResult, NodeType, setup}; pub fn default_rpc_config(chain_config: &ChainConfig) -> RpcConfigFile { RpcConfigFile::with_run_options( diff --git a/node-lib/src/node_daemon_runner.rs b/node-lib/src/node_daemon_runner.rs index d8c651ff5a..a01490f0f9 100644 --- a/node-lib/src/node_daemon_runner.rs +++ b/node-lib/src/node_daemon_runner.rs @@ -15,12 +15,12 @@ use anyhow::Result; -use chainstate::{import_bootstrap_file, BootstrapError, ChainstateError}; +use chainstate::{BootstrapError, ChainstateError, import_bootstrap_file}; use utils::{shallow_clone::ShallowClone as _, tokio_spawn}; use crate::{ - setup, NodeSetupResult, NodeType, Options, CLEAN_DATA_OPTION_LONG_NAME, - IMPORT_BOOTSTRAP_FILE_OPTION_LONG_NAME, + CLEAN_DATA_OPTION_LONG_NAME, IMPORT_BOOTSTRAP_FILE_OPTION_LONG_NAME, NodeSetupResult, NodeType, + Options, setup, }; pub struct ExitCode(pub i32); diff --git a/node-lib/src/options.rs b/node-lib/src/options.rs index 0ed40fca13..9016d2e258 100644 --- a/node-lib/src/options.rs +++ b/node-lib/src/options.rs @@ -29,8 +29,8 @@ use common::{ chain::{ self, config::{ - regtest_options::{regtest_chain_config_builder, ChainConfigOptions}, ChainType, + regtest_options::{ChainConfigOptions, regtest_chain_config_builder}, }, }, primitives::semver::SemVer, @@ -42,9 +42,9 @@ use utils::{ use utils_networking::IpOrSocketAddress; use crate::{ + NodeType, checkpoints_from_file::read_checkpoints_from_csv_file, config_files::{NodeTypeConfigFile, StorageBackendConfigFile}, - NodeType, }; const CONFIG_NAME: &str = "config.toml"; @@ -449,7 +449,7 @@ mod tests { use common::{ chain::config::Checkpoints, - primitives::{BlockHeight, Id, Idable as _, H256}, + primitives::{BlockHeight, H256, Id, Idable as _}, }; use utils::concatln; diff --git a/node-lib/src/rpc.rs b/node-lib/src/rpc.rs index 80b012b710..87f02b84d4 100644 --- a/node-lib/src/rpc.rs +++ b/node-lib/src/rpc.rs @@ -18,7 +18,7 @@ use std::{sync::Arc, time::Duration}; use chainstate_launcher::ChainConfig; -use rpc::{description::Described, handle_result, RpcResult}; +use rpc::{RpcResult, description::Described, handle_result}; use subsystem::ShutdownTrigger; use utils::{app_version_with_git_info, tokio_spawn}; diff --git a/node-lib/src/runner.rs b/node-lib/src/runner.rs index 039ba3880e..e71a59de2d 100644 --- a/node-lib/src/runner.rs +++ b/node-lib/src/runner.rs @@ -21,15 +21,15 @@ use std::{ sync::Arc, }; -use anyhow::{anyhow, Context, Result}; -use file_rotate::{compression::Compression, suffix::AppendCount, ContentLimit, FileRotate}; +use anyhow::{Context, Result, anyhow}; +use file_rotate::{ContentLimit, FileRotate, compression::Compression, suffix::AppendCount}; use blockprod::rpc::BlockProductionRpcServer; -use chainstate::{rpc::ChainstateRpcServer, ChainstateError, InitializationError}; +use chainstate::{ChainstateError, InitializationError, rpc::ChainstateRpcServer}; use chainstate_launcher::{ChainConfig, StorageBackendConfig}; -use common::chain::config::{assert_no_ignore_consensus_in_chain_config, ChainType}; +use common::chain::config::{ChainType, assert_no_ignore_consensus_in_chain_config}; use logging::log; -use mempool::{rpc::MempoolRpcServer, MempoolInit}; +use mempool::{MempoolInit, rpc::MempoolRpcServer}; use p2p::{error::P2pError, rpc::P2pRpcServer}; use rpc::rpc_creds::RpcCreds; use test_rpc_functions::{ @@ -37,11 +37,11 @@ use test_rpc_functions::{ }; use crate::{ - config_files::{NodeConfigFile, DEFAULT_P2P_NETWORKING_ENABLED, DEFAULT_RPC_ENABLED}, + RpcConfigFile, + config_files::{DEFAULT_P2P_NETWORKING_ENABLED, DEFAULT_RPC_ENABLED, NodeConfigFile}, mock_time::set_mock_time, node_controller::NodeController, - options::{default_data_dir, OptionsWithResolvedCommand, RunOptions}, - RpcConfigFile, + options::{OptionsWithResolvedCommand, RunOptions, default_data_dir}, }; const LOCK_FILE_NAME: &str = ".lock"; @@ -397,7 +397,9 @@ async fn start( Some(ChainstateError::FailedToInitializeChainstate( InitializationError::StorageCompatibilityCheckError(e), )) => { - log::warn!("Failed to init chainstate: {e} \n Cleaning up current db and trying from scratch."); + log::warn!( + "Failed to init chainstate: {e} \n Cleaning up current db and trying from scratch." + ); let storage_config: StorageBackendConfig = node_config.chainstate.clone().unwrap_or_default().storage_backend.into(); diff --git a/node-lib/tests/cli.rs b/node-lib/tests/cli.rs index aa9e630689..8463a2ed4d 100644 --- a/node-lib/tests/cli.rs +++ b/node-lib/tests/cli.rs @@ -56,13 +56,15 @@ fn create_default_config() { None ); - assert!(config - .p2p - .clone() - .unwrap_or_default() - .bind_addresses - .unwrap_or_default() - .is_empty()); + assert!( + config + .p2p + .clone() + .unwrap_or_default() + .bind_addresses + .unwrap_or_default() + .is_empty() + ); assert_eq!( config.p2p.clone().unwrap_or_default().discouragement_threshold, None diff --git a/orders-accounting/src/cache.rs b/orders-accounting/src/cache.rs index e26f1cc9a0..e4f5a84c7e 100644 --- a/orders-accounting/src/cache.rs +++ b/orders-accounting/src/cache.rs @@ -24,7 +24,7 @@ use logging::log; use utils::{debug_panic_or_log, ensure}; use crate::{ - calculate_fill_order, + FlushableOrdersAccountingView, OrderData, OrdersAccountingDeltaUndoData, calculate_fill_order, data::OrdersAccountingDeltaData, error::{Error, Result}, operations::{ @@ -32,7 +32,6 @@ use crate::{ OrdersAccountingOperations, OrdersAccountingUndo, }, view::OrdersAccountingView, - FlushableOrdersAccountingView, OrderData, OrdersAccountingDeltaUndoData, }; pub struct OrdersAccountingCache

{ diff --git a/orders-accounting/src/data.rs b/orders-accounting/src/data.rs index 21a91b0c2e..e050fd4daa 100644 --- a/orders-accounting/src/data.rs +++ b/orders-accounting/src/data.rs @@ -17,7 +17,7 @@ use std::collections::BTreeMap; use accounting::{DeltaAmountCollection, DeltaDataCollection, DeltaDataUndoCollection}; use common::{ - chain::{output_value::OutputValue, Destination, OrderId}, + chain::{Destination, OrderId, output_value::OutputValue}, primitives::Amount, }; use serialization::{Decode, Encode}; diff --git a/orders-accounting/src/lib.rs b/orders-accounting/src/lib.rs index de7d1073ee..9eacee909c 100644 --- a/orders-accounting/src/lib.rs +++ b/orders-accounting/src/lib.rs @@ -30,8 +30,8 @@ pub use { operations::{OrdersAccountingOperations, OrdersAccountingUndo}, price_calculation::{calculate_fill_order, calculate_filled_amount}, storage::{ - db::OrdersAccountingDB, in_memory::InMemoryOrdersAccounting, OrdersAccountingStorageRead, - OrdersAccountingStorageWrite, + OrdersAccountingStorageRead, OrdersAccountingStorageWrite, db::OrdersAccountingDB, + in_memory::InMemoryOrdersAccounting, }, view::{FlushableOrdersAccountingView, OrdersAccountingView}, }; diff --git a/orders-accounting/src/operations.rs b/orders-accounting/src/operations.rs index 8ae549c359..524833c4d2 100644 --- a/orders-accounting/src/operations.rs +++ b/orders-accounting/src/operations.rs @@ -21,7 +21,7 @@ use common::{ use serialization::{Decode, Encode}; use strum::EnumCount; -use crate::{error::Result, OrderData}; +use crate::{OrderData, error::Result}; #[derive(Clone, Debug, PartialEq, Eq, Encode, Decode)] pub struct CreateOrderUndo { diff --git a/orders-accounting/src/price_calculation.rs b/orders-accounting/src/price_calculation.rs index 1391cf2244..8ad0d708fb 100644 --- a/orders-accounting/src/price_calculation.rs +++ b/orders-accounting/src/price_calculation.rs @@ -14,13 +14,13 @@ // limitations under the License. use common::{ + Uint256, chain::{OrderId, OrdersVersion}, primitives::Amount, - Uint256, }; use utils::ensure; -use crate::{error::Result, Error, OrdersAccountingView}; +use crate::{Error, OrdersAccountingView, error::Result}; pub fn calculate_fill_order( view: &impl OrdersAccountingView, @@ -114,7 +114,7 @@ mod tests { use super::*; use common::{ - chain::{output_value::OutputValue, tokens::TokenId, Destination}, + chain::{Destination, output_value::OutputValue, tokens::TokenId}, primitives::H256, }; use rstest::rstest; diff --git a/orders-accounting/src/storage/db.rs b/orders-accounting/src/storage/db.rs index cb3ebe1d6b..811ec12fa0 100644 --- a/orders-accounting/src/storage/db.rs +++ b/orders-accounting/src/storage/db.rs @@ -19,16 +19,16 @@ use std::{ }; use accounting::{ - combine_amount_delta, combine_data_with_delta, DeltaAmountCollection, DeltaDataUndoCollection, + DeltaAmountCollection, DeltaDataUndoCollection, combine_amount_delta, combine_data_with_delta, }; use common::{chain::OrderId, primitives::Amount}; use utils::tap_log::TapLog; use crate::{ + OrderData, data::{OrdersAccountingDeltaData, OrdersAccountingDeltaUndoData}, error::Error, view::{FlushableOrdersAccountingView, OrdersAccountingView}, - OrderData, }; use super::{OrdersAccountingStorageRead, OrdersAccountingStorageWrite}; diff --git a/orders-accounting/src/tests/operations.rs b/orders-accounting/src/tests/operations.rs index dbdd5cc5d1..c693e2ac75 100644 --- a/orders-accounting/src/tests/operations.rs +++ b/orders-accounting/src/tests/operations.rs @@ -19,16 +19,16 @@ use rstest::rstest; use accounting::GetDataResult; use common::{ - chain::{output_value::OutputValue, tokens::TokenId, Destination, OrderId, OrdersVersion}, + chain::{Destination, OrderId, OrdersVersion, output_value::OutputValue, tokens::TokenId}, primitives::Amount, }; use randomness::{Rng, RngExt as _}; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use crate::{ + Error, InMemoryOrdersAccounting, OrderData, OrdersAccountingDB, OrdersAccountingView, cache::OrdersAccountingCache, operations::OrdersAccountingOperations, - view::FlushableOrdersAccountingView, Error, InMemoryOrdersAccounting, OrderData, - OrdersAccountingDB, OrdersAccountingView, + view::FlushableOrdersAccountingView, }; fn make_order_data(rng: &mut impl Rng) -> OrderData { diff --git a/p2p/backend-test-suite/src/ban.rs b/p2p/backend-test-suite/src/ban.rs index a1c8d81076..87dc983a4d 100644 --- a/p2p/backend-test-suite/src/ban.rs +++ b/p2p/backend-test-suite/src/ban.rs @@ -17,23 +17,23 @@ use std::{fmt::Debug, sync::Arc}; use tokio::sync::{mpsc, oneshot}; -use chainstate::{ban_score::BanScore, BlockError, ChainstateError, CheckBlockError}; +use chainstate::{BlockError, ChainstateError, CheckBlockError, ban_score::BanScore}; use common::{ - chain::block::{timestamp::BlockTimestamp, Block, BlockReward, ConsensusData}, + chain::block::{Block, BlockReward, ConsensusData, timestamp::BlockTimestamp}, primitives::Idable, time_getter::TimeGetter, }; use networking::test_helpers::TestTransportMaker; use p2p::{ + PeerManagerEvent, error::P2pError, message::{BlockSyncMessage, HeaderList}, net::{ - types::SyncingEvent, ConnectivityService, MessagingService, NetworkingService, - SyncingEventReceiver, + ConnectivityService, MessagingService, NetworkingService, SyncingEventReceiver, + types::SyncingEvent, }, sync::SyncManager, test_helpers::{connect_and_accept_services, test_p2p_config}, - PeerManagerEvent, }; use utils::{atomics::SeqCstAtomicBool, tokio_spawn_in_current_tracing_span}; diff --git a/p2p/backend-test-suite/src/block_announcement.rs b/p2p/backend-test-suite/src/block_announcement.rs index 7c55551873..816b8219da 100644 --- a/p2p/backend-test-suite/src/block_announcement.rs +++ b/p2p/backend-test-suite/src/block_announcement.rs @@ -18,8 +18,8 @@ use std::{fmt::Debug, sync::Arc}; use tokio::sync::{mpsc, oneshot}; use common::{ - chain::block::{consensus_data::ConsensusData, timestamp::BlockTimestamp, Block, BlockReward}, - primitives::{user_agent::mintlayer_core_user_agent, Id, H256}, + chain::block::{Block, BlockReward, consensus_data::ConsensusData, timestamp::BlockTimestamp}, + primitives::{H256, Id, user_agent::mintlayer_core_user_agent}, time_getter::TimeGetter, }; use networking::test_helpers::TestTransportMaker; @@ -27,8 +27,8 @@ use p2p::{ config::{NodeType, P2pConfig}, message::{BlockSyncMessage, HeaderList}, net::{ - types::SyncingEvent, ConnectivityService, MessagingService, NetworkingService, - SyncingEventReceiver, + ConnectivityService, MessagingService, NetworkingService, SyncingEventReceiver, + types::SyncingEvent, }, test_helpers::{connect_and_accept_services, test_p2p_config}, }; diff --git a/p2p/backend-test-suite/src/events.rs b/p2p/backend-test-suite/src/events.rs index 3e000f2681..7e26083b1e 100644 --- a/p2p/backend-test-suite/src/events.rs +++ b/p2p/backend-test-suite/src/events.rs @@ -26,12 +26,12 @@ use tokio::{ use networking::test_helpers::TestTransportMaker; use p2p::{ + P2pEvent, net::{ - types::services::Service, ConnectivityService, MessagingService, NetworkingService, - SyncingEventReceiver, + ConnectivityService, MessagingService, NetworkingService, SyncingEventReceiver, + types::services::Service, }, test_helpers::{connect_and_accept_services, test_p2p_config}, - P2pEvent, }; use utils::atomics::SeqCstAtomicBool; diff --git a/p2p/benches/benches.rs b/p2p/benches/benches.rs index 9445bbb0d8..1c7dd81308 100644 --- a/p2p/benches/benches.rs +++ b/p2p/benches/benches.rs @@ -16,7 +16,7 @@ use std::{collections::BTreeSet, sync::Arc, time::Duration}; use common::chain::config::create_unit_test_config; -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; use networking::test_helpers::TestAddressMaker; use p2p::{ diff --git a/p2p/src/disconnection_reason.rs b/p2p/src/disconnection_reason.rs index c9c0af8c12..c004fbcc0a 100644 --- a/p2p/src/disconnection_reason.rs +++ b/p2p/src/disconnection_reason.rs @@ -257,8 +257,8 @@ impl DisconnectionReason { mod tests { use common::{ chain::{ - output_value::OutputValue, signature::inputsig::InputWitness, SignedTransaction, - Transaction, TxInput, TxOutput, + SignedTransaction, Transaction, TxInput, TxOutput, output_value::OutputValue, + signature::inputsig::InputWitness, }, primitives::{Amount, VersionTag}, }; diff --git a/p2p/src/error.rs b/p2p/src/error.rs index 1ced1c0d88..33abc2e482 100644 --- a/p2p/src/error.rs +++ b/p2p/src/error.rs @@ -15,14 +15,14 @@ use thiserror::Error; -use chainstate::{ban_score::BanScore, ChainstateError}; +use chainstate::{ChainstateError, ban_score::BanScore}; use common::{ - chain::{config::MagicBytes, Block, Transaction}, - primitives::{semver::SemVer, time::Time, Id}, + chain::{Block, Transaction, config::MagicBytes}, + primitives::{Id, semver::SemVer, time::Time}, }; use mempool::error::{Error as MempoolError, MempoolBanScore}; use networking::error::{MessageCodecError, NetworkingError}; -use p2p_types::{services::Services, socket_address::SocketAddress, PeerId}; +use p2p_types::{PeerId, services::Services, socket_address::SocketAddress}; use utils::try_as::TryAsRef; use crate::{net::types::PeerRole, peer_manager::peerdb_common, protocol::ProtocolVersion}; @@ -141,7 +141,9 @@ pub enum ConnectionValidationError { }, #[error("Networking disabled")] NetworkingDisabled, - #[error("Minimum peer software version not satisfied, min version = {min_version}, actual = {actual_version}")] + #[error( + "Minimum peer software version not satisfied, min version = {min_version}, actual = {actual_version}" + )] MinPeerSoftwareVersionNotSatisfied { min_version: SemVer, actual_version: SemVer, diff --git a/p2p/src/interface/p2p_interface_impl.rs b/p2p/src/interface/p2p_interface_impl.rs index 9e2574c783..bd5887f8d4 100644 --- a/p2p/src/interface/p2p_interface_impl.rs +++ b/p2p/src/interface/p2p_interface_impl.rs @@ -24,6 +24,7 @@ use p2p_types::{bannable_address::BannableAddress, socket_address::SocketAddress use utils_networking::IpOrSocketAddress; use crate::{ + MessagingService, P2p, P2pEvent, PeerManagerEvent, disconnection_reason::DisconnectionReason, error::P2pError, interface::{p2p_interface::P2pInterface, types::ConnectedPeer}, @@ -31,7 +32,6 @@ use crate::{ peer_manager_event::PeerDisconnectionDbAction, types::peer_id::PeerId, utils::oneshot_nofail, - MessagingService, P2p, P2pEvent, PeerManagerEvent, }; #[async_trait::async_trait] diff --git a/p2p/src/interface/p2p_interface_impl_delegation.rs b/p2p/src/interface/p2p_interface_impl_delegation.rs index 9f97ba7ebb..4d9af5d906 100644 --- a/p2p/src/interface/p2p_interface_impl_delegation.rs +++ b/p2p/src/interface/p2p_interface_impl_delegation.rs @@ -24,7 +24,7 @@ use mempool::tx_options::TxOptionsOverrides; use p2p_types::{bannable_address::BannableAddress, socket_address::SocketAddress}; use utils_networking::IpOrSocketAddress; -use crate::{types::peer_id::PeerId, P2pEvent}; +use crate::{P2pEvent, types::peer_id::PeerId}; use super::{p2p_interface::P2pInterface, types::ConnectedPeer}; diff --git a/p2p/src/lib.rs b/p2p/src/lib.rs index 8b2f18e738..16e48ad46c 100644 --- a/p2p/src/lib.rs +++ b/p2p/src/lib.rs @@ -45,7 +45,7 @@ use tokio::{ use ::utils::{atomics::SeqCstAtomicBool, ensure, tokio_spawn_in_current_tracing_span}; use common::{ - chain::{config::ChainType, ChainConfig}, + chain::{ChainConfig, config::ChainType}, primitives::BlockHeight, time_getter::TimeGetter, }; @@ -64,8 +64,8 @@ use crate::{ config::P2pConfig, error::P2pError, net::{ - default_backend::DefaultNetworkingService, ConnectivityService, MessagingService, - NetworkingService, SyncingEventReceiver, + ConnectivityService, MessagingService, NetworkingService, SyncingEventReceiver, + default_backend::DefaultNetworkingService, }, }; diff --git a/p2p/src/message.rs b/p2p/src/message.rs index fb91ecd506..9c5bfadf38 100644 --- a/p2p/src/message.rs +++ b/p2p/src/message.rs @@ -16,8 +16,8 @@ use chainstate::Locator; use common::{ chain::{ - block::{signed_block_header::SignedBlockHeader, Block}, SignedTransaction, Transaction, + block::{Block, signed_block_header::SignedBlockHeader}, }, primitives::Id, }; diff --git a/p2p/src/net/default_backend/backend.rs b/p2p/src/net/default_backend/backend.rs index e5c9946ef0..453571df39 100644 --- a/p2p/src/net/default_backend/backend.rs +++ b/p2p/src/net/default_backend/backend.rs @@ -19,12 +19,12 @@ use std::{collections::HashMap, sync::Arc}; -use futures::{future::BoxFuture, never::Never, stream::FuturesUnordered, FutureExt}; +use futures::{FutureExt, future::BoxFuture, never::Never, stream::FuturesUnordered}; use tokio::{ sync::{mpsc, oneshot}, time::timeout, }; -use tokio_stream::{wrappers::ReceiverStream, StreamExt, StreamMap}; +use tokio_stream::{StreamExt, StreamMap, wrappers::ReceiverStream}; use common::{ chain::ChainConfig, @@ -34,13 +34,14 @@ use common::{ use logging::log; use networking::transport::{ConnectedSocketInfo, TransportListener, TransportSocket}; use p2p_types::socket_address::SocketAddress; -use randomness::{make_pseudo_rng, RngExt as _}; +use randomness::{RngExt as _, make_pseudo_rng}; use utils::{ atomics::SeqCstAtomicBool, eventhandler::EventsController, set_flag::SetFlag, shallow_clone::ShallowClone, tokio_spawn_in_current_tracing_span, }; use crate::{ + P2pEvent, P2pEventHandler, config::P2pConfig, disconnection_reason::DisconnectionReason, error::{DialError, P2pError, PeerError}, @@ -50,17 +51,16 @@ use crate::{ types::{BackendEvent, BackendObserver, Command, PeerEvent}, }, types::{ - services::Services, ConnectivityEvent, PeerInfo, PeerManagerMessageExt, SyncingEvent, + ConnectivityEvent, PeerInfo, PeerManagerMessageExt, SyncingEvent, services::Services, }, }, protocol::{ProtocolVersion, SupportedProtocolVersion}, types::{peer_address::PeerAddress, peer_id::PeerId}, - P2pEvent, P2pEventHandler, }; use super::{ peer::ConnectionInfo, - types::{peer_event, HandshakeNonce, Message}, + types::{HandshakeNonce, Message, peer_event}, }; /// Buffer sizes for the channels used by Peer to send peer messages to other parts of p2p. diff --git a/p2p/src/net/default_backend/default_networking_service.rs b/p2p/src/net/default_backend/default_networking_service.rs index efc79637fb..8b5fa5a074 100644 --- a/p2p/src/net/default_backend/default_networking_service.rs +++ b/p2p/src/net/default_backend/default_networking_service.rs @@ -28,13 +28,13 @@ use p2p_types::socket_address::SocketAddress; use utils::{atomics::SeqCstAtomicBool, tokio_spawn_in_tracing_span}; use crate::{ + P2pConfig, P2pEventHandler, error::P2pError, - net::{default_backend::types::BackendObserver, NetworkingService}, + net::{NetworkingService, default_backend::types::BackendObserver}, protocol::{ProtocolVersion, SupportedProtocolVersion}, - P2pConfig, P2pEventHandler, }; -use super::{backend::Backend, ConnectivityHandle, MessagingHandle, SyncingEventReceiver}; +use super::{ConnectivityHandle, MessagingHandle, SyncingEventReceiver, backend::Backend}; // The preferred protocol version. // Note that we intentionally keep this constant private, because most of the code should diff --git a/p2p/src/net/default_backend/mod.rs b/p2p/src/net/default_backend/mod.rs index 5af7d88e53..9202cc4917 100644 --- a/p2p/src/net/default_backend/mod.rs +++ b/p2p/src/net/default_backend/mod.rs @@ -31,9 +31,8 @@ use crate::{ error::P2pError, message::{BlockSyncMessage, PeerManagerMessage, TransactionSyncMessage}, net::{ - self, + self, ConnectivityService, MessagingService, NetworkingService, types::{ConnectivityEvent, SyncingEvent}, - ConnectivityService, MessagingService, NetworkingService, }, types::peer_id::PeerId, }; diff --git a/p2p/src/net/default_backend/peer/handshake_handler.rs b/p2p/src/net/default_backend/peer/handshake_handler.rs index b83c42a82a..0c05b12ed8 100644 --- a/p2p/src/net/default_backend/peer/handshake_handler.rs +++ b/p2p/src/net/default_backend/peer/handshake_handler.rs @@ -30,11 +30,11 @@ use crate::{ config::P2pConfig, disconnection_reason::DisconnectionReason, error::{ConnectionValidationError, P2pError, PeerError, ProtocolError}, - net::default_backend::types::{peer_event, HandshakeMessage, Message, P2pTimestamp, PeerEvent}, - protocol::{choose_common_protocol_version, ProtocolVersion, SupportedProtocolVersion}, + net::default_backend::types::{HandshakeMessage, Message, P2pTimestamp, PeerEvent, peer_event}, + protocol::{ProtocolVersion, SupportedProtocolVersion, choose_common_protocol_version}, }; -use super::{maybe_send_will_disconnect, ConnectionInfo}; +use super::{ConnectionInfo, maybe_send_will_disconnect}; /// The chosen common protocol version; available only after the handshake has completed. pub struct CommonProtocolVersion(pub SupportedProtocolVersion); diff --git a/p2p/src/net/default_backend/peer/mod.rs b/p2p/src/net/default_backend/peer/mod.rs index 3f54fd49fb..0d467133a8 100644 --- a/p2p/src/net/default_backend/peer/mod.rs +++ b/p2p/src/net/default_backend/peer/mod.rs @@ -30,8 +30,8 @@ use logging::log; use networking::{ error::NetworkingError, transport::{ - new_message_stream, ConnectedSocketInfo, MessageReader, MessageWriter, PeerStream, - TransportSocket, + ConnectedSocketInfo, MessageReader, MessageWriter, PeerStream, TransportSocket, + new_message_stream, }, }; use p2p_types::{peer_address::PeerAddress, services::Services, socket_addr_ext::SocketAddrExt}; @@ -54,7 +54,7 @@ use crate::{ types::peer_id::PeerId, }; -use super::types::{can_send_will_disconnect, CategorizedMessage, HandshakeNonce, Message}; +use super::types::{CategorizedMessage, HandshakeNonce, Message, can_send_will_disconnect}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ConnectionInfo { diff --git a/p2p/src/net/default_backend/peer/tests.rs b/p2p/src/net/default_backend/peer/tests.rs index fb3b9f5164..701b3717a5 100644 --- a/p2p/src/net/default_backend/peer/tests.rs +++ b/p2p/src/net/default_backend/peer/tests.rs @@ -24,8 +24,8 @@ use chainstate::Locator; use common::chain::config::MagicBytes; use networking::{ test_helpers::{ - get_two_connected_sockets, TestTransportChannel, TestTransportMaker, TestTransportNoise, - TestTransportTcp, + TestTransportChannel, TestTransportMaker, TestTransportNoise, TestTransportTcp, + get_two_connected_sockets, }, transport::{MpscChannelTransport, NoiseTcpTransport, TcpTransportSocket}, }; @@ -39,10 +39,10 @@ use crate::{ error::ConnectionValidationError, message::HeaderListRequest, net::{ - default_backend::types::{peer_event, HandshakeMessage, P2pTimestamp}, + default_backend::types::{HandshakeMessage, P2pTimestamp, peer_event}, types::services::Service, }, - test_helpers::{test_p2p_config, TEST_PROTOCOL_VERSION}, + test_helpers::{TEST_PROTOCOL_VERSION, test_p2p_config}, }; use super::*; @@ -119,19 +119,21 @@ where let (mut socket2_reader, mut socket2_writer) = new_message_stream(socket2, Some(*p2p_config.protocol_config.max_message_size)); assert!(socket2_reader.recv().now_or_never().is_none()); - assert!(socket2_writer - .send(Message::Handshake(HandshakeMessage::Hello { - protocol_version: TEST_PROTOCOL_VERSION.into(), - software_version: *chain_config.software_version(), - network: *chain_config.magic_bytes(), - user_agent: p2p_config.user_agent.clone(), - services: [Service::Blocks, Service::Transactions].as_slice().into(), - receiver_address: None, - current_time: P2pTimestamp::from_int_seconds(123456), - handshake_nonce: 123, - })) - .await - .is_ok()); + assert!( + socket2_writer + .send(Message::Handshake(HandshakeMessage::Hello { + protocol_version: TEST_PROTOCOL_VERSION.into(), + software_version: *chain_config.software_version(), + network: *chain_config.magic_bytes(), + user_agent: p2p_config.user_agent.clone(), + services: [Service::Blocks, Service::Transactions].as_slice().into(), + receiver_address: None, + current_time: P2pTimestamp::from_int_seconds(123456), + handshake_nonce: 123, + })) + .await + .is_ok() + ); expect_peer_info_received_event( &mut peer_event_receiver, @@ -208,18 +210,20 @@ where let (mut socket2_reader, mut socket2_writer) = new_message_stream(socket2, Some(*p2p_config.protocol_config.max_message_size)); socket2_reader.recv().await.unwrap(); - assert!(socket2_writer - .send(Message::Handshake(HandshakeMessage::HelloAck { - protocol_version: TEST_PROTOCOL_VERSION.into(), - software_version: *chain_config.software_version(), - network: *chain_config.magic_bytes(), - user_agent: p2p_config.user_agent.clone(), - services: [Service::Blocks, Service::Transactions].as_slice().into(), - receiver_address: None, - current_time: P2pTimestamp::from_int_seconds(123456), - })) - .await - .is_ok()); + assert!( + socket2_writer + .send(Message::Handshake(HandshakeMessage::HelloAck { + protocol_version: TEST_PROTOCOL_VERSION.into(), + software_version: *chain_config.software_version(), + network: *chain_config.magic_bytes(), + user_agent: p2p_config.user_agent.clone(), + services: [Service::Blocks, Service::Transactions].as_slice().into(), + receiver_address: None, + current_time: P2pTimestamp::from_int_seconds(123456), + })) + .await + .is_ok() + ); expect_peer_info_received_event( &mut peer_event_receiver, @@ -291,19 +295,21 @@ where let (mut socket2_reader, mut socket2_writer) = new_message_stream(socket2, Some(*p2p_config.protocol_config.max_message_size)); assert!(socket2_reader.recv().now_or_never().is_none()); - assert!(socket2_writer - .send(Message::Handshake(HandshakeMessage::Hello { - protocol_version: TEST_PROTOCOL_VERSION.into(), - software_version: *chain_config.software_version(), - network: MagicBytes::new([1, 2, 3, 4]), - user_agent: p2p_config.user_agent.clone(), - services: [Service::Blocks, Service::Transactions].as_slice().into(), - receiver_address: None, - current_time: P2pTimestamp::from_int_seconds(cur_time.load()), - handshake_nonce: 123, - })) - .await - .is_ok()); + assert!( + socket2_writer + .send(Message::Handshake(HandshakeMessage::Hello { + protocol_version: TEST_PROTOCOL_VERSION.into(), + software_version: *chain_config.software_version(), + network: MagicBytes::new([1, 2, 3, 4]), + user_agent: p2p_config.user_agent.clone(), + services: [Service::Blocks, Service::Transactions].as_slice().into(), + receiver_address: None, + current_time: P2pTimestamp::from_int_seconds(cur_time.load()), + handshake_nonce: 123, + })) + .await + .is_ok() + ); expect_some_peer_info_received_event(&mut peer_event_receiver).await; expect_sync_event(&mut peer_event_receiver).await; diff --git a/p2p/src/net/default_backend/tests.rs b/p2p/src/net/default_backend/tests.rs index f47cb89759..e2f82b8b94 100644 --- a/p2p/src/net/default_backend/tests.rs +++ b/p2p/src/net/default_backend/tests.rs @@ -41,8 +41,9 @@ use crate::{ config::NodeType, error::{DialError, P2pError}, net::{ + ConnectivityService, NetworkingService, default_backend::default_networking_service::get_preferred_protocol_version_for_tests, - types::ConnectivityEvent, ConnectivityService, NetworkingService, + types::ConnectivityEvent, }, protocol::{ProtocolVersion, SupportedProtocolVersion}, test_helpers::test_p2p_config, diff --git a/p2p/src/net/default_backend/types.rs b/p2p/src/net/default_backend/types.rs index 33e9e5aede..bf327e5d61 100644 --- a/p2p/src/net/default_backend/types.rs +++ b/p2p/src/net/default_backend/types.rs @@ -18,8 +18,8 @@ use std::time::Duration; use tokio::sync::{mpsc::Sender, oneshot}; use common::{ - chain::{config::MagicBytes, Transaction}, - primitives::{semver::SemVer, time::Time, user_agent::UserAgent, Id, Idable as _}, + chain::{Transaction, config::MagicBytes}, + primitives::{Id, Idable as _, semver::SemVer, time::Time, user_agent::UserAgent}, }; use p2p_types::socket_address::SocketAddress; use serialization::{Decode, Encode}; @@ -33,7 +33,7 @@ use crate::{ BlockSyncMessage, HeaderList, HeaderListRequest, PeerManagerMessage, PingRequest, PingResponse, TransactionResponse, TransactionSyncMessage, WillDisconnectMessage, }, - net::types::{services::Services, PeerManagerMessageExt}, + net::types::{PeerManagerMessageExt, services::Services}, protocol::{ProtocolVersion, SupportedProtocolVersion}, types::{peer_address::PeerAddress, peer_id::PeerId}, }; @@ -427,10 +427,10 @@ mod tests { use chainstate_test_framework::TestFramework; use common::{ chain::config::MagicBytes, - primitives::{semver::SemVer, Id}, + primitives::{Id, semver::SemVer}, }; - use networking::test_helpers::{get_two_connected_sockets, TestTransportChannel}; - use networking::transport::{new_message_stream, MpscChannelTransport}; + use networking::test_helpers::{TestTransportChannel, get_two_connected_sockets}; + use networking::transport::{MpscChannelTransport, new_message_stream}; use p2p_types::services::Service; use randomness::RngExt; use test_utils::random::Seed; @@ -550,16 +550,18 @@ mod tests { }), Message::AddrListRequest(AddrListRequest {}), Message::AddrListResponse(AddrListResponse { - addresses: vec![SocketAddr::new( - IpAddr::V4(Ipv4Addr::new( - rng.random(), - rng.random(), - rng.random(), + addresses: vec![ + SocketAddr::new( + IpAddr::V4(Ipv4Addr::new( + rng.random(), + rng.random(), + rng.random(), + rng.random(), + )), rng.random(), - )), - rng.random(), - ) - .into()], + ) + .into(), + ], }), ]; diff --git a/p2p/src/net/mod.rs b/p2p/src/net/mod.rs index 10fda32f05..71c9b04189 100644 --- a/p2p/src/net/mod.rs +++ b/p2p/src/net/mod.rs @@ -32,11 +32,10 @@ use tokio::{ use utils::atomics::SeqCstAtomicBool; use crate::{ - config, + P2pEventHandler, config, disconnection_reason::DisconnectionReason, message::{BlockSyncMessage, PeerManagerMessage, TransactionSyncMessage}, types::peer_id::PeerId, - P2pEventHandler, }; /// [NetworkingService] provides the low-level network interface diff --git a/p2p/src/net/types.rs b/p2p/src/net/types.rs index ddc7cf90dc..79704b8aa9 100644 --- a/p2p/src/net/types.rs +++ b/p2p/src/net/types.rs @@ -18,20 +18,20 @@ pub use crate::types::services; use std::fmt::{Debug, Display}; use common::{ - chain::{config::MagicBytes, ChainConfig}, + chain::{ChainConfig, config::MagicBytes}, primitives::{semver::SemVer, user_agent::UserAgent}, }; use p2p_types::socket_address::SocketAddress; use tokio::sync::mpsc::Receiver; use crate::{ + P2pError, error::ConnectionValidationError, message::{ BlockSyncMessage, PeerManagerMessage, PeerManagerMessageTag, TransactionSyncMessage, }, protocol::SupportedProtocolVersion, types::{peer_address::PeerAddress, peer_id::PeerId}, - P2pError, }; use self::services::Services; diff --git a/p2p/src/peer_manager/dns_seed.rs b/p2p/src/peer_manager/dns_seed.rs index b3dd05f138..08382f0616 100644 --- a/p2p/src/peer_manager/dns_seed.rs +++ b/p2p/src/peer_manager/dns_seed.rs @@ -20,7 +20,7 @@ use async_trait::async_trait; use common::chain::ChainConfig; use logging::log; use p2p_types::{peer_address::PeerAddress, socket_address::SocketAddress}; -use randomness::{seq::IteratorRandom, Rng}; +use randomness::{Rng, seq::IteratorRandom}; use crate::config::P2pConfig; diff --git a/p2p/src/peer_manager/mod.rs b/p2p/src/peer_manager/mod.rs index a820023036..62a56f1623 100644 --- a/p2p/src/peer_manager/mod.rs +++ b/p2p/src/peer_manager/mod.rs @@ -38,13 +38,13 @@ use tokio::sync::mpsc; use chainstate::ban_score::BanScore; use common::{ chain::ChainConfig, - primitives::time::{duration_to_int, Time}, + primitives::time::{Time, duration_to_int}, time_getter::TimeGetter, }; use logging::log; use networking::types::ConnectionDirection; -use p2p_types::{bannable_address::BannableAddress, socket_address::SocketAddress, IsGlobalIp}; -use randomness::{seq::IteratorRandom, BoxedRngMutexWrapper, Rng, RngExt as _}; +use p2p_types::{IsGlobalIp, bannable_address::BannableAddress, socket_address::SocketAddress}; +use randomness::{BoxedRngMutexWrapper, Rng, RngExt as _, seq::IteratorRandom}; use utils::{ bloom_filters::rolling_bloom_filter::RollingBloomFilter, debug_panic_or_log, ensure, set_flag::SetFlag, @@ -52,6 +52,7 @@ use utils::{ use utils_networking::IpOrSocketAddress; use crate::{ + PeerManagerEvent, config::P2pConfig, disconnection_reason::DisconnectionReason, error::{ConnectionValidationError, P2pError, PeerError, ProtocolError}, @@ -61,11 +62,11 @@ use crate::{ PingResponse, WillDisconnectMessage, }, net::{ + ConnectivityService, NetworkingService, types::{ - services::{Service, Services}, ConnectivityEvent, PeerInfo, PeerManagerMessageExt, PeerManagerMessageExtTag, PeerRole, + services::{Service, Services}, }, - ConnectivityService, NetworkingService, }, peer_manager_event::PeerDisconnectionDbAction, sync::sync_status::PeerBlockSyncStatus, @@ -74,7 +75,6 @@ use crate::{ peer_id::PeerId, }, utils::{oneshot_nofail, rate_limiter::RateLimiter}, - PeerManagerEvent, }; use self::{ @@ -732,8 +732,12 @@ where }; let peer_role: PeerRole = (&outbound_connect_type).into(); - log::debug!("Trying a new outbound connection, address: {:?}, local_services_override: {:?}, peer_role: {:?}", - address, local_services_override, peer_role); + log::debug!( + "Trying a new outbound connection, address: {:?}, local_services_override: {:?}, peer_role: {:?}", + address, + local_services_override, + peer_role + ); let res = self.try_connect(address, local_services_override, peer_role); match res { @@ -886,14 +890,18 @@ where >= *self.p2p_config.peer_manager_config.max_inbound_connections { if self.peerdb.is_address_discouraged(&address.as_bannable()) { - log::info!("Rejecting inbound connection from a discouraged address - too many peers"); + log::info!( + "Rejecting inbound connection from a discouraged address - too many peers" + ); return Err(P2pError::ConnectionValidationFailed( ConnectionValidationError::TooManyInboundPeersAndThisOneIsDiscouraged, )); } if !self.try_evict_random_inbound_connection() { - log::info!("Rejecting inbound connection - too many peers and none of them can be evicted"); + log::info!( + "Rejecting inbound connection - too many peers and none of them can be evicted" + ); return Err(P2pError::ConnectionValidationFailed( ConnectionValidationError::TooManyInboundPeersAndCannotEvictAnyone, )); @@ -1840,7 +1848,9 @@ where new_status: status, } => { if let Some(peer) = self.peers.get_mut(&peer_id) { - log::debug!("Block sync status update received from peer {peer_id}, new status is {status:?}"); + log::debug!( + "Block sync status update received from peer {peer_id}, new status is {status:?}" + ); peer.block_sync_status = status; } } diff --git a/p2p/src/peer_manager/peerdb/address_data/tests.rs b/p2p/src/peer_manager/peerdb/address_data/tests.rs index 89f2b7cd2f..2d39450c4a 100644 --- a/p2p/src/peer_manager/peerdb/address_data/tests.rs +++ b/p2p/src/peer_manager/peerdb/address_data/tests.rs @@ -18,11 +18,11 @@ use strum::IntoEnumIterator as _; use logging::log; use randomness::{ + RngExt as _, distributions::{Distribution, WeightedIndex}, seq::IteratorRandom as _, - RngExt as _, }; -use test_utils::random::{make_seedable_rng, Seed, StepRng}; +use test_utils::random::{Seed, StepRng, make_seedable_rng}; use super::*; @@ -123,7 +123,9 @@ fn next_connect_time_test_impl(rng: &mut impl Rng) { for fail_count in [0, u32::MAX] { for connections_without_activity_count in [0, u32::MAX] { - log::debug!("fail_count = {fail_count}, connections_without_activity_count = {connections_without_activity_count}"); + log::debug!( + "fail_count = {fail_count}, connections_without_activity_count = {connections_without_activity_count}" + ); let time = AddressData::next_connect_time( start_time, diff --git a/p2p/src/peer_manager/peerdb/address_tables/table.rs b/p2p/src/peer_manager/peerdb/address_tables/table.rs index 1a592a9945..9f2871af66 100644 --- a/p2p/src/peer_manager/peerdb/address_tables/table.rs +++ b/p2p/src/peer_manager/peerdb/address_tables/table.rs @@ -13,7 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::{btree_map, BTreeMap}; +use std::collections::{BTreeMap, btree_map}; use p2p_types::socket_address::SocketAddress; use utils::array_2d::Array2d; @@ -259,7 +259,7 @@ impl Table { #[cfg(test)] pub mod test_utils { use std::{ - collections::{btree_map::Entry, BTreeSet}, + collections::{BTreeSet, btree_map::Entry}, net::{Ipv4Addr, SocketAddr, SocketAddrV4}, }; @@ -383,7 +383,7 @@ pub mod test_utils { mod tests { use rstest::rstest; - use ::test_utils::random::{make_seedable_rng, Seed}; + use ::test_utils::random::{Seed, make_seedable_rng}; use super::{test_utils::*, *}; diff --git a/p2p/src/peer_manager/peerdb/mod.rs b/p2p/src/peer_manager/peerdb/mod.rs index 4463b8b77e..767fd884e6 100644 --- a/p2p/src/peer_manager/peerdb/mod.rs +++ b/p2p/src/peer_manager/peerdb/mod.rs @@ -33,7 +33,7 @@ pub mod storage_impl; mod storage_load; use std::{ - collections::{btree_map::Entry, BTreeMap, BTreeSet}, + collections::{BTreeMap, BTreeSet, btree_map::Entry}, sync::Arc, time::Duration, }; @@ -41,7 +41,7 @@ use std::{ use common::{chain::ChainConfig, primitives::time::Time, time_getter::TimeGetter}; use logging::log; use p2p_types::{bannable_address::BannableAddress, socket_address::SocketAddress}; -use randomness::{seq::IteratorRandom, Rng, RngExt as _, SliceRandom}; +use randomness::{Rng, RngExt as _, SliceRandom, seq::IteratorRandom}; use crate::{config::P2pConfig, net::types::OutboundPeerRole}; @@ -58,7 +58,7 @@ use super::{ peerdb_common::storage::update_db, }; -pub use storage_load::{open_storage, CURRENT_STORAGE_VERSION}; +pub use storage_load::{CURRENT_STORAGE_VERSION, open_storage}; pub struct PeerDb { /// P2P configuration @@ -166,7 +166,9 @@ impl PeerDb { if let Entry::Vacant(entry) = addresses.entry(*addr) { let discarded_addr = address_tables.force_add_to_new(addr); if let Some(discarded_addr) = discarded_addr { - log::info!("Previously loaded 'new' address {discarded_addr} replaced with boot address {addr} when loading PeerDb"); + log::info!( + "Previously loaded 'new' address {discarded_addr} replaced with boot address {addr} when loading PeerDb" + ); } entry.insert(AddressData::new(false, false, now)); diff --git a/p2p/src/peer_manager/peerdb/storage_impl.rs b/p2p/src/peer_manager/peerdb/storage_impl.rs index 4764e70231..05bf141e95 100644 --- a/p2p/src/peer_manager/peerdb/storage_impl.rs +++ b/p2p/src/peer_manager/peerdb/storage_impl.rs @@ -17,14 +17,14 @@ use std::time::Duration; use common::primitives::time::Time; use p2p_types::{bannable_address::BannableAddress, socket_address::SocketAddress}; -use serialization::{encoded::Encoded, DecodeAll, Encode}; +use serialization::{DecodeAll, Encode, encoded::Encoded}; use storage::MakeMapRef; use crate::{ error::P2pError, peer_manager::peerdb_common::{ - storage_impl::{StorageImpl, StorageTxRo, StorageTxRw}, StorageVersion, + storage_impl::{StorageImpl, StorageTxRo, StorageTxRw}, }, }; diff --git a/p2p/src/peer_manager/peerdb/tests.rs b/p2p/src/peer_manager/peerdb/tests.rs index 191682a35a..1b3c88385c 100644 --- a/p2p/src/peer_manager/peerdb/tests.rs +++ b/p2p/src/peer_manager/peerdb/tests.rs @@ -25,13 +25,13 @@ use rstest::rstest; use strum::IntoEnumIterator as _; use ::test_utils::{ - random::{make_seedable_rng, Seed}, BasicTestTimeGetter, + random::{Seed, make_seedable_rng}, }; use common::{chain::config::create_unit_test_config, primitives::time::Time}; use networking::test_helpers::TestAddressMaker; use p2p_types::socket_addr_ext::SocketAddrExt; -use randomness::{seq::IteratorRandom as _, Rng, RngExt as _}; +use randomness::{Rng, RngExt as _, seq::IteratorRandom as _}; use crate::{ ban_config::BanConfig, @@ -51,13 +51,13 @@ use crate::{ }; use super::{ + PeerDb, address_tables::{ table::Table, test_utils::{make_non_colliding_addresses, make_random_address}, }, config::PeerDbConfig, storage::PeerDbStorage, - PeerDb, }; // Ban the peer, check that it's banned. diff --git a/p2p/src/peer_manager/peers_eviction/mod.rs b/p2p/src/peer_manager/peers_eviction/mod.rs index bce604cb05..f8ffd18803 100644 --- a/p2p/src/peer_manager/peers_eviction/mod.rs +++ b/p2p/src/peer_manager/peers_eviction/mod.rs @@ -16,7 +16,7 @@ use std::{collections::BTreeMap, hash::Hasher, time::Duration}; use common::primitives::time::Time; -use randomness::{seq::IteratorRandom, Rng, RngExt as _}; +use randomness::{Rng, RngExt as _, seq::IteratorRandom}; use utils::make_config_setting; use crate::{net::types::PeerRole, types::peer_id::PeerId}; diff --git a/p2p/src/peer_manager/tests/addr_list_response_caching.rs b/p2p/src/peer_manager/tests/addr_list_response_caching.rs index 66af4d4f56..11d1ba1641 100644 --- a/p2p/src/peer_manager/tests/addr_list_response_caching.rs +++ b/p2p/src/peer_manager/tests/addr_list_response_caching.rs @@ -29,28 +29,26 @@ use p2p_test_utils::expect_recv; use p2p_types::peer_address::PeerAddress; use randomness::{Rng, RngExt as _}; use test_utils::{ - assert_matches_return_val, - random::{make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches_return_val, + random::{Seed, make_seedable_rng}, }; use crate::{ config::{NodeType, P2pConfig}, message::AddrListResponse, net::{ + ConnectivityService, NetworkingService, default_backend::{ - types::{Command, Message}, DefaultNetworkingService, + types::{Command, Message}, }, types::PeerInfo, - ConnectivityService, NetworkingService, }, peer_manager::{ - addr_list_response_cache, + PeerManager, addr_list_response_cache, peerdb::{ address_tables::table::test_utils::make_non_colliding_addresses, storage::PeerDbStorage, }, - PeerManager, }, protocol::ProtocolConfig, test_helpers::TEST_PROTOCOL_VERSION, diff --git a/p2p/src/peer_manager/tests/addresses.rs b/p2p/src/peer_manager/tests/addresses.rs index fc1b7ee134..bd710b2bb8 100644 --- a/p2p/src/peer_manager/tests/addresses.rs +++ b/p2p/src/peer_manager/tests/addresses.rs @@ -20,10 +20,10 @@ use std::{ }; use rstest::rstest; -use tokio::sync::mpsc::{error::TryRecvError, UnboundedReceiver, UnboundedSender}; +use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, error::TryRecvError}; use common::{ - chain::{self, config, ChainConfig}, + chain::{self, ChainConfig, config}, primitives::user_agent::mintlayer_core_user_agent, }; use logging::log; @@ -40,37 +40,35 @@ use p2p_types::{ }; use randomness::{Rng, RngExt as _}; use test_utils::{ - assert_matches, - random::{make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches, + random::{Seed, make_seedable_rng}, }; use utils::tokio_spawn_in_current_tracing_span; use crate::{ + PeerManagerEvent, config::{NodeType, P2pConfig}, error::{DialError, P2pError}, message::{AddrListRequest, AnnounceAddrRequest, PeerManagerMessage}, net::{ + ConnectivityService, NetworkingService, default_backend::{ - types::{CategorizedMessage, Command, Message}, ConnectivityHandle, DefaultNetworkingService, + types::{CategorizedMessage, Command, Message}, }, types::{ConnectivityEvent, PeerInfo}, - ConnectivityService, NetworkingService, }, peer_manager::{ - self, + self, DNS_SEED_QUERY_INTERVAL, OutboundConnectType, PeerManager, tests::{ make_peer_manager_custom, utils::{cmd_to_peer_man_msg, expect_cmd_connect_to, make_full_relay_peer_info}, }, - OutboundConnectType, PeerManager, DNS_SEED_QUERY_INTERVAL, }, - test_helpers::{peerdb_inmemory_store, test_p2p_config, TEST_PROTOCOL_VERSION}, + test_helpers::{TEST_PROTOCOL_VERSION, peerdb_inmemory_store, test_p2p_config}, tests::helpers::TestDnsSeed, types::peer_id::PeerId, utils::oneshot_nofail, - PeerManagerEvent, }; fn get_new_discoverable_address(rng: &mut impl Rng) -> PeerAddress { diff --git a/p2p/src/peer_manager/tests/ban.rs b/p2p/src/peer_manager/tests/ban.rs index eb2ee53c93..d6a064aadd 100644 --- a/p2p/src/peer_manager/tests/ban.rs +++ b/p2p/src/peer_manager/tests/ban.rs @@ -22,8 +22,8 @@ use networking::test_helpers::{TestAddressMaker, TestTransportMaker, TestTranspo use p2p_test_utils::{expect_no_recv, expect_recv, wait_for_no_recv}; use randomness::RngExt as _; use test_utils::{ - random::{make_seedable_rng, Seed}, BasicTestTimeGetter, + random::{Seed, make_seedable_rng}, }; use utils::tokio_spawn_in_current_tracing_span; @@ -37,6 +37,7 @@ use crate::{ types::ConnectivityEvent, }, peer_manager::{ + MAX_ADDR_RATE_PER_SECOND, config::PeerManagerConfig, peerdb::test_utils::make_non_colliding_addresses_for_peer_db_in_distinct_addr_groups, tests::{ @@ -49,7 +50,6 @@ use crate::{ wait_for_heartbeat, }, }, - MAX_ADDR_RATE_PER_SECOND, }, test_helpers::{ test_p2p_config, test_p2p_config_with_ban_config, test_p2p_config_with_peer_mgr_config, diff --git a/p2p/src/peer_manager/tests/connections.rs b/p2p/src/peer_manager/tests/connections.rs index d89e497b49..0d6e15da01 100644 --- a/p2p/src/peer_manager/tests/connections.rs +++ b/p2p/src/peer_manager/tests/connections.rs @@ -40,28 +40,28 @@ use p2p_test_utils::{expect_no_recv, expect_recv, run_with_timeout}; use p2p_types::socket_address::SocketAddress; use randomness::{Rng, RngExt as _}; use test_utils::{ - random::{make_seedable_rng, Seed}, BasicTestTimeGetter, + random::{Seed, make_seedable_rng}, }; use utils::{atomics::SeqCstAtomicBool, tokio_spawn_in_current_tracing_span}; use utils_networking::IpOrSocketAddress; use crate::{ + PeerManagerEvent, config::{BackendTimeoutsConfig, P2pConfig}, disconnection_reason::DisconnectionReason, error::{ConnectionValidationError, DialError, P2pError, ProtocolError}, message::AddrListRequest, net::{ - self, + self, ConnectivityService, NetworkingService, default_backend::{ - types::{Command, Message}, ConnectivityHandle, DefaultNetworkingService, + types::{Command, Message}, }, - types::{services::Service, ConnectivityEvent, PeerInfo, PeerRole}, - ConnectivityService, NetworkingService, + types::{ConnectivityEvent, PeerInfo, PeerRole, services::Service}, }, peer_manager::{ - self, + self, PeerManager, config::{MaxInboundConnections, PeerManagerConfig}, peerdb::{ self, config::PeerDbConfig, @@ -76,17 +76,15 @@ use crate::{ query_peer_manager, recv_command_advance_time, start_manually_connecting, }, }, - PeerManager, }, test_helpers::{ - connect_and_accept_services, connect_services, get_connectivity_event, - make_transport_with_local_addr_in_group, peerdb_inmemory_store, test_p2p_config, - test_p2p_config_with_peer_mgr_config, TEST_PROTOCOL_VERSION, + TEST_PROTOCOL_VERSION, connect_and_accept_services, connect_services, + get_connectivity_event, make_transport_with_local_addr_in_group, peerdb_inmemory_store, + test_p2p_config, test_p2p_config_with_peer_mgr_config, }, tests::helpers::TestPeersInfo, types::peer_id::PeerId, utils::oneshot_nofail, - PeerManagerEvent, }; async fn validate_invalid_connection(seed: Seed) @@ -2071,7 +2069,7 @@ async fn feeler_connections_test_impl(seed: Seed) { mod feeler_connections_test_utils { use crate::peer_manager::{ config::PeerManagerConfig, - peerdb::{salt::Salt, storage::PeerDbStorage, PeerDb}, + peerdb::{PeerDb, salt::Salt, storage::PeerDbStorage}, }; use super::*; diff --git a/p2p/src/peer_manager/tests/discouragement.rs b/p2p/src/peer_manager/tests/discouragement.rs index 0146c9b00b..69221f17af 100644 --- a/p2p/src/peer_manager/tests/discouragement.rs +++ b/p2p/src/peer_manager/tests/discouragement.rs @@ -22,8 +22,8 @@ use networking::test_helpers::{TestAddressMaker, TestTransportMaker, TestTranspo use p2p_test_utils::{expect_no_recv, expect_recv, wait_for_no_recv}; use randomness::RngExt as _; use test_utils::{ - random::{make_seedable_rng, Seed}, BasicTestTimeGetter, + random::{Seed, make_seedable_rng}, }; use utils::tokio_spawn_in_current_tracing_span; @@ -37,6 +37,7 @@ use crate::{ types::ConnectivityEvent, }, peer_manager::{ + MAX_ADDR_RATE_PER_SECOND, config::PeerManagerConfig, peerdb::test_utils::make_non_colliding_addresses_for_peer_db_in_distinct_addr_groups, tests::{ @@ -49,7 +50,6 @@ use crate::{ wait_for_heartbeat, }, }, - MAX_ADDR_RATE_PER_SECOND, }, test_helpers::{ test_p2p_config_with_ban_config, test_p2p_config_with_peer_mgr_config, diff --git a/p2p/src/peer_manager/tests/eviction.rs b/p2p/src/peer_manager/tests/eviction.rs index 78a1029750..7462342c51 100644 --- a/p2p/src/peer_manager/tests/eviction.rs +++ b/p2p/src/peer_manager/tests/eviction.rs @@ -18,25 +18,27 @@ use std::{collections::BTreeSet, sync::Arc, time::Duration}; use rstest::rstest; use common::{ - chain::{config, Block}, - primitives::{user_agent::mintlayer_core_user_agent, Id}, Uint256, + chain::{Block, config}, + primitives::{Id, user_agent::mintlayer_core_user_agent}, }; use logging::log; use networking::test_helpers::{TestTransportMaker, TestTransportTcp}; use p2p_test_utils::{expect_no_recv, expect_recv}; use randomness::RngExt as _; use test_utils::{ - random::{make_seedable_rng, Seed}, BasicTestTimeGetter, + random::{Seed, make_seedable_rng}, }; use utils::tokio_spawn_in_current_tracing_span; use crate::{ + PeerManagerEvent, config::P2pConfig, disconnection_reason::DisconnectionReason, net::default_backend::types::Command, peer_manager::{ + HEARTBEAT_INTERVAL_MAX, config::PeerManagerConfig, peerdb::{self, config::PeerDbConfig, salt::Salt}, peers_eviction, @@ -44,10 +46,8 @@ use crate::{ make_standalone_peer_manager, utils::{expect_cmd_connect_to_one_of, outbound_block_relay_peer_accepted_by_backend}, }, - HEARTBEAT_INTERVAL_MAX, }, sync::sync_status::PeerBlockSyncStatus, - PeerManagerEvent, }; // 1) Setup the peer manager so that it must open 3 block relay connections, 1 of which is diff --git a/p2p/src/peer_manager/tests/mod.rs b/p2p/src/peer_manager/tests/mod.rs index 01ff85da88..6afadf4c3e 100644 --- a/p2p/src/peer_manager/tests/mod.rs +++ b/p2p/src/peer_manager/tests/mod.rs @@ -44,19 +44,19 @@ use randomness::{Rng, RngExt as _}; use test_utils::assert_matches_return_val; use crate::{ + P2pConfig, P2pEventHandler, PeerManagerEvent, interface::types::ConnectedPeer, message::{PeerManagerMessage, PingRequest, PingResponse}, net::{ - default_backend::{types::Command, ConnectivityHandle, DefaultNetworkingService}, - types::ConnectivityEvent, ConnectivityService, NetworkingService, + default_backend::{ConnectivityHandle, DefaultNetworkingService, types::Command}, + types::ConnectivityEvent, }, peer_manager::PeerManager, test_helpers::{peerdb_inmemory_store, test_p2p_config}, tests::helpers::{PeerManagerNotification, PeerManagerObserverImpl}, types::peer_id::PeerId, utils::oneshot_nofail, - P2pConfig, P2pEventHandler, PeerManagerEvent, }; use self::utils::cmd_to_peer_man_msg; diff --git a/p2p/src/peer_manager/tests/peer_types.rs b/p2p/src/peer_manager/tests/peer_types.rs index 87581e347f..bbda9e2001 100644 --- a/p2p/src/peer_manager/tests/peer_types.rs +++ b/p2p/src/peer_manager/tests/peer_types.rs @@ -21,16 +21,17 @@ use strum::IntoEnumIterator as _; use common::{chain::config, primitives::user_agent::mintlayer_core_user_agent}; use networking::transport::TcpTransportSocket; use p2p_types::{ - services::{Service, Services}, PeerId, + services::{Service, Services}, }; use randomness::RngExt as _; use test_utils::{ - random::{make_seedable_rng, Seed}, BasicTestTimeGetter, + random::{Seed, make_seedable_rng}, }; use crate::{ + PeerManagerEvent, config::{NodeType, P2pConfig}, error::{ConnectionValidationError, P2pError}, net::{ @@ -38,8 +39,7 @@ use crate::{ types::{PeerInfo, PeerRole}, }, peer_manager::PeerManager, - test_helpers::{peerdb_inmemory_store, TEST_PROTOCOL_VERSION}, - PeerManagerEvent, + test_helpers::{TEST_PROTOCOL_VERSION, peerdb_inmemory_store}, }; #[tracing::instrument(skip(seed))] diff --git a/p2p/src/peer_manager/tests/ping.rs b/p2p/src/peer_manager/tests/ping.rs index c3d0a082e8..0f27716e58 100644 --- a/p2p/src/peer_manager/tests/ping.rs +++ b/p2p/src/peer_manager/tests/ping.rs @@ -25,27 +25,26 @@ use networking::{ use p2p_test_utils::expect_recv; use randomness::RngExt as _; use test_utils::{ - assert_matches, assert_matches_return_val, - random::{make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches, assert_matches_return_val, + random::{Seed, make_seedable_rng}, }; use utils::tokio_spawn_in_current_tracing_span; use crate::{ + PeerManagerEvent, config::{NodeType, P2pConfig}, disconnection_reason::DisconnectionReason, message::{PeerManagerMessage, PingRequest, PingResponse}, net::{ - default_backend::{types::Command, ConnectivityHandle, DefaultNetworkingService}, + default_backend::{ConnectivityHandle, DefaultNetworkingService, types::Command}, types::{ConnectivityEvent, PeerInfo}, }, peer_manager::{ - tests::{send_and_sync, utils::cmd_to_peer_man_msg}, PeerManager, + tests::{send_and_sync, utils::cmd_to_peer_man_msg}, }, - test_helpers::{peerdb_inmemory_store, TEST_PROTOCOL_VERSION}, + test_helpers::{TEST_PROTOCOL_VERSION, peerdb_inmemory_store}, types::peer_id::PeerId, - PeerManagerEvent, }; #[tracing::instrument(skip(seed))] diff --git a/p2p/src/peer_manager/tests/unsuccessful_connection_counter_update.rs b/p2p/src/peer_manager/tests/unsuccessful_connection_counter_update.rs index a27281cd9c..e0afe898db 100644 --- a/p2p/src/peer_manager/tests/unsuccessful_connection_counter_update.rs +++ b/p2p/src/peer_manager/tests/unsuccessful_connection_counter_update.rs @@ -23,8 +23,8 @@ use tokio::sync::mpsc; use common::{ chain::{ - config::{self}, ChainConfig, + config::{self}, }, primitives::time::Time, }; @@ -34,13 +34,13 @@ use p2p_test_utils::{expect_no_recv, expect_recv}; use p2p_types::socket_address::SocketAddress; use randomness::RngExt; use test_utils::{ - assert_matches, assert_matches_return_val, - random::{make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches, assert_matches_return_val, + random::{Seed, make_seedable_rng}, }; use utils::tokio_spawn_in_current_tracing_span; use crate::{ + PeerManagerEvent, config::P2pConfig, disconnection_reason::DisconnectionReason, error::{DialError, P2pError}, @@ -65,7 +65,6 @@ use crate::{ test_helpers::test_p2p_config_with_peer_mgr_config, tests::helpers::PeerManagerNotification, types::peer_id::PeerId, - PeerManagerEvent, }; // Check the case of an automatic connection failure when the peer address would end up in the diff --git a/p2p/src/peer_manager/tests/utils.rs b/p2p/src/peer_manager/tests/utils.rs index 19e202a6c6..12d1e89a2e 100644 --- a/p2p/src/peer_manager/tests/utils.rs +++ b/p2p/src/peer_manager/tests/utils.rs @@ -21,12 +21,13 @@ use common::{chain::ChainConfig, primitives::user_agent::mintlayer_core_user_age use logging::log; use p2p_test_utils::wait_for_recv; use p2p_types::{ - bannable_address::BannableAddress, services::Service, socket_address::SocketAddress, PeerId, + PeerId, bannable_address::BannableAddress, services::Service, socket_address::SocketAddress, }; -use test_utils::{assert_matches_return_val, BasicTestTimeGetter}; +use test_utils::{BasicTestTimeGetter, assert_matches_return_val}; use utils_networking::IpOrSocketAddress; use crate::{ + PeerManagerEvent, config::NodeType, message::PeerManagerMessage, net::{ @@ -37,7 +38,6 @@ use crate::{ test_helpers::TEST_PROTOCOL_VERSION, tests::helpers::PeerManagerNotification, utils::oneshot_nofail, - PeerManagerEvent, }; pub fn cmd_to_peer_man_msg(cmd: Command) -> (PeerId, PeerManagerMessage) { diff --git a/p2p/src/peer_manager/tests/whitelist.rs b/p2p/src/peer_manager/tests/whitelist.rs index 45a41ad460..598b15618f 100644 --- a/p2p/src/peer_manager/tests/whitelist.rs +++ b/p2p/src/peer_manager/tests/whitelist.rs @@ -29,29 +29,29 @@ use networking::{ use p2p_types::{bannable_address::BannableAddress, socket_address::SocketAddress}; use randomness::RngExt as _; use test_utils::{ - random::{make_seedable_rng, Seed}, BasicTestTimeGetter, + random::{Seed, make_seedable_rng}, }; use utils::atomics::SeqCstAtomicBool; use crate::{ + PeerManagerEvent, config::{NodeType, P2pConfig}, disconnection_reason::DisconnectionReason, net::{ - default_backend::{types::Command, ConnectivityHandle, DefaultNetworkingService}, - types::{PeerInfo, PeerRole}, ConnectivityService, NetworkingService, + default_backend::{ConnectivityHandle, DefaultNetworkingService, types::Command}, + types::{PeerInfo, PeerRole}, }, peer_manager::{ - peerdb::{salt::Salt, storage::PeerDbStorageWrite, CURRENT_STORAGE_VERSION}, + PeerManager, + peerdb::{CURRENT_STORAGE_VERSION, salt::Salt, storage::PeerDbStorageWrite}, peerdb_common::storage::{TransactionRw, Transactional}, tests::{make_peer_manager, make_peer_manager_custom}, - PeerManager, }, - test_helpers::{connect_services, peerdb_inmemory_store, TEST_PROTOCOL_VERSION}, + test_helpers::{TEST_PROTOCOL_VERSION, connect_services, peerdb_inmemory_store}, types::peer_id::PeerId, utils::oneshot_nofail, - PeerManagerEvent, }; fn p2p_config_with_whitelisted(whitelisted_addresses: Vec) -> P2pConfig { diff --git a/p2p/src/peer_manager_event.rs b/p2p/src/peer_manager_event.rs index fc81a94149..24290a7e94 100644 --- a/p2p/src/peer_manager_event.rs +++ b/p2p/src/peer_manager_event.rs @@ -17,7 +17,7 @@ use std::time::Duration; use common::{ chain::{Block, GenBlock, Transaction}, - primitives::{time::Time, Id}, + primitives::{Id, time::Time}, }; use p2p_types::{bannable_address::BannableAddress, socket_address::SocketAddress}; use utils_networking::IpOrSocketAddress; diff --git a/p2p/src/sync/mod.rs b/p2p/src/sync/mod.rs index a43acb4652..8649541f37 100644 --- a/p2p/src/sync/mod.rs +++ b/p2p/src/sync/mod.rs @@ -33,25 +33,25 @@ use tokio::{ use tracing::Instrument; use common::{ - chain::{config::ChainConfig, GenBlock, Transaction}, + chain::{GenBlock, Transaction, config::ChainConfig}, primitives::Id, time_getter::TimeGetter, }; use logging::log; -use mempool::{event::TransactionProcessed, tx_origin::TxOrigin, MempoolHandle}; +use mempool::{MempoolHandle, event::TransactionProcessed, tx_origin::TxOrigin}; use utils::{sync::Arc, tap_log::TapLog, tokio_spawn_in_join_set}; use crate::{ + PeerManagerEvent, Result, config::P2pConfig, error::P2pError, message::{BlockSyncMessage, TransactionSyncMessage}, net::{ - types::{services::Services, SyncingEvent}, MessagingService, NetworkingService, SyncingEventReceiver, + types::{SyncingEvent, services::Services}, }, protocol::SupportedProtocolVersion, types::peer_id::PeerId, - PeerManagerEvent, Result, }; use self::chainstate_handle::ChainstateHandle; diff --git a/p2p/src/sync/peer/block_manager.rs b/p2p/src/sync/peer/block_manager.rs index 3ceb1900c3..66940f681f 100644 --- a/p2p/src/sync/peer/block_manager.rs +++ b/p2p/src/sync/peer/block_manager.rs @@ -22,15 +22,15 @@ use itertools::Itertools; use tokio::sync::mpsc::{Receiver, UnboundedReceiver, UnboundedSender}; use chainstate::{ - chainstate_interface::ChainstateInterface, BlockIndex, BlockSource, GenBlockIndex, - GenBlockIndexRef, Locator, + BlockIndex, BlockSource, GenBlockIndex, GenBlockIndexRef, Locator, + chainstate_interface::ChainstateInterface, }; use common::{ chain::{ - block::{signed_block_header::SignedBlockHeader, timestamp::BlockTimestamp}, Block, ChainConfig, GenBlock, + block::{signed_block_header::SignedBlockHeader, timestamp::BlockTimestamp}, }, - primitives::{time::Time, BlockHeight, Id, Idable}, + primitives::{BlockHeight, Id, Idable, time::Time}, time_getter::TimeGetter, }; use logging::log; @@ -40,16 +40,18 @@ use utils::{ }; use crate::{ + MessagingService, PeerManagerEvent, Result, config::P2pConfig, disconnection_reason::DisconnectionReason, error::{P2pError, PeerError, ProtocolError, SyncError}, message::{BlockListRequest, BlockResponse, BlockSyncMessage, HeaderList, HeaderListRequest}, net::{ - types::services::{Service, Services}, NetworkingService, + types::services::{Service, Services}, }, peer_manager_event::PeerDisconnectionDbAction, sync::{ + LocalEvent, chainstate_handle::ChainstateHandle, peer_activity::PeerActivity, peer_common::{ @@ -57,11 +59,9 @@ use crate::{ handle_message_processing_result, }, sync_status::PeerBlockSyncStatus, - LocalEvent, }, types::peer_id::PeerId, utils::oneshot_nofail, - MessagingService, PeerManagerEvent, Result, }; // TODO: Take into account the chain work when syncing. @@ -994,8 +994,11 @@ where // Nodes can disconnect each other if all of them are in the initial block download state, // but this should never occur in a normal network and can be worked around in the tests. let (sender, receiver) = oneshot_nofail::channel(); - log::warn!("Disconnecting the peer for ignoring requests, headers_req_stalling = {}, blocks_req_stalling = {}", - headers_req_stalling, blocks_req_stalling); + log::warn!( + "Disconnecting the peer for ignoring requests, headers_req_stalling = {}, blocks_req_stalling = {}", + headers_req_stalling, + blocks_req_stalling + ); self.peer_mgr_event_sender.send(PeerManagerEvent::Disconnect( self.id(), PeerDisconnectionDbAction::Keep, diff --git a/p2p/src/sync/peer/pending_transactions.rs b/p2p/src/sync/peer/pending_transactions.rs index 2d93f27c18..f0efb3608f 100644 --- a/p2p/src/sync/peer/pending_transactions.rs +++ b/p2p/src/sync/peer/pending_transactions.rs @@ -59,7 +59,7 @@ mod tests { use common::primitives::H256; use rstest::rstest; - use test_utils::random::{make_seedable_rng, RngExt as _, Seed}; + use test_utils::random::{RngExt as _, Seed, make_seedable_rng}; #[rstest] #[trace] diff --git a/p2p/src/sync/peer/requested_transactions.rs b/p2p/src/sync/peer/requested_transactions.rs index 5a4bae3998..aaacaf3f32 100644 --- a/p2p/src/sync/peer/requested_transactions.rs +++ b/p2p/src/sync/peer/requested_transactions.rs @@ -17,7 +17,7 @@ use std::{collections::BTreeMap, time::Duration}; use common::{ chain::Transaction, - primitives::{time::Time, Id}, + primitives::{Id, time::Time}, time_getter::TimeGetter, }; diff --git a/p2p/src/sync/peer/transaction_manager.rs b/p2p/src/sync/peer/transaction_manager.rs index 58ba513bb8..2e66aa51ff 100644 --- a/p2p/src/sync/peer/transaction_manager.rs +++ b/p2p/src/sync/peer/transaction_manager.rs @@ -32,20 +32,20 @@ use utils::const_value::ConstValue; use utils::sync::Arc; use crate::{ + MessagingService, PeerManagerEvent, Result, config::P2pConfig, error::{P2pError, ProtocolError}, message::{TransactionResponse, TransactionSyncMessage}, net::{ - types::services::{Service, Services}, NetworkingService, + types::services::{Service, Services}, }, sync::{ - chainstate_handle::ChainstateHandle, - peer_common::{handle_message_processing_result, KnownTransactions}, BoxedObserver, LocalEvent, + chainstate_handle::ChainstateHandle, + peer_common::{KnownTransactions, handle_message_processing_result}, }, types::peer_id::PeerId, - MessagingService, PeerManagerEvent, Result, }; use super::{ @@ -350,7 +350,9 @@ where // in such a situation. Note that after certain time, older requests will be purged // from requested_transactions, after which we'll start to handle peer's tx // announcements again. - log::warn!("Ignoring announcement for tx {tx} because requested_transactions is over the limit"); + log::warn!( + "Ignoring announcement for tx {tx} because requested_transactions is over the limit" + ); return Ok(()); } diff --git a/p2p/src/sync/peer_common/mod.rs b/p2p/src/sync/peer_common/mod.rs index 23ab5fdbc6..2f8e79e27b 100644 --- a/p2p/src/sync/peer_common/mod.rs +++ b/p2p/src/sync/peer_common/mod.rs @@ -16,7 +16,7 @@ mod known_transactions; use chainstate::{ - ban_score::BanScore, chainstate_interface::ChainstateInterface, GenBlockIndex, GenBlockIndexRef, + GenBlockIndex, GenBlockIndexRef, ban_score::BanScore, chainstate_interface::ChainstateInterface, }; use common::{chain::GenBlock, primitives::Id}; use logging::log; @@ -25,9 +25,9 @@ use p2p_types::PeerId; use tokio::sync::mpsc::UnboundedSender; use crate::{ + PeerManagerEvent, Result, error::{P2pError, PeerError}, utils::oneshot_nofail, - PeerManagerEvent, Result, }; pub use known_transactions::KnownTransactions; diff --git a/p2p/src/sync/tests/ban_scores.rs b/p2p/src/sync/tests/ban_scores.rs index 6ada9c448c..f50ba5981d 100644 --- a/p2p/src/sync/tests/ban_scores.rs +++ b/p2p/src/sync/tests/ban_scores.rs @@ -15,20 +15,20 @@ use tokio::sync::mpsc::unbounded_channel; -use chainstate::{ban_score::BanScore, BlockError, BlockSource, ChainstateError, CheckBlockError}; -use chainstate_test_framework::{empty_witness, TestFramework, TransactionBuilder}; +use chainstate::{BlockError, BlockSource, ChainstateError, CheckBlockError, ban_score::BanScore}; +use chainstate_test_framework::{TestFramework, TransactionBuilder, empty_witness}; use common::{ + Uint256, chain::{ - self, output_value::OutputValue, ChainConfig, GenBlock, OutPointSourceId, TxInput, TxOutput, + self, ChainConfig, GenBlock, OutPointSourceId, TxInput, TxOutput, output_value::OutputValue, }, - primitives::{Amount, BlockHeight, Id, Idable, H256}, - Uint256, + primitives::{Amount, BlockHeight, H256, Id, Idable}, }; use consensus::{ConsensusPoSError, ConsensusVerificationError}; use mempool::error::MempoolPolicyError; use p2p_test_utils::create_n_blocks; use randomness::RngExt; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use utils::tokio_spawn_in_current_tracing_span; use crate::{ diff --git a/p2p/src/sync/tests/block_announcement.rs b/p2p/src/sync/tests/block_announcement.rs index bf3c78238e..644de28eaa 100644 --- a/p2p/src/sync/tests/block_announcement.rs +++ b/p2p/src/sync/tests/block_announcement.rs @@ -15,21 +15,22 @@ use std::sync::Arc; -use chainstate::{ban_score::BanScore, BlockError, ChainstateError, CheckBlockError}; +use chainstate::{BlockError, ChainstateError, CheckBlockError, ban_score::BanScore}; use chainstate_test_framework::TestFramework; use common::{ chain::{ - block::{timestamp::BlockTimestamp, BlockReward, ConsensusData}, - config::{create_unit_test_config, Builder as ChainConfigBuilder, ChainType}, Block, NetUpgrades, + block::{BlockReward, ConsensusData, timestamp::BlockTimestamp}, + config::{Builder as ChainConfigBuilder, ChainType, create_unit_test_config}, }, - primitives::{user_agent::mintlayer_core_user_agent, Idable}, + primitives::{Idable, user_agent::mintlayer_core_user_agent}, }; use consensus::ConsensusVerificationError; use logging::log; -use test_utils::{random::Seed, BasicTestTimeGetter}; +use test_utils::{BasicTestTimeGetter, random::Seed}; use crate::{ + P2pError, config::P2pConfig, error::ProtocolError, message::{BlockListRequest, BlockResponse, BlockSyncMessage, HeaderList, HeaderListRequest}, @@ -37,7 +38,6 @@ use crate::{ sync::tests::helpers::TestNode, test_helpers::{for_each_protocol_version, test_p2p_config}, types::peer_id::PeerId, - P2pError, }; use super::helpers::{make_new_blocks, make_new_top_blocks_return_headers}; @@ -106,10 +106,10 @@ async fn invalid_timestamp() { BlockReward::new(Vec::new()), ) .unwrap(); - peer.send_block_sync_message(BlockSyncMessage::HeaderList(HeaderList::new(vec![block - .header() - .clone()]))) - .await; + peer.send_block_sync_message(BlockSyncMessage::HeaderList(HeaderList::new(vec![ + block.header().clone(), + ]))) + .await; let (adjusted_peer, score) = node.receive_adjust_peer_score_event().await; assert_eq!(peer.get_id(), adjusted_peer); @@ -156,10 +156,10 @@ async fn invalid_consensus_data() { BlockReward::new(Vec::new()), ) .unwrap(); - peer.send_block_sync_message(BlockSyncMessage::HeaderList(HeaderList::new(vec![block - .header() - .clone()]))) - .await; + peer.send_block_sync_message(BlockSyncMessage::HeaderList(HeaderList::new(vec![ + block.header().clone(), + ]))) + .await; let (adjusted_peer, score) = node.receive_adjust_peer_score_event().await; assert_eq!(peer.get_id(), adjusted_peer); @@ -251,10 +251,10 @@ async fn valid_block(#[case] seed: Seed) { let peer = node.connect_peer(PeerId::new(), protocol_version).await; - peer.send_block_sync_message(BlockSyncMessage::HeaderList(HeaderList::new(vec![block - .header() - .clone()]))) - .await; + peer.send_block_sync_message(BlockSyncMessage::HeaderList(HeaderList::new(vec![ + block.header().clone(), + ]))) + .await; let (sent_to, message) = node.get_sent_block_sync_message().await; assert_eq!(sent_to, peer.get_id()); diff --git a/p2p/src/sync/tests/block_list_request.rs b/p2p/src/sync/tests/block_list_request.rs index 197581ab6e..2d9caa3c6d 100644 --- a/p2p/src/sync/tests/block_list_request.rs +++ b/p2p/src/sync/tests/block_list_request.rs @@ -15,24 +15,24 @@ use std::{iter, sync::Arc}; -use chainstate::{ban_score::BanScore, BlockSource}; +use chainstate::{BlockSource, ban_score::BanScore}; use chainstate_test_framework::TestFramework; use common::{ - chain::{config::create_unit_test_config, Block}, + chain::{Block, config::create_unit_test_config}, primitives::{Id, Idable}, }; use logging::log; use p2p_test_utils::create_n_blocks; use randomness::RngExt; -use test_utils::{random::Seed, BasicTestTimeGetter}; +use test_utils::{BasicTestTimeGetter, random::Seed}; use crate::{ + P2pError, error::ProtocolError, message::{BlockListRequest, BlockResponse, BlockSyncMessage}, - sync::tests::helpers::{make_new_blocks, TestNode}, + sync::tests::helpers::{TestNode, make_new_blocks}, test_helpers::{for_each_protocol_version, test_p2p_config}, types::peer_id::PeerId, - P2pError, }; #[tracing::instrument(skip(seed))] diff --git a/p2p/src/sync/tests/block_response.rs b/p2p/src/sync/tests/block_response.rs index 8155827dcc..d970f3d490 100644 --- a/p2p/src/sync/tests/block_response.rs +++ b/p2p/src/sync/tests/block_response.rs @@ -23,26 +23,26 @@ use chainstate::ban_score::BanScore; use chainstate_test_framework::TestFramework; use common::{ chain::config::create_unit_test_config, - primitives::{user_agent::mintlayer_core_user_agent, Idable}, + primitives::{Idable, user_agent::mintlayer_core_user_agent}, }; use logging::log; use p2p_test_utils::create_n_blocks; use randomness::RngExt; use test_utils::{ - random::{shuffle_until_different, Seed}, BasicTestTimeGetter, + random::{Seed, shuffle_until_different}, }; use crate::{ + P2pConfig, P2pError, PeerManagerEvent, ban_config::BanConfig, error::ProtocolError, message::{BlockListRequest, BlockResponse, BlockSyncMessage, HeaderList, HeaderListRequest}, sync::tests::helpers::{ - make_new_blocks, make_new_top_blocks_return_headers, PeerManagerEventDesc, TestNode, + PeerManagerEventDesc, TestNode, make_new_blocks, make_new_top_blocks_return_headers, }, test_helpers::{for_each_protocol_version, test_p2p_config}, types::peer_id::PeerId, - P2pConfig, P2pError, PeerManagerEvent, }; #[tracing::instrument(skip(seed))] @@ -314,10 +314,10 @@ async fn disconnect(#[case] seed: Seed) { let peer = node.connect_peer(PeerId::new(), protocol_version).await; - peer.send_block_sync_message(BlockSyncMessage::HeaderList(HeaderList::new(vec![block - .header() - .clone()]))) - .await; + peer.send_block_sync_message(BlockSyncMessage::HeaderList(HeaderList::new(vec![ + block.header().clone(), + ]))) + .await; let (sent_to, message) = node.get_sent_block_sync_message().await; assert_eq!(peer.get_id(), sent_to); @@ -391,10 +391,10 @@ async fn slow_response(#[case] seed: Seed) { let peer = node.connect_peer(PeerId::new(), protocol_version).await; - peer.send_block_sync_message(BlockSyncMessage::HeaderList(HeaderList::new(vec![block - .header() - .clone()]))) - .await; + peer.send_block_sync_message(BlockSyncMessage::HeaderList(HeaderList::new(vec![ + block.header().clone(), + ]))) + .await; let (sent_to, message) = node.get_sent_block_sync_message().await; assert_eq!(peer.get_id(), sent_to); diff --git a/p2p/src/sync/tests/header_list_request.rs b/p2p/src/sync/tests/header_list_request.rs index 0fb5307547..3614282236 100644 --- a/p2p/src/sync/tests/header_list_request.rs +++ b/p2p/src/sync/tests/header_list_request.rs @@ -17,21 +17,21 @@ use std::{iter, sync::Arc, time::Duration}; use itertools::Itertools as _; -use chainstate::{ban_score::BanScore, Locator}; +use chainstate::{Locator, ban_score::BanScore}; use chainstate_test_framework::TestFramework; use common::{ chain::config::create_unit_test_config, - primitives::{user_agent::mintlayer_core_user_agent, Idable}, + primitives::{Idable, user_agent::mintlayer_core_user_agent}, }; use logging::log; use randomness::RngExt as _; use test_utils::{ - assert_matches_return_val, - random::{make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches_return_val, + random::{Seed, make_seedable_rng}, }; use crate::{ + P2pError, config::P2pConfig, error::ProtocolError, message::{BlockListRequest, BlockResponse, BlockSyncMessage, HeaderList, HeaderListRequest}, @@ -40,7 +40,6 @@ use crate::{ sync::tests::helpers::TestNode, test_helpers::{for_each_protocol_version, test_p2p_config_with_protocol_config}, types::peer_id::PeerId, - P2pError, }; #[tracing::instrument(skip(seed))] @@ -172,11 +171,12 @@ async fn respond_with_empty_header_list_when_in_ibd() { .await; // Node must be in Initial Download State - assert!(node - .chainstate() - .call(|chainstate| chainstate.is_initial_block_download()) - .await - .unwrap()); + assert!( + node.chainstate() + .call(|chainstate| chainstate.is_initial_block_download()) + .await + .unwrap() + ); let peer = node.connect_peer(PeerId::new(), protocol_version).await; diff --git a/p2p/src/sync/tests/header_list_response.rs b/p2p/src/sync/tests/header_list_response.rs index 0aeee888c1..4cf8b4b121 100644 --- a/p2p/src/sync/tests/header_list_response.rs +++ b/p2p/src/sync/tests/header_list_response.rs @@ -20,25 +20,24 @@ use itertools::Itertools as _; use chainstate::ban_score::BanScore; use chainstate_test_framework::TestFramework; use common::{ - chain::{config::create_unit_test_config, GenBlock}, + chain::{GenBlock, config::create_unit_test_config}, primitives::{BlockHeight, Id, Idable}, }; use logging::log; use p2p_test_utils::create_n_blocks; use randomness::RngExt as _; use test_utils::{ - assert_matches, - random::{make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches, + random::{Seed, make_seedable_rng}, }; use crate::{ + P2pConfig, P2pError, error::ProtocolError, message::{BlockListRequest, BlockResponse, BlockSyncMessage, HeaderList}, sync::{test_helpers::make_new_blocks, tests::helpers::TestNode}, test_helpers::{for_each_protocol_version, test_p2p_config}, types::peer_id::PeerId, - P2pConfig, P2pError, }; #[tracing::instrument(skip(seed))] diff --git a/p2p/src/sync/tests/helpers/mod.rs b/p2p/src/sync/tests/helpers/mod.rs index d095fb37ba..fbe939b2fe 100644 --- a/p2p/src/sync/tests/helpers/mod.rs +++ b/p2p/src/sync/tests/helpers/mod.rs @@ -26,28 +26,28 @@ use tokio::{ }; use chainstate::{ - chainstate_interface::ChainstateInterface, make_chainstate, BlockSource, ChainstateConfig, - ChainstateHandle, DefaultTransactionVerificationStrategy, Locator, + BlockSource, ChainstateConfig, ChainstateHandle, DefaultTransactionVerificationStrategy, + Locator, chainstate_interface::ChainstateInterface, make_chainstate, }; use common::{ chain::{ + Block, ChainConfig, Destination, GenBlock, SignedTransaction, Transaction, TxInput, + TxOutput, block::{ - signed_block_header::SignedBlockHeader, timestamp::BlockTimestamp, BlockReward, - ConsensusData, + BlockReward, ConsensusData, signed_block_header::SignedBlockHeader, + timestamp::BlockTimestamp, }, config::create_unit_test_config, output_value::OutputValue, signature::inputsig::InputWitness, - Block, ChainConfig, Destination, GenBlock, SignedTransaction, Transaction, TxInput, - TxOutput, }, - primitives::{Amount, BlockHeight, Id, Idable, H256}, + primitives::{Amount, BlockHeight, H256, Id, Idable}, time_getter::TimeGetter, }; use logging::log; -use mempool::{event::TransactionProcessed, MempoolConfig, MempoolHandle, MempoolInit}; +use mempool::{MempoolConfig, MempoolHandle, MempoolInit, event::TransactionProcessed}; use networking::transport::TcpTransportSocket; -use p2p_test_utils::{expect_future_val, expect_no_recv, expect_recv, SHORT_TIMEOUT}; +use p2p_test_utils::{SHORT_TIMEOUT, expect_future_val, expect_no_recv, expect_recv}; use p2p_types::{bannable_address::BannableAddress, socket_address::SocketAddress}; use randomness::{Rng, RngExt as _}; use subsystem::{ManagerJoinHandle, ShutdownTrigger}; @@ -56,14 +56,14 @@ use utils::{atomics::SeqCstAtomicBool, tokio_spawn_in_current_tracing_span}; use utils_networking::IpOrSocketAddress; use crate::{ + MessagingService, NetworkingService, P2pConfig, P2pError, P2pEventHandler, PeerManagerEvent, + Result, SyncingEventReceiver, message::{BlockSyncMessage, HeaderList, TransactionSyncMessage}, net::types::SyncingEvent, - protocol::{choose_common_protocol_version, ProtocolVersion}, - sync::{subscribe_to_new_tip, subscribe_to_tx_processed, Observer, SyncManager}, + protocol::{ProtocolVersion, choose_common_protocol_version}, + sync::{Observer, SyncManager, subscribe_to_new_tip, subscribe_to_tx_processed}, test_helpers::test_p2p_config, types::peer_id::PeerId, - MessagingService, NetworkingService, P2pConfig, P2pError, P2pEventHandler, PeerManagerEvent, - Result, SyncingEventReceiver, }; pub mod test_node_group; diff --git a/p2p/src/sync/tests/helpers/test_node_group.rs b/p2p/src/sync/tests/helpers/test_node_group.rs index 0dca28eb81..d22859f95b 100644 --- a/p2p/src/sync/tests/helpers/test_node_group.rs +++ b/p2p/src/sync/tests/helpers/test_node_group.rs @@ -15,7 +15,7 @@ use std::collections::BTreeMap; -use futures::{future::select_all, FutureExt}; +use futures::{FutureExt, future::select_all}; use itertools::Either; use tokio::time; @@ -25,9 +25,9 @@ use p2p_test_utils::LONG_TIMEOUT; use p2p_types::PeerId; use randomness::Rng; -use crate::{message::BlockSyncMessage, PeerManagerEvent}; +use crate::{PeerManagerEvent, message::BlockSyncMessage}; -use super::{get_random_hash, TestNode, TestPeer}; +use super::{TestNode, TestPeer, get_random_hash}; struct NodeDataItem { node: TestNode, diff --git a/p2p/src/sync/tests/network_sync.rs b/p2p/src/sync/tests/network_sync.rs index 5b32977302..ffac1a09f8 100644 --- a/p2p/src/sync/tests/network_sync.rs +++ b/p2p/src/sync/tests/network_sync.rs @@ -21,32 +21,31 @@ use chainstate::{BlockSource, ChainstateConfig, ChainstateHandle, Locator}; use chainstate_test_framework::TestFramework; use common::{ chain::{self, block::timestamp::BlockTimestamp}, - primitives::{user_agent::mintlayer_core_user_agent, BlockDistance, Idable}, + primitives::{BlockDistance, Idable, user_agent::mintlayer_core_user_agent}, }; use logging::log; -use p2p_test_utils::{create_n_blocks, run_with_timeout, MEDIUM_TIMEOUT}; +use p2p_test_utils::{MEDIUM_TIMEOUT, create_n_blocks, run_with_timeout}; use p2p_types::PeerId; use randomness::RngExt; use test_utils::{ - mock_time_getter::mocked_time_getter_seconds, - random::{make_seedable_rng, Seed}, BasicTestTimeGetter, + mock_time_getter::mocked_time_getter_seconds, + random::{Seed, make_seedable_rng}, }; use utils::atomics::SeqCstAtomicU64; use crate::{ + PeerManagerEvent, config::{BackendTimeoutsConfig, P2pConfig}, message::{BlockListRequest, BlockResponse, BlockSyncMessage, HeaderList, HeaderListRequest}, protocol::ProtocolConfig, sync::tests::helpers::{ - make_new_block, make_new_blocks, make_new_top_blocks, + TestNode, make_new_block, make_new_blocks, make_new_top_blocks, test_node_group::{ BlockSyncMessageWithNodeIdx, MsgAction, PeerManagerEventWithNodeIdx, TestNodeGroup, }, - TestNode, }, test_helpers::{for_each_protocol_version, test_p2p_config_with_protocol_config}, - PeerManagerEvent, }; #[tracing::instrument(skip(seed))] diff --git a/p2p/src/sync/tests/no_discouragement_after_tx_reorg.rs b/p2p/src/sync/tests/no_discouragement_after_tx_reorg.rs index af8a4e3dbb..c83bf8eac2 100644 --- a/p2p/src/sync/tests/no_discouragement_after_tx_reorg.rs +++ b/p2p/src/sync/tests/no_discouragement_after_tx_reorg.rs @@ -17,12 +17,15 @@ use std::{collections::BTreeSet, sync::Arc}; use chainstate_storage::Transactional as _; use chainstate_test_framework::{ - anyonecanspend_address, create_stake_pool_data_with_all_reward_to_staker, TestFramework, - TransactionBuilder, + TestFramework, TransactionBuilder, anyonecanspend_address, + create_stake_pool_data_with_all_reward_to_staker, }; use common::{ address::pubkeyhash::PublicKeyHash, chain::{ + AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, CoinUnit, DelegationId, + Destination, Genesis, OrderAccountCommand, OrderData, OrderId, OutPointSourceId, PoolId, + SignedTransaction, TxInput, TxOutput, UtxoOutPoint, block::timestamp::BlockTimestamp, classic_multisig::ClassicMultisigChallenge, htlc::{HashedTimelockContract, HtlcSecret}, @@ -34,9 +37,6 @@ use common::{ IsTokenFreezable, IsTokenUnfreezable, TokenId, TokenIssuance, TokenIssuanceV1, TokenTotalSupply, }, - AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, CoinUnit, DelegationId, - Destination, Genesis, OrderAccountCommand, OrderData, OrderId, OutPointSourceId, PoolId, - SignedTransaction, TxInput, TxOutput, UtxoOutPoint, }, primitives::{Amount, Idable as _}, }; @@ -50,11 +50,10 @@ use orders_accounting::OrdersAccountingDB; use p2p_types::PeerId; use randomness::{CryptoRng, RngExt as _}; use test_utils::{ - assert_matches, - random::{gen_random_bytes, Seed}, + BasicTestTimeGetter, assert_matches, + random::{Seed, gen_random_bytes}, random_ascii_alphanumeric_string, token_utils::random_nft_issuance, - BasicTestTimeGetter, }; use crate::{ diff --git a/p2p/src/sync/tests/peer_events.rs b/p2p/src/sync/tests/peer_events.rs index 8cda60abdb..227c629707 100644 --- a/p2p/src/sync/tests/peer_events.rs +++ b/p2p/src/sync/tests/peer_events.rs @@ -18,7 +18,7 @@ use std::sync::Arc; use chainstate::BlockSource; use chainstate_test_framework::TestFramework; use common::chain::{block::timestamp::BlockTimestamp, config::create_unit_test_config}; -use test_utils::{random::Seed, BasicTestTimeGetter}; +use test_utils::{BasicTestTimeGetter, random::Seed}; use crate::{ message::{BlockSyncMessage, HeaderList}, diff --git a/p2p/src/sync/tests/tx_announcement.rs b/p2p/src/sync/tests/tx_announcement.rs index 453ca7c2ac..2906d38aaf 100644 --- a/p2p/src/sync/tests/tx_announcement.rs +++ b/p2p/src/sync/tests/tx_announcement.rs @@ -15,25 +15,26 @@ use std::{collections::BTreeSet, sync::Arc, time::Duration}; -use chainstate::{ban_score::BanScore, BlockSource}; -use chainstate_test_framework::{anyonecanspend_address, TestFramework}; +use chainstate::{BlockSource, ban_score::BanScore}; +use chainstate_test_framework::{TestFramework, anyonecanspend_address}; use common::{ chain::{ + GenBlock, OutPointSourceId, SignedTransaction, Transaction, TxInput, TxOutput, config::create_unit_test_config, output_value::OutputValue, - signature::inputsig::InputWitness, timelock::OutputTimeLock, GenBlock, OutPointSourceId, - SignedTransaction, Transaction, TxInput, TxOutput, + signature::inputsig::InputWitness, timelock::OutputTimeLock, }, primitives::{Amount, Id, Idable}, }; use mempool::{ + FeeRate, MempoolConfig, error::{Error as MempoolError, MempoolPolicyError}, tx_origin::RemoteTxOrigin, - FeeRate, MempoolConfig, }; use serialization::Encode; -use test_utils::{random::Seed, BasicTestTimeGetter}; +use test_utils::{BasicTestTimeGetter, random::Seed}; use crate::{ + P2pConfig, P2pError, config::NodeType, error::ProtocolError, message::{TransactionResponse, TransactionSyncMessage}, @@ -44,7 +45,6 @@ use crate::{ }, test_helpers::{for_each_protocol_version, test_p2p_config}, types::peer_id::PeerId, - P2pConfig, P2pError, }; #[tracing::instrument(skip(seed))] diff --git a/p2p/src/test_helpers.rs b/p2p/src/test_helpers.rs index 891d415619..f1efcfafa3 100644 --- a/p2p/src/test_helpers.rs +++ b/p2p/src/test_helpers.rs @@ -35,8 +35,8 @@ use crate::{ ban_config::BanConfig, config::P2pConfig, net::{ - types::{ConnectivityEvent, PeerInfo}, ConnectivityService, NetworkingService, + types::{ConnectivityEvent, PeerInfo}, }, peer_manager::{ self, diff --git a/p2p/src/tests/bad_time_diff.rs b/p2p/src/tests/bad_time_diff.rs index a0341434d7..34c88b7e19 100644 --- a/p2p/src/tests/bad_time_diff.rs +++ b/p2p/src/tests/bad_time_diff.rs @@ -23,14 +23,13 @@ use networking::{ test_helpers::{ TestTransportChannel, TestTransportMaker, TestTransportNoise, TestTransportTcp, }, - transport::{new_message_stream, TransportListener, TransportSocket}, + transport::{TransportListener, TransportSocket, new_message_stream}, }; use p2p_test_utils::run_with_timeout; use randomness::RngExt as _; use test_utils::{ - assert_matches, - random::{make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches, + random::{Seed, make_seedable_rng}, }; use crate::{ diff --git a/p2p/src/tests/connection_lockup_when_socket_not_read.rs b/p2p/src/tests/connection_lockup_when_socket_not_read.rs index c1c311df1d..19830eda6f 100644 --- a/p2p/src/tests/connection_lockup_when_socket_not_read.rs +++ b/p2p/src/tests/connection_lockup_when_socket_not_read.rs @@ -21,20 +21,19 @@ use rstest::rstest; use chainstate::{BlockSource, ChainstateConfig, Locator}; use common::{ chain, - primitives::{user_agent::mintlayer_core_user_agent, Id, Idable as _}, + primitives::{Id, Idable as _, user_agent::mintlayer_core_user_agent}, }; use logging::log; use networking::{ test_helpers::{TestTransportChannel, TestTransportMaker}, - transport::{new_message_stream, TransportSocket}, + transport::{TransportSocket, new_message_stream}, }; use p2p_test_utils::run_with_timeout; use randomness::RngExt; use serialization::Encode as _; use test_utils::{ - assert_matches, assert_matches_return_val, - random::{make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches, assert_matches_return_val, + random::{Seed, make_seedable_rng}, }; use crate::{ @@ -45,7 +44,7 @@ use crate::{ types::PeerManagerMessageExtTag, }, sync::test_helpers::make_new_blocks, - test_helpers::{test_p2p_config, TEST_PROTOCOL_VERSION}, + test_helpers::{TEST_PROTOCOL_VERSION, test_p2p_config}, tests::helpers::{PeerManagerNotification, TestNode}, }; diff --git a/p2p/src/tests/correct_handshake.rs b/p2p/src/tests/correct_handshake.rs index cb2cea1ca7..c7d88a462c 100644 --- a/p2p/src/tests/correct_handshake.rs +++ b/p2p/src/tests/correct_handshake.rs @@ -22,20 +22,19 @@ use networking::{ test_helpers::{ TestTransportChannel, TestTransportMaker, TestTransportNoise, TestTransportTcp, }, - transport::{new_message_stream, TransportListener, TransportSocket}, + transport::{TransportListener, TransportSocket, new_message_stream}, }; use p2p_test_utils::run_with_timeout; use randomness::RngExt as _; use test_utils::{ - assert_matches, - random::{make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches, + random::{Seed, make_seedable_rng}, }; use crate::{ net::default_backend::types::{HandshakeMessage, Message, P2pTimestamp}, peer_manager::PeerManagerInterface, - test_helpers::{test_p2p_config, TEST_PROTOCOL_VERSION}, + test_helpers::{TEST_PROTOCOL_VERSION, test_p2p_config}, tests::helpers::TestNode, }; diff --git a/p2p/src/tests/disable_networking.rs b/p2p/src/tests/disable_networking.rs index 587893d51c..374e665695 100644 --- a/p2p/src/tests/disable_networking.rs +++ b/p2p/src/tests/disable_networking.rs @@ -23,19 +23,19 @@ use networking::test_helpers::{TestTransportChannel, TestTransportMaker}; use p2p_test_utils::run_with_timeout; use randomness::RngExt as _; use test_utils::{ - random::{make_seedable_rng, Seed}, BasicTestTimeGetter, + random::{Seed, make_seedable_rng}, }; use crate::{ error::{DialError, P2pError}, peer_manager, test_helpers::{ - make_transport_with_local_addr_in_group, test_p2p_config, TEST_PROTOCOL_VERSION, + TEST_PROTOCOL_VERSION, make_transport_with_local_addr_in_group, test_p2p_config, }, tests::helpers::{ - node_wait_for_connection_to_ip_addr, node_wait_for_connection_to_sock_addr, - node_wait_for_disconnection_from_ip_addr, TestNode, + TestNode, node_wait_for_connection_to_ip_addr, node_wait_for_connection_to_sock_addr, + node_wait_for_disconnection_from_ip_addr, }, }; diff --git a/p2p/src/tests/disconnect_on_will_disconnect_msg.rs b/p2p/src/tests/disconnect_on_will_disconnect_msg.rs index e36097ba66..0c28f43892 100644 --- a/p2p/src/tests/disconnect_on_will_disconnect_msg.rs +++ b/p2p/src/tests/disconnect_on_will_disconnect_msg.rs @@ -22,14 +22,13 @@ use networking::{ test_helpers::{ TestTransportChannel, TestTransportMaker, TestTransportNoise, TestTransportTcp, }, - transport::{new_message_stream, TransportSocket}, + transport::{TransportSocket, new_message_stream}, }; use p2p_test_utils::run_with_timeout; use randomness::RngExt as _; use test_utils::{ - assert_matches, - random::{make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches, + random::{Seed, make_seedable_rng}, }; use crate::{ diff --git a/p2p/src/tests/helpers/mod.rs b/p2p/src/tests/helpers/mod.rs index bd33e78b95..78d40e9ffa 100644 --- a/p2p/src/tests/helpers/mod.rs +++ b/p2p/src/tests/helpers/mod.rs @@ -25,7 +25,7 @@ use tokio::sync::mpsc::UnboundedSender; use logging::log; use networking::transport::TransportSocket; -use p2p_types::{bannable_address::BannableAddress, socket_address::SocketAddress, PeerId}; +use p2p_types::{PeerId, bannable_address::BannableAddress, socket_address::SocketAddress}; use randomness::Rng; use test_utils::BasicTestTimeGetter; @@ -35,7 +35,7 @@ use crate::{ default_backend::types::{BackendObserver, Message}, types::{PeerInfo, PeerManagerMessageExtTag, PeerRole}, }, - peer_manager::{self, dns_seed::DnsSeed, PeerManagerObserver}, + peer_manager::{self, PeerManagerObserver, dns_seed::DnsSeed}, }; pub mod test_node; diff --git a/p2p/src/tests/helpers/test_node.rs b/p2p/src/tests/helpers/test_node.rs index c1ccad42ef..4901f25df5 100644 --- a/p2p/src/tests/helpers/test_node.rs +++ b/p2p/src/tests/helpers/test_node.rs @@ -30,13 +30,13 @@ use tokio::{ use ::test_utils::BasicTestTimeGetter; use chainstate::{ - make_chainstate, ChainstateConfig, ChainstateHandle, DefaultTransactionVerificationStrategy, + ChainstateConfig, ChainstateHandle, DefaultTransactionVerificationStrategy, make_chainstate, }; use common::chain::ChainConfig; use mempool::MempoolConfig; use networking::transport::{TransportListener, TransportSocket}; use p2p_test_utils::SHORT_TIMEOUT; -use p2p_types::{p2p_event::P2pEventHandler, socket_address::SocketAddress, PeerId}; +use p2p_types::{PeerId, p2p_event::P2pEventHandler, socket_address::SocketAddress}; use randomness::Rng; use storage_inmemory::InMemory; use subsystem::ShutdownTrigger; @@ -44,17 +44,18 @@ use utils::{atomics::SeqCstAtomicBool, tokio_spawn_in_tracing_span}; use utils_networking::IpOrSocketAddress; use crate::{ + PeerManagerEvent, config::P2pConfig, error::P2pError, net::{ - default_backend::{types::MessageTag, DefaultNetworkingService}, - types::PeerRole, ConnectivityService, + default_backend::{DefaultNetworkingService, types::MessageTag}, + types::PeerRole, }, peer_manager::{ + PeerManager, peerdb::storage_impl::PeerDbStorageImpl, test_utils::{mutate_peer_manager, query_peer_manager}, - PeerManager, }, peer_manager_event::PeerDisconnectionDbAction, protocol::ProtocolVersion, @@ -62,7 +63,6 @@ use crate::{ test_helpers::peerdb_inmemory_store, tests::helpers::{BackendNotification, BackendObserverImpl}, utils::oneshot_nofail, - PeerManagerEvent, }; use super::{PeerManagerNotification, PeerManagerObserverImpl, TestDnsSeed, TestPeersInfo}; diff --git a/p2p/src/tests/incorrect_handshake.rs b/p2p/src/tests/incorrect_handshake.rs index c0ba502a2e..25d30cff6d 100644 --- a/p2p/src/tests/incorrect_handshake.rs +++ b/p2p/src/tests/incorrect_handshake.rs @@ -22,21 +22,20 @@ use networking::{ test_helpers::{ TestTransportChannel, TestTransportMaker, TestTransportNoise, TestTransportTcp, }, - transport::{new_message_stream, TransportListener, TransportSocket}, + transport::{TransportListener, TransportSocket, new_message_stream}, }; use p2p_test_utils::run_with_timeout; use randomness::RngExt as _; use test_utils::{ - assert_matches, - random::{make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches, + random::{Seed, make_seedable_rng}, }; use crate::{ message::HeaderList, net::default_backend::types::{HandshakeMessage, Message}, peer_manager, - test_helpers::{test_p2p_config, TEST_PROTOCOL_VERSION}, + test_helpers::{TEST_PROTOCOL_VERSION, test_p2p_config}, tests::helpers::TestNode, }; diff --git a/p2p/src/tests/min_peer_software_version.rs b/p2p/src/tests/min_peer_software_version.rs index 90457cfe83..7f914e462a 100644 --- a/p2p/src/tests/min_peer_software_version.rs +++ b/p2p/src/tests/min_peer_software_version.rs @@ -21,25 +21,24 @@ use rstest::rstest; use chainstate::ChainstateConfig; use common::primitives::{ semver::SemVer, - user_agent::{mintlayer_core_user_agent, UserAgent}, + user_agent::{UserAgent, mintlayer_core_user_agent}, }; use networking::{ test_helpers::{TestTransportChannel, TestTransportMaker}, - transport::{new_message_stream, ConnectedSocketInfo as _, TransportListener, TransportSocket}, + transport::{ConnectedSocketInfo as _, TransportListener, TransportSocket, new_message_stream}, }; use p2p_test_utils::run_with_timeout; use p2p_types::socket_address::SocketAddress; use randomness::RngExt as _; use test_utils::{ - assert_matches, - random::{make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches, + random::{Seed, make_seedable_rng}, }; use crate::{ config::P2pConfig, net::default_backend::types::{HandshakeMessage, Message, P2pTimestamp}, - peer_manager::{self, config::PeerManagerConfig, PeerManagerInterface}, + peer_manager::{self, PeerManagerInterface, config::PeerManagerConfig}, test_helpers::TEST_PROTOCOL_VERSION, tests::helpers::TestNode, }; diff --git a/p2p/src/tests/misbehavior.rs b/p2p/src/tests/misbehavior.rs index f04319835d..4a22a39bac 100644 --- a/p2p/src/tests/misbehavior.rs +++ b/p2p/src/tests/misbehavior.rs @@ -17,26 +17,25 @@ use std::sync::Arc; use rstest::rstest; -use chainstate::{ban_score::BanScore, ChainstateConfig}; +use chainstate::{ChainstateConfig, ban_score::BanScore}; use networking::{ test_helpers::{ TestTransportChannel, TestTransportMaker, TestTransportNoise, TestTransportTcp, }, - transport::{new_message_stream, TransportSocket}, + transport::{TransportSocket, new_message_stream}, }; use p2p_test_utils::run_with_timeout; use randomness::RngExt as _; use test_utils::{ - assert_matches, - random::{make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches, + random::{Seed, make_seedable_rng}, }; use crate::{ error::{P2pError, ProtocolError}, net::default_backend::types::{HandshakeMessage, Message, P2pTimestamp}, peer_manager::PeerManagerInterface, - test_helpers::{test_p2p_config, TEST_PROTOCOL_VERSION}, + test_helpers::{TEST_PROTOCOL_VERSION, test_p2p_config}, tests::helpers::TestNode, }; diff --git a/p2p/src/tests/peer_discovery_on_stale_tip.rs b/p2p/src/tests/peer_discovery_on_stale_tip.rs index e09ba322e6..91f417adbf 100644 --- a/p2p/src/tests/peer_discovery_on_stale_tip.rs +++ b/p2p/src/tests/peer_discovery_on_stale_tip.rs @@ -18,16 +18,16 @@ use std::{collections::BTreeSet, sync::Arc, time::Duration}; use chainstate::{BlockSource, ChainstateConfig}; use common::{ chain::{Block, ChainConfig}, - primitives::{user_agent::mintlayer_core_user_agent, Idable}, + primitives::{Idable, user_agent::mintlayer_core_user_agent}, }; use logging::log; use networking::test_helpers::{TestTransportChannel, TestTransportMaker}; -use p2p_test_utils::{run_with_timeout, SHORT_TIMEOUT}; +use p2p_test_utils::{SHORT_TIMEOUT, run_with_timeout}; use p2p_types::socket_address::SocketAddress; use randomness::{Rng, RngExt as _}; use test_utils::{ - random::{make_seedable_rng, Seed}, BasicTestTimeGetter, + random::{Seed, make_seedable_rng}, }; use crate::{ @@ -35,7 +35,7 @@ use crate::{ net::types::PeerRole, peer_manager::{self, address_groups::AddressGroup, config::PeerManagerConfig}, sync::test_helpers::make_new_block, - test_helpers::{make_transport_with_local_addr_in_group, TEST_PROTOCOL_VERSION}, + test_helpers::{TEST_PROTOCOL_VERSION, make_transport_with_local_addr_in_group}, tests::helpers::{PeerManagerNotification, TestNode, TestNodeGroup}, }; diff --git a/p2p/src/tests/peer_mgr_events.rs b/p2p/src/tests/peer_mgr_events.rs index fcad9ea66d..a20fc62cc6 100644 --- a/p2p/src/tests/peer_mgr_events.rs +++ b/p2p/src/tests/peer_mgr_events.rs @@ -25,15 +25,14 @@ use chainstate::{ChainstateConfig, Locator}; use common::primitives::Id; use networking::{ test_helpers::{TestTransportChannel, TestTransportMaker}, - transport::{new_message_stream, TransportListener, TransportSocket}, + transport::{TransportListener, TransportSocket, new_message_stream}, }; -use p2p_test_utils::{run_with_timeout, MEDIUM_TIMEOUT, SHORT_TIMEOUT}; +use p2p_test_utils::{MEDIUM_TIMEOUT, SHORT_TIMEOUT, run_with_timeout}; use p2p_types::peer_address::PeerAddress; -use randomness::{seq::IteratorRandom as _, Rng, RngExt as _}; +use randomness::{Rng, RngExt as _, seq::IteratorRandom as _}; use test_utils::{ - assert_matches, - random::{gen_random_alnum_string, make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches, + random::{Seed, gen_random_alnum_string, make_seedable_rng}, }; use crate::{ @@ -47,7 +46,7 @@ use crate::{ types::PeerManagerMessageExtTag, }, sync::test_helpers::make_new_block, - test_helpers::{test_p2p_config, TEST_PROTOCOL_VERSION}, + test_helpers::{TEST_PROTOCOL_VERSION, test_p2p_config}, tests::helpers::{PeerManagerNotification, TestNode}, }; diff --git a/p2p/src/tests/same_handshake_nonce.rs b/p2p/src/tests/same_handshake_nonce.rs index 793160b8a5..0038d69e56 100644 --- a/p2p/src/tests/same_handshake_nonce.rs +++ b/p2p/src/tests/same_handshake_nonce.rs @@ -22,14 +22,13 @@ use networking::{ test_helpers::{ TestTransportChannel, TestTransportMaker, TestTransportNoise, TestTransportTcp, }, - transport::{new_message_stream, TransportListener, TransportSocket}, + transport::{TransportListener, TransportSocket, new_message_stream}, }; use p2p_test_utils::run_with_timeout; use randomness::RngExt as _; use test_utils::{ - assert_matches, - random::{make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches, + random::{Seed, make_seedable_rng}, }; use crate::{ diff --git a/p2p/src/tests/unsupported_message.rs b/p2p/src/tests/unsupported_message.rs index f0bd0f21b4..fdde0ae0d1 100644 --- a/p2p/src/tests/unsupported_message.rs +++ b/p2p/src/tests/unsupported_message.rs @@ -19,15 +19,14 @@ use chainstate::ChainstateConfig; use common::{chain::Transaction, primitives::Id}; use networking::{ test_helpers::{TestTransportChannel, TestTransportMaker}, - transport::{new_message_stream, TransportSocket as _}, + transport::{TransportSocket as _, new_message_stream}, }; use p2p_test_utils::run_with_timeout; use randomness::RngExt as _; use serialization::{Decode, Encode}; use test_utils::{ - assert_matches, assert_matches_return_val, - random::{gen_random_bytes, make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches, assert_matches_return_val, + random::{Seed, gen_random_bytes, make_seedable_rng}, }; use crate::{ @@ -38,7 +37,7 @@ use crate::{ }, net::default_backend::types::{HandshakeMessage, P2pTimestamp}, protocol::ProtocolConfig, - test_helpers::{test_p2p_config_with_protocol_config, TEST_PROTOCOL_VERSION}, + test_helpers::{TEST_PROTOCOL_VERSION, test_p2p_config_with_protocol_config}, tests::helpers::TestNode, }; diff --git a/p2p/src/tests/unsupported_version.rs b/p2p/src/tests/unsupported_version.rs index 0e39bf3ad3..b60c58c258 100644 --- a/p2p/src/tests/unsupported_version.rs +++ b/p2p/src/tests/unsupported_version.rs @@ -22,20 +22,19 @@ use networking::{ test_helpers::{ TestTransportChannel, TestTransportMaker, TestTransportNoise, TestTransportTcp, }, - transport::{new_message_stream, TransportListener, TransportSocket}, + transport::{TransportListener, TransportSocket, new_message_stream}, }; use p2p_test_utils::run_with_timeout; use randomness::RngExt as _; use test_utils::{ - assert_matches, - random::{make_seedable_rng, Seed}, - BasicTestTimeGetter, + BasicTestTimeGetter, assert_matches, + random::{Seed, make_seedable_rng}, }; use crate::{ net::default_backend::types::{HandshakeMessage, Message, P2pTimestamp}, protocol::ProtocolVersion, - test_helpers::{test_p2p_config, TEST_PROTOCOL_VERSION}, + test_helpers::{TEST_PROTOCOL_VERSION, test_p2p_config}, tests::helpers::TestNode, }; diff --git a/p2p/test-utils/src/lib.rs b/p2p/test-utils/src/lib.rs index 9dbab2f776..46ce2d0a90 100644 --- a/p2p/test-utils/src/lib.rs +++ b/p2p/test-utils/src/lib.rs @@ -24,12 +24,12 @@ use std::{future::Future, sync::Arc, time::Duration}; use tokio::sync::mpsc; use chainstate::{ - make_chainstate, ChainstateConfig, ChainstateHandle, ChainstateSubsystem, - DefaultTransactionVerificationStrategy, + ChainstateConfig, ChainstateHandle, ChainstateSubsystem, + DefaultTransactionVerificationStrategy, make_chainstate, }; use chainstate_test_framework::TestFramework; use common::{ - chain::{config::ChainConfig, Block}, + chain::{Block, config::ChainConfig}, primitives::Idable, time_getter::TimeGetter, }; diff --git a/p2p/tests/shutdown.rs b/p2p/tests/shutdown.rs index 2133663efc..95d3e99196 100644 --- a/p2p/tests/shutdown.rs +++ b/p2p/tests/shutdown.rs @@ -15,7 +15,7 @@ use std::{sync::Arc, time::Duration}; -use chainstate::{make_chainstate, ChainstateConfig, DefaultTransactionVerificationStrategy}; +use chainstate::{ChainstateConfig, DefaultTransactionVerificationStrategy, make_chainstate}; use common::chain::config::create_unit_test_config; use mempool::{MempoolConfig, MempoolInit}; use storage_inmemory::InMemory; diff --git a/p2p/types/src/peer_address.rs b/p2p/types/src/peer_address.rs index 481694d969..72b777bf83 100644 --- a/p2p/types/src/peer_address.rs +++ b/p2p/types/src/peer_address.rs @@ -21,9 +21,9 @@ use std::{ use serialization::{Decode, Encode}; use crate::{ + IsGlobalIp, ip_address::{Ip4, Ip6}, socket_address::SocketAddress, - IsGlobalIp, }; #[derive(Debug, Encode, Decode, Clone, PartialOrd, Ord, PartialEq, Eq)] diff --git a/pos-accounting/src/lib.rs b/pos-accounting/src/lib.rs index 38e08fbd7d..8239d8e1da 100644 --- a/pos-accounting/src/lib.rs +++ b/pos-accounting/src/lib.rs @@ -23,7 +23,7 @@ pub use crate::{ error::{Error, Result}, pool::{ delegation::DelegationData, - delta::{data::PoSAccountingDeltaData, DeltaMergeUndo, PoSAccountingDelta}, + delta::{DeltaMergeUndo, PoSAccountingDelta, data::PoSAccountingDeltaData}, helpers::random_undo_for_test, operations::{PoSAccountingOperations, PoSAccountingUndo}, pool_data::PoolData, @@ -31,7 +31,7 @@ pub use crate::{ view::{FlushablePoSAccountingView, PoSAccountingView}, }, storage::{ - in_memory::InMemoryPoSAccounting, DefaultStorageTag, PoSAccountingStorageRead, - PoSAccountingStorageWrite, StorageTag, + DefaultStorageTag, PoSAccountingStorageRead, PoSAccountingStorageWrite, StorageTag, + in_memory::InMemoryPoSAccounting, }, }; diff --git a/pos-accounting/src/pool/delta/data.rs b/pos-accounting/src/pool/delta/data.rs index 3cdc75f3f2..bfd90c6cab 100644 --- a/pos-accounting/src/pool/delta/data.rs +++ b/pos-accounting/src/pool/delta/data.rs @@ -17,8 +17,8 @@ use accounting::{DeltaAmountCollection, DeltaDataCollection}; use common::chain::{DelegationId, PoolId}; use crate::{ - pool::{delegation::DelegationData, pool_data::PoolData}, DeltaMergeUndo, Error, + pool::{delegation::DelegationData, pool_data::PoolData}, }; use serialization::{Decode, Encode}; diff --git a/pos-accounting/src/pool/delta/mod.rs b/pos-accounting/src/pool/delta/mod.rs index 17aca323a5..047903f035 100644 --- a/pos-accounting/src/pool/delta/mod.rs +++ b/pos-accounting/src/pool/delta/mod.rs @@ -18,7 +18,7 @@ use std::collections::BTreeMap; use accounting::{DeltaAmountCollection, DeltaDataUndoCollection}; use common::{ chain::{DelegationId, PoolId}, - primitives::{amount::SignedAmount, Amount, H256}, + primitives::{Amount, H256, amount::SignedAmount}, }; use serialization::{Decode, Encode}; diff --git a/pos-accounting/src/pool/delta/view_impl.rs b/pos-accounting/src/pool/delta/view_impl.rs index a223d118ff..d71f5159ff 100644 --- a/pos-accounting/src/pool/delta/view_impl.rs +++ b/pos-accounting/src/pool/delta/view_impl.rs @@ -18,21 +18,21 @@ use std::collections::BTreeMap; use accounting::combine_amount_delta; use common::{ chain::{DelegationId, PoolId}, - primitives::{amount::SignedAmount, Amount}, + primitives::{Amount, amount::SignedAmount}, }; use utils::tap_log::TapLog; use crate::{ + DeltaMergeUndo, error::Error, pool::{ delegation::DelegationData, pool_data::PoolData, view::{FlushablePoSAccountingView, PoSAccountingView}, }, - DeltaMergeUndo, }; -use super::{data::PoSAccountingDeltaData, PoSAccountingDelta}; +use super::{PoSAccountingDelta, data::PoSAccountingDeltaData}; fn signed_to_unsigned_pair( (k, v): (DelegationId, SignedAmount), diff --git a/pos-accounting/src/pool/helpers.rs b/pos-accounting/src/pool/helpers.rs index 17fa532f16..39534c31d7 100644 --- a/pos-accounting/src/pool/helpers.rs +++ b/pos-accounting/src/pool/helpers.rs @@ -19,7 +19,7 @@ use common::{ }; use randomness::{Rng, RngExt as _}; -use crate::{pool::operations::DelegateStakingUndo, PoSAccountingUndo}; +use crate::{PoSAccountingUndo, pool::operations::DelegateStakingUndo}; pub fn random_undo_for_test(rng: &mut impl Rng) -> PoSAccountingUndo { let delegation_target: DelegationId = H256::random_using(rng).into(); diff --git a/pos-accounting/src/pool/pool_data.rs b/pos-accounting/src/pool/pool_data.rs index 0787789eee..3502b619eb 100644 --- a/pos-accounting/src/pool/pool_data.rs +++ b/pos-accounting/src/pool/pool_data.rs @@ -14,8 +14,8 @@ // limitations under the License. use common::{ - chain::{stakelock::StakePoolData, Destination}, - primitives::{per_thousand::PerThousand, Amount}, + chain::{Destination, stakelock::StakePoolData}, + primitives::{Amount, per_thousand::PerThousand}, }; use crypto::vrf::VRFPublicKey; use serialization::{Decode, Encode}; diff --git a/pos-accounting/src/pool/storage/helpers.rs b/pos-accounting/src/pool/storage/helpers.rs index 40e570a9c2..30c6e4bc45 100644 --- a/pos-accounting/src/pool/storage/helpers.rs +++ b/pos-accounting/src/pool/storage/helpers.rs @@ -14,8 +14,8 @@ // limitations under the License. use crate::{ - storage::{PoSAccountingStorageRead, PoSAccountingStorageWrite}, StorageTag, + storage::{PoSAccountingStorageRead, PoSAccountingStorageWrite}, }; pub struct BorrowedStorageValue<'a, T, S, Getter, Setter, Deleter> { diff --git a/pos-accounting/src/pool/storage/mod.rs b/pos-accounting/src/pool/storage/mod.rs index affd9f0076..3aa229129f 100644 --- a/pos-accounting/src/pool/storage/mod.rs +++ b/pos-accounting/src/pool/storage/mod.rs @@ -16,14 +16,14 @@ use std::{collections::BTreeMap, ops::Neg}; use accounting::{ - combine_amount_delta, combine_data_with_delta, DeltaAmountCollection, DeltaDataCollection, - DeltaDataUndoCollection, + DeltaAmountCollection, DeltaDataCollection, DeltaDataUndoCollection, combine_amount_delta, + combine_data_with_delta, }; -use common::primitives::{amount::SignedAmount, Amount}; +use common::primitives::{Amount, amount::SignedAmount}; use crate::{ - error::Error, pool::delta::data::PoSAccountingDeltaData, storage::PoSAccountingStorageWrite, - DeltaMergeUndo, StorageTag, + DeltaMergeUndo, StorageTag, error::Error, pool::delta::data::PoSAccountingDeltaData, + storage::PoSAccountingStorageWrite, }; pub mod view_impls; diff --git a/pos-accounting/src/pool/storage/view_impls.rs b/pos-accounting/src/pool/storage/view_impls.rs index c20d2ee450..01b27c291e 100644 --- a/pos-accounting/src/pool/storage/view_impls.rs +++ b/pos-accounting/src/pool/storage/view_impls.rs @@ -21,6 +21,7 @@ use common::{ }; use crate::{ + DeltaMergeUndo, PoSAccountingDB, StorageTag, pool::{ delegation::DelegationData, delta::data::PoSAccountingDeltaData, @@ -28,7 +29,6 @@ use crate::{ view::{FlushablePoSAccountingView, PoSAccountingView}, }, storage::{PoSAccountingStorageRead, PoSAccountingStorageWrite}, - DeltaMergeUndo, PoSAccountingDB, StorageTag, }; impl, T: StorageTag> PoSAccountingView for PoSAccountingDB { diff --git a/pos-accounting/src/pool/tests/delta_tests.rs b/pos-accounting/src/pool/tests/delta_tests.rs index 2b573deb19..3d6fbd5295 100644 --- a/pos-accounting/src/pool/tests/delta_tests.rs +++ b/pos-accounting/src/pool/tests/delta_tests.rs @@ -16,16 +16,16 @@ use std::collections::BTreeMap; use accounting::{DataDelta, DeltaAmountCollection, DeltaDataCollection}; -use common::primitives::{amount::SignedAmount, Amount}; +use common::primitives::{Amount, amount::SignedAmount}; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use super::{create_pool_data, new_delegation_id, new_pool_id, new_pub_key_destination}; use crate::{ pool::{ delegation::DelegationData, - delta::{data::PoSAccountingDeltaData, PoSAccountingDelta}, + delta::{PoSAccountingDelta, data::PoSAccountingDeltaData}, storage::PoSAccountingDB, }, storage::in_memory::InMemoryPoSAccounting, diff --git a/pos-accounting/src/pool/tests/mod.rs b/pos-accounting/src/pool/tests/mod.rs index 012e19306b..e65a3c680a 100644 --- a/pos-accounting/src/pool/tests/mod.rs +++ b/pos-accounting/src/pool/tests/mod.rs @@ -17,7 +17,7 @@ use std::collections::BTreeMap; use common::{ chain::{DelegationId, Destination, PoolId}, - primitives::{per_thousand::PerThousand, Amount, H256}, + primitives::{Amount, H256, per_thousand::PerThousand}, }; use crypto::{ key::{KeyKind, PrivateKey}, @@ -26,8 +26,8 @@ use crypto::{ use randomness::{CryptoRng, RngExt as _}; use crate::{ - error::Error, storage::in_memory::InMemoryPoSAccounting, DelegationData, - PoSAccountingOperations, PoSAccountingUndo, PoolData, + DelegationData, PoSAccountingOperations, PoSAccountingUndo, PoolData, error::Error, + storage::in_memory::InMemoryPoSAccounting, }; mod delta_tests; diff --git a/pos-accounting/src/pool/tests/operations_tests.rs b/pos-accounting/src/pool/tests/operations_tests.rs index 993ab5bdf3..5f56f29bd6 100644 --- a/pos-accounting/src/pool/tests/operations_tests.rs +++ b/pos-accounting/src/pool/tests/operations_tests.rs @@ -20,7 +20,7 @@ use common::{ primitives::Amount, }; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use super::{ create_pool, create_pool_data, create_storage_with_pool, @@ -28,9 +28,9 @@ use super::{ }; use crate::{ + Error, PoSAccountingOperations, pool::{delta::PoSAccountingDelta, storage::PoSAccountingDB, view::FlushablePoSAccountingView}, storage::in_memory::InMemoryPoSAccounting, - Error, PoSAccountingOperations, }; #[rstest] diff --git a/pos-accounting/src/pool/tests/simulation_tests.rs b/pos-accounting/src/pool/tests/simulation_tests.rs index 04fb94bf53..b6b84ec08c 100644 --- a/pos-accounting/src/pool/tests/simulation_tests.rs +++ b/pos-accounting/src/pool/tests/simulation_tests.rs @@ -21,15 +21,15 @@ use common::{ primitives::Amount, }; use randomness::{CryptoRng, Rng, RngExt as _}; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use super::create_pool_data; use crate::{ - pool::{delegation::DelegationData, storage::PoSAccountingDB}, - storage::in_memory::InMemoryPoSAccounting, FlushablePoSAccountingView, PoSAccountingDelta, PoSAccountingOperations, PoSAccountingUndo, PoSAccountingView, + pool::{delegation::DelegationData, storage::PoSAccountingDB}, + storage::in_memory::InMemoryPoSAccounting, }; fn get_random_pool_id(rng: &mut impl Rng, storage: &InMemoryPoSAccounting) -> Option { diff --git a/pos-accounting/src/pool/tests/undo_tests.rs b/pos-accounting/src/pool/tests/undo_tests.rs index e60a21c66c..37ba0e3579 100644 --- a/pos-accounting/src/pool/tests/undo_tests.rs +++ b/pos-accounting/src/pool/tests/undo_tests.rs @@ -18,7 +18,7 @@ use std::collections::BTreeMap; use common::{chain::Destination, primitives::Amount}; use randomness::Rng; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use super::{ create_delegation_id, create_pool, create_storage_with_pool, diff --git a/pos-accounting/src/storage/in_memory.rs b/pos-accounting/src/storage/in_memory.rs index 499df05ffe..6976ab2d92 100644 --- a/pos-accounting/src/storage/in_memory.rs +++ b/pos-accounting/src/storage/in_memory.rs @@ -21,8 +21,8 @@ use common::{ }; use crate::{ - pool::{delegation::DelegationData, pool_data::PoolData}, PoSAccountingData, + pool::{delegation::DelegationData, pool_data::PoolData}, }; use super::{PoSAccountingStorageRead, PoSAccountingStorageWrite}; diff --git a/randomness/src/lib.rs b/randomness/src/lib.rs index 652d2a15f7..eb3e60e79a 100644 --- a/randomness/src/lib.rs +++ b/randomness/src/lib.rs @@ -18,11 +18,11 @@ pub mod adapters; use std::sync::Mutex; pub use rand::prelude::{IndexedMutRandom, IndexedRandom, SliceRandom}; -pub use rand::{seq, CryptoRng, Rng, RngExt, SeedableRng, TryCryptoRng, TryRng}; +pub use rand::{CryptoRng, Rng, RngExt, SeedableRng, TryCryptoRng, TryRng, seq}; pub mod distributions { pub use rand::distr::{ - weighted::WeightedIndex, Alphanumeric, Distribution, SampleString, StandardUniform, + Alphanumeric, Distribution, SampleString, StandardUniform, weighted::WeightedIndex, }; pub mod uniform { pub use rand::distr::uniform::SampleRange; diff --git a/rpc/description-macro/src/describe_impl.rs b/rpc/description-macro/src/describe_impl.rs index fa3ae87542..84ef63a042 100644 --- a/rpc/description-macro/src/describe_impl.rs +++ b/rpc/description-macro/src/describe_impl.rs @@ -14,7 +14,7 @@ // limitations under the License. use quote::quote; -use syn::{parse_quote, spanned::Spanned, ItemTrait, TraitItem, TraitItemFn}; +use syn::{ItemTrait, TraitItem, TraitItemFn, parse_quote, spanned::Spanned}; fn for_attr<'a>( name: &str, @@ -126,7 +126,7 @@ impl<'a> MethodMeta<'a> { return Err(syn::Error::new( item.span(), "Neither method nor subscription", - )) + )); } (Some(method_name), None) => { let return_type = match &item.sig.output { @@ -146,7 +146,7 @@ impl<'a> MethodMeta<'a> { return Err(syn::Error::new( item.span(), "Method AND subscription at the same time", - )) + )); } }; diff --git a/rpc/description-macro/src/value_hint.rs b/rpc/description-macro/src/value_hint.rs index 5758fc9122..25eba99112 100644 --- a/rpc/description-macro/src/value_hint.rs +++ b/rpc/description-macro/src/value_hint.rs @@ -91,7 +91,7 @@ impl SerdeAttributes { }, (None, Some(span)) => EnumTag::None(span), (Some(_), Some(span)) => { - return Err(syn::Error::new(span, "Conflicting tag specifiers")) + return Err(syn::Error::new(span, "Conflicting tag specifiers")); } }; diff --git a/rpc/description/src/value_hint.rs b/rpc/description/src/value_hint.rs index 69701120b3..8c7e6950b6 100644 --- a/rpc/description/src/value_hint.rs +++ b/rpc/description/src/value_hint.rs @@ -14,8 +14,8 @@ // limitations under the License. use std::num::{ - NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128, - NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, + NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize, NonZeroU8, + NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize, }; pub use rpc_description_macro::HasValueHint; diff --git a/rpc/src/error.rs b/rpc/src/error.rs index c9719d7e33..a2e6ae9f0f 100644 --- a/rpc/src/error.rs +++ b/rpc/src/error.rs @@ -18,7 +18,7 @@ use std::fmt::Display; /// RPC error -use jsonrpsee::types::{error::CALL_EXECUTION_FAILED_CODE, ErrorObject, ErrorObjectOwned}; +use jsonrpsee::types::{ErrorObject, ErrorObjectOwned, error::CALL_EXECUTION_FAILED_CODE}; /// The Result type with RPC-specific error. pub type RpcResult = jsonrpsee::core::RpcResult; diff --git a/rpc/src/lib.rs b/rpc/src/lib.rs index a7dc7cc2f6..bb122ff4bf 100644 --- a/rpc/src/lib.rs +++ b/rpc/src/lib.rs @@ -29,16 +29,16 @@ pub use rpc_types as types; use std::{net::SocketAddr, path::PathBuf}; use base64::Engine; -use http::{header, HeaderValue}; +use http::{HeaderValue, header}; use jsonrpsee::{ core::middleware::RpcServiceBuilder, - http_client::{transport::HttpBackend, HttpClient, HttpClientBuilder, RpcService}, + http_client::{HttpClient, HttpClientBuilder, RpcService, transport::HttpBackend}, server::{ServerBuilder, ServerHandle}, }; use logging::log; -pub use error::{handle_result, ClientError, Error, RpcCallResult, RpcClientResult, RpcResult}; +pub use error::{ClientError, Error, RpcCallResult, RpcClientResult, RpcResult, handle_result}; pub use jsonrpsee::{core::server::Methods, proc_macros::rpc}; use rpc_auth::RpcAuth; diff --git a/rpc/src/rpc_auth/mod.rs b/rpc/src/rpc_auth/mod.rs index f93989124e..43584afe6b 100644 --- a/rpc/src/rpc_auth/mod.rs +++ b/rpc/src/rpc_auth/mod.rs @@ -15,7 +15,7 @@ use base64::Engine; use crypto::{ - kdf::{argon2::Argon2Config, hash_password, verify_password, KdfConfig, KdfResult}, + kdf::{KdfConfig, KdfResult, argon2::Argon2Config, hash_password, verify_password}, util::eq::SliceEqualityCheckMethod, }; use hyper::{Request, Response}; diff --git a/rpc/src/rpc_creds.rs b/rpc/src/rpc_creds.rs index a5382534a4..45a95aa646 100644 --- a/rpc/src/rpc_creds.rs +++ b/rpc/src/rpc_creds.rs @@ -19,7 +19,7 @@ use std::{ }; use logging::log; -use randomness::{distributions::SampleString, make_true_rng, CryptoRng}; +use randomness::{CryptoRng, distributions::SampleString, make_true_rng}; use utils::cookie::COOKIE_FILENAME; const COOKIE_PASSWORD_LEN: usize = 32; diff --git a/rpc/tests/basic/main.rs b/rpc/tests/basic/main.rs index b9ba591d7d..79d640c904 100644 --- a/rpc/tests/basic/main.rs +++ b/rpc/tests/basic/main.rs @@ -22,14 +22,14 @@ use jsonrpsee::{ use rstest::rstest; use randomness::{ - distributions::{Alphanumeric, SampleString}, Rng, RngExt as _, + distributions::{Alphanumeric, SampleString}, }; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use rpc::{ - new_http_client, new_ws_client, rpc_creds::RpcCreds, subscription, Builder, Rpc, RpcAuthData, - RpcClientResult, RpcResult, + Builder, Rpc, RpcAuthData, RpcClientResult, RpcResult, new_http_client, new_ws_client, + rpc_creds::RpcCreds, subscription, }; mod desc; diff --git a/rustfmt.toml b/rustfmt.toml index 999cc01ae4..0b44aea1a3 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -5,7 +5,6 @@ array_width = 80 chain_width = 80 single_line_if_else_max_width = 50 newline_style = "Unix" -edition = "2021" -style_edition = "2021" +edition = "2024" match_arm_leading_pipes = "Preserve" diff --git a/script/src/lib.rs b/script/src/lib.rs index 9b3dc8649e..b2325553e6 100644 --- a/script/src/lib.rs +++ b/script/src/lib.rs @@ -56,8 +56,8 @@ pub mod script; mod test; pub use crate::script::{Builder, Script}; +pub use context::Context; #[cfg(feature = "testcontext")] pub use context::testcontext::TestContext; -pub use context::Context; pub use error::{Error, Result}; -pub use interpreter::{run_pushdata, run_script, verify_witness_lock, Stack}; +pub use interpreter::{Stack, run_pushdata, run_script, verify_witness_lock}; diff --git a/script/src/script.rs b/script/src/script.rs index 9f1adaba1a..c8ffd0e2c6 100644 --- a/script/src/script.rs +++ b/script/src/script.rs @@ -973,8 +973,11 @@ mod test { hex_script!("6363636363686868686800").asm(), "OP_IF OP_IF OP_IF OP_IF OP_IF OP_ENDIF OP_ENDIF OP_ENDIF OP_ENDIF OP_ENDIF OP_0" ); - assert_eq!(hex_script!("2102715e91d37d239dea832f1460e91e368115d8ca6cc23a7da966795abad9e3b699ac").asm(), - "OP_PUSHBYTES_33 02715e91d37d239dea832f1460e91e368115d8ca6cc23a7da966795abad9e3b699 OP_CHECKSIG"); + assert_eq!( + hex_script!("2102715e91d37d239dea832f1460e91e368115d8ca6cc23a7da966795abad9e3b699ac") + .asm(), + "OP_PUSHBYTES_33 02715e91d37d239dea832f1460e91e368115d8ca6cc23a7da966795abad9e3b699 OP_CHECKSIG" + ); // Elements Alpha peg-out transaction with some signatures removed for brevity. Mainly to // test PUSHDATA1 assert_eq!(hex_script!("0047304402202457e78cc1b7f50d0543863c27de75d07982bde8359b9e3316adec0aec165f2f02200203fd331c4e4a4a02f48cf1c291e2c0d6b2f7078a784b5b3649fca41f8794d401004cf1552103244e602b46755f24327142a0517288cebd159eccb6ccf41ea6edf1f601e9af952103bbbacc302d19d29dbfa62d23f37944ae19853cf260c745c2bea739c95328fcb721039227e83246bd51140fe93538b2301c9048be82ef2fb3c7fc5d78426ed6f609ad210229bf310c379b90033e2ecb07f77ecf9b8d59acb623ab7be25a0caed539e2e6472103703e2ed676936f10b3ce9149fa2d4a32060fb86fa9a70a4efe3f21d7ab90611921031e9b7c6022400a6bb0424bbcde14cff6c016b91ee3803926f3440abf5c146d05210334667f975f55a8455d515a2ef1c94fdfa3315f12319a14515d2a13d82831f62f57ae").asm(), @@ -995,10 +998,10 @@ mod test { #[test] fn script_p2pk() { - assert!(hex_script!( - "21021aeaf2f8638a129a3156fbe7e5ef635226b0bafd495ff03afe2c843d7e3a4b51ac" - ) - .is_p2pk()); + assert!( + hex_script!("21021aeaf2f8638a129a3156fbe7e5ef635226b0bafd495ff03afe2c843d7e3a4b51ac") + .is_p2pk() + ); assert!(hex_script!("410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac").is_p2pk()); } diff --git a/serialization/core/tests/complex_types.rs b/serialization/core/tests/complex_types.rs index d71bed5a06..2eec421c7b 100644 --- a/serialization/core/tests/complex_types.rs +++ b/serialization/core/tests/complex_types.rs @@ -21,7 +21,7 @@ use rstest::rstest; use randomness::RngExt as _; use serialization_core::{Decode, DecodeAll, Encode}; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use utils::{OptionWrapper, SimpleWrapper}; #[test] diff --git a/serialization/core/tests/containers.rs b/serialization/core/tests/containers.rs index cb64da789c..781114ed1b 100644 --- a/serialization/core/tests/containers.rs +++ b/serialization/core/tests/containers.rs @@ -21,7 +21,7 @@ use rstest::rstest; use randomness::RngExt as _; use serialization_core::{DecodeAll, Encode}; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use utils::SimpleWrapper; #[test] diff --git a/storage/backend-test-suite/src/concurrent.rs b/storage/backend-test-suite/src/concurrent.rs index 47a0580d5e..7bcd81835d 100644 --- a/storage/backend-test-suite/src/concurrent.rs +++ b/storage/backend-test-suite/src/concurrent.rs @@ -61,8 +61,10 @@ fn read_write_race>(backend_factory: Arc< let dbtx = store.transaction_ro().unwrap(); let expected = [[0u8].as_ref(), [2].as_ref()]; - assert!(expected - .contains(&dbtx.get(MAPID.0, TEST_KEY).unwrap().as_ref().map(|v| v.as_ref()).unwrap())); + assert!( + expected + .contains(&dbtx.get(MAPID.0, TEST_KEY).unwrap().as_ref().map(|v| v.as_ref()).unwrap()) + ); drop(dbtx); thr0.join().unwrap(); diff --git a/storage/backend-test-suite/src/frontend.rs b/storage/backend-test-suite/src/frontend.rs index 146c8d3cd1..d95e4e79a0 100644 --- a/storage/backend-test-suite/src/frontend.rs +++ b/storage/backend-test-suite/src/frontend.rs @@ -18,11 +18,11 @@ use crate::prelude::*; -use test_utils::random::{gen_random_bytes, make_seedable_rng, RngExt as _}; +use test_utils::random::{RngExt as _, gen_random_bytes, make_seedable_rng}; mod iter_sort_preserving_numbers { use serialization::{Decode, Encode}; - use storage::{decl_schema, MakeMapRef, OrderPreservingValue, Storage}; + use storage::{MakeMapRef, OrderPreservingValue, Storage, decl_schema}; use utils::sorted::Sorted; use crate::with_rng_seed; diff --git a/storage/backend-test-suite/src/model.rs b/storage/backend-test-suite/src/model.rs index 5900bf9e1a..58136fb400 100644 --- a/storage/backend-test-suite/src/model.rs +++ b/storage/backend-test-suite/src/model.rs @@ -15,7 +15,7 @@ //! A dead-simple reference implementation of some aspects of a storage backend -use storage_core::{backend, Data, DbMapId}; +use storage_core::{Data, DbMapId, backend}; /// A modifying action to apply to a backend or a model #[derive(Debug, PartialEq, Eq, Clone)] diff --git a/storage/backend-test-suite/src/prelude.rs b/storage/backend-test-suite/src/prelude.rs index 61b8a974ea..57f7f751ac 100644 --- a/storage/backend-test-suite/src/prelude.rs +++ b/storage/backend-test-suite/src/prelude.rs @@ -20,10 +20,10 @@ use utils::shallow_clone::ShallowClone; // Re-export a bunch of often used items pub use crate::model::{ApplyActions, Model, WriteAction}; pub use storage_core::{ + DbDesc, DbMapCount, DbMapDesc, DbMapId, DbMapsData, backend::{ Backend, BackendImpl, Data, ReadOps, SharedBackend, SharedBackendImpl, TxRo, TxRw, WriteOps, }, - DbDesc, DbMapCount, DbMapDesc, DbMapId, DbMapsData, }; pub use utils::{sync, thread}; diff --git a/storage/core/src/adaptor/locking.rs b/storage/core/src/adaptor/locking.rs index 7c77f35b04..1babeaa781 100644 --- a/storage/core/src/adaptor/locking.rs +++ b/storage/core/src/adaptor/locking.rs @@ -17,10 +17,10 @@ //! read/write operations, giving a full-featured (albeit not necessarily efficient) backend. use crate::{ + Data, DbDesc, DbMapCount, DbMapId, DbMapsData, adaptor::{Construct, CoreOps}, backend::{self, ReadOps, WriteOps}, util::MapPrefixIter, - Data, DbDesc, DbMapCount, DbMapId, DbMapsData, }; use itertools::EitherOrBoth; diff --git a/storage/failing/src/backend.rs b/storage/failing/src/backend.rs index c717e33c78..5bad381e92 100644 --- a/storage/failing/src/backend.rs +++ b/storage/failing/src/backend.rs @@ -18,7 +18,7 @@ use std::{ sync::{Arc, Mutex}, }; -use storage_core::{backend, Data, DbMapId}; +use storage_core::{Data, DbMapId, backend}; use test_utils::random::{RngExt as _, Seed, TestRng}; use utils::{atomics::AcqRelAtomicU32, shallow_clone::ShallowClone}; diff --git a/storage/failing/src/config/mod.rs b/storage/failing/src/config/mod.rs index 05f7a175bd..0151e90697 100644 --- a/storage/failing/src/config/mod.rs +++ b/storage/failing/src/config/mod.rs @@ -15,7 +15,7 @@ use std::collections::BTreeMap; -use storage_core::{error::Recoverable as StorageError, DbMapId}; +use storage_core::{DbMapId, error::Recoverable as StorageError}; use test_utils::random::{IteratorRandom, Rng, RngExt as _}; use utils::ensure; diff --git a/storage/failing/src/lib.rs b/storage/failing/src/lib.rs index 5b972ab7ea..75450955a3 100644 --- a/storage/failing/src/lib.rs +++ b/storage/failing/src/lib.rs @@ -19,5 +19,5 @@ mod backend; mod config; pub use backend::{Failing, FailingImpl}; -pub use config::{builder::Builder, ErrorGeneration, ErrorSet, FailureConfig}; +pub use config::{ErrorGeneration, ErrorSet, FailureConfig, builder::Builder}; pub use storage_core::error::Recoverable as StorageError; diff --git a/storage/inmemory/src/lib.rs b/storage/inmemory/src/lib.rs index 15414305df..a823cee048 100644 --- a/storage/inmemory/src/lib.rs +++ b/storage/inmemory/src/lib.rs @@ -14,10 +14,10 @@ // limitations under the License. use storage_core::{ + Data, DbDesc, DbMapId, DbMapsData, adaptor::{self, TransactionLockImpl}, backend, util::MapPrefixIter, - Data, DbDesc, DbMapId, DbMapsData, }; use std::{borrow::Cow, collections::BTreeMap}; diff --git a/storage/lmdb/src/lib.rs b/storage/lmdb/src/lib.rs index 9156f82f5f..59e7e11a1c 100644 --- a/storage/lmdb/src/lib.rs +++ b/storage/lmdb/src/lib.rs @@ -30,7 +30,7 @@ use std::{borrow::Cow, path::PathBuf}; use initial_map_size::InitialMapSize; use lmdb::Cursor; use resize_callback::MapResizeCallback; -use storage_core::{backend, Data, DbDesc, DbMapDesc, DbMapId, DbMapsData}; +use storage_core::{Data, DbDesc, DbMapDesc, DbMapId, DbMapsData, backend}; use utils::const_value::ConstValue; use utils::sync::Arc; diff --git a/storage/lmdb/src/resize_tests.rs b/storage/lmdb/src/resize_tests.rs index a8c95288c2..9d647afe48 100644 --- a/storage/lmdb/src/resize_tests.rs +++ b/storage/lmdb/src/resize_tests.rs @@ -19,7 +19,7 @@ use rstest::rstest; use memsize::MemSize; use storage_core::backend::{Backend, BackendImpl, ReadOps, SharedBackendImpl, TxRw, WriteOps}; -use test_utils::random::{make_seedable_rng, CryptoRng, RngExt as _, Seed}; +use test_utils::random::{CryptoRng, RngExt as _, Seed, make_seedable_rng}; use super::*; @@ -115,7 +115,10 @@ fn auto_map_resize_between_txs(#[case] seed: Seed) { assert_eq!(ro_tx.get(DbMapId::new(0), &key).unwrap().unwrap(), val); } - assert!(resizes_via_commit_count > 0, "Not a single resize was scheduled after a transaction... this is very unlikely based on the test structure"); + assert!( + resizes_via_commit_count > 0, + "Not a single resize was scheduled after a transaction... this is very unlikely based on the test structure" + ); }) } @@ -211,8 +214,8 @@ fn auto_map_resize_between_puts(#[case] seed: Seed) { } assert!( - resizes_via_put_count > 0, - "Not a single resize was scheduled after a write/put... this is very unlikely based on the test structure" - ); + resizes_via_put_count > 0, + "Not a single resize was scheduled after a write/put... this is very unlikely based on the test structure" + ); }) } diff --git a/storage/sqlite/src/lib.rs b/storage/sqlite/src/lib.rs index cc9c4b8e2d..8f63b095cd 100644 --- a/storage/sqlite/src/lib.rs +++ b/storage/sqlite/src/lib.rs @@ -31,7 +31,7 @@ use std::{ use rusqlite::{Connection, OpenFlags, OptionalExtension}; use error::process_sqlite_error; -use storage_core::{backend, Data, DbDesc, DbMapId}; +use storage_core::{Data, DbDesc, DbMapId, backend}; use crate::queries::SqliteQueries; diff --git a/storage/sqlite/src/tests.rs b/storage/sqlite/src/tests.rs index 3a93e4a210..5e8412fb33 100644 --- a/storage/sqlite/src/tests.rs +++ b/storage/sqlite/src/tests.rs @@ -14,10 +14,10 @@ // limitations under the License. use storage::error::Fatal; -use storage_backend_test_suite::prelude::{desc, MAPID}; +use storage_backend_test_suite::prelude::{MAPID, desc}; use storage_core::{ - backend::{BackendImpl as _, ReadOps as _, TxRw as _, WriteOps as _}, Backend as _, + backend::{BackendImpl as _, ReadOps as _, TxRw as _, WriteOps as _}, }; use test_utils::assert_matches_return_val; diff --git a/storage/src/database/internal.rs b/storage/src/database/internal.rs index 04d7de36fc..92e58e2881 100644 --- a/storage/src/database/internal.rs +++ b/storage/src/database/internal.rs @@ -18,10 +18,10 @@ use std::borrow::Cow; use crate::schema; -use serialization::{encoded::Encoded, EncodeLike}; +use serialization::{EncodeLike, encoded::Encoded}; use storage_core::{ - backend::{self, ReadOps}, Backend, DbMapId, + backend::{self, ReadOps}, }; /// Map high-level transaction type to the backend-specific implementation type diff --git a/storage/src/database/mod.rs b/storage/src/database/mod.rs index 41425362a4..d7963fd968 100644 --- a/storage/src/database/mod.rs +++ b/storage/src/database/mod.rs @@ -24,10 +24,10 @@ use internal::{EntryIterator, TxImpl}; use utils::shallow_clone::ShallowClone; use crate::schema::{self, Schema}; -use serialization::{encoded::Encoded, Encode, EncodeLike}; +use serialization::{Encode, EncodeLike, encoded::Encoded}; use storage_core::{ - backend::{self, TxRw, WriteOps}, Backend, DbMapId, SharedBackend, + backend::{self, TxRw, WriteOps}, }; /// The main storage type diff --git a/storage/src/database/raw.rs b/storage/src/database/raw.rs index 4f5e6ab936..d4bb9be998 100644 --- a/storage/src/database/raw.rs +++ b/storage/src/database/raw.rs @@ -16,11 +16,11 @@ //! Raw database representation for contents inspection purposes use crate::{ - schema::{self, HasDbMap, Schema}, TransactionRo, + schema::{self, HasDbMap, Schema}, }; use std::collections::BTreeMap; -use storage_core::{backend::ReadOps, Backend}; +use storage_core::{Backend, backend::ReadOps}; pub use storage_core::Data; diff --git a/storage/src/lib.rs b/storage/src/lib.rs index 2376616b33..c1eb873847 100644 --- a/storage/src/lib.rs +++ b/storage/src/lib.rs @@ -100,8 +100,8 @@ pub mod schema; // Re-export user-facing items from core pub use order_preserving_value::OrderPreservingValue; pub use storage_core::{ - error, Backend, BackendImpl, BackendWithSendableTransactions, DbDesc, Error, Result, - SharedBackend, SharedBackendImpl, + Backend, BackendImpl, BackendWithSendableTransactions, DbDesc, Error, Result, SharedBackend, + SharedBackendImpl, error, }; // Re-export the interface types diff --git a/storage/src/order_preserving_value.rs b/storage/src/order_preserving_value.rs index 3f344d2a50..0f210645be 100644 --- a/storage/src/order_preserving_value.rs +++ b/storage/src/order_preserving_value.rs @@ -75,9 +75,8 @@ mod tests { use rstest::rstest; use test_utils::random::{ - make_seedable_rng, + Rng, RngExt as _, Seed, make_seedable_rng, randomness::{self, distributions::Distribution}, - Rng, RngExt as _, Seed, }; use super::*; diff --git a/subsystem/src/calls/blocking.rs b/subsystem/src/calls/blocking.rs index 22b532ba9a..77e997fa79 100644 --- a/subsystem/src/calls/blocking.rs +++ b/subsystem/src/calls/blocking.rs @@ -15,7 +15,7 @@ //! Blocking interface to subsystem. -use crate::{error::CallError, CallResult, Handle}; +use crate::{CallResult, Handle, error::CallError}; use futures::future::BoxFuture; use utils::shallow_clone::ShallowClone; diff --git a/subsystem/src/lib.rs b/subsystem/src/lib.rs index 8def8b2f17..a9e1fc3ce6 100644 --- a/subsystem/src/lib.rs +++ b/subsystem/src/lib.rs @@ -42,7 +42,7 @@ pub mod error; pub mod wrappers; pub use crate::{ - calls::{blocking, CallResponse, CallResult, Handle, SubmitOnlyHandle}, + calls::{CallResponse, CallResult, Handle, SubmitOnlyHandle, blocking}, manager::{Manager, ManagerConfig, ManagerJoinHandle, ShutdownTrigger}, subsystem::Subsystem, }; diff --git a/subsystem/src/manager/manager_impl.rs b/subsystem/src/manager/manager_impl.rs index 9281351c45..a1024569b1 100644 --- a/subsystem/src/manager/manager_impl.rs +++ b/subsystem/src/manager/manager_impl.rs @@ -27,7 +27,7 @@ use utils::{ tokio_spawn_in_current_tracing_span, tokio_spawn_in_tracing_span, }; -use crate::{task, wrappers, Handle, ManagerConfig, SubmitOnlyHandle, Subsystem}; +use crate::{Handle, ManagerConfig, SubmitOnlyHandle, Subsystem, task, wrappers}; use super::shutdown_signal::shutdown_signal; diff --git a/subsystem/src/task.rs b/subsystem/src/task.rs index d86b810000..2c87523a70 100644 --- a/subsystem/src/task.rs +++ b/subsystem/src/task.rs @@ -18,7 +18,7 @@ use std::future::IntoFuture; use tokio::{ - sync::{mpsc, oneshot, RwLock}, + sync::{RwLock, mpsc, oneshot}, task::JoinSet, }; use tracing::Instrument; @@ -26,7 +26,7 @@ use tracing::Instrument; use logging::log; use utils::{once_destructor::OnceDestructor, sync::Arc, tokio_spawn_in_join_set}; -use crate::{calls::Action, Subsystem}; +use crate::{Subsystem, calls::Action}; /// Handle a task completion result pub fn handle_result(full_name: &str, task_type: &str, res: Result<(), tokio::task::JoinError>) { diff --git a/subsystem/tests/shutdown.rs b/subsystem/tests/shutdown.rs index 681b55d5b4..0e7b662aa9 100644 --- a/subsystem/tests/shutdown.rs +++ b/subsystem/tests/shutdown.rs @@ -18,7 +18,7 @@ use std::{sync::Arc, time::Duration}; use subsystem::wrappers; -use tokio::sync::{watch, Mutex}; +use tokio::sync::{Mutex, watch}; use utils::{set_flag::SetFlag, tokio_spawn}; // A subsystem that blocks the shutdown process. diff --git a/test-rpc-functions/src/lib.rs b/test-rpc-functions/src/lib.rs index d5f55ab04c..a5df2c3065 100644 --- a/test-rpc-functions/src/lib.rs +++ b/test-rpc-functions/src/lib.rs @@ -16,7 +16,7 @@ use std::sync::Arc; use chainstate_types::vrf_tools::ProofOfStakeVRFError; -use common::chain::{signature::DestinationSigError, ChainConfig}; +use common::chain::{ChainConfig, signature::DestinationSigError}; use crypto::key::SignatureError; use interface::{ rpc_test_interface::RpcTestFunctionsInterface, rpc_test_interface_impl::RpcTestFunctionsImpl, diff --git a/test-rpc-functions/src/rpc.rs b/test-rpc-functions/src/rpc.rs index f669680d9a..a64ddd36bc 100644 --- a/test-rpc-functions/src/rpc.rs +++ b/test-rpc-functions/src/rpc.rs @@ -20,31 +20,30 @@ use std::str::FromStr; use chainstate::rpc::RpcUtxoOutpoint; use chainstate_types::vrf_tools::{construct_transcript, verify_vrf_and_get_vrf_output}; use common::{ - address::{dehexify, Address}, + address::{Address, dehexify}, chain::{ + Destination, OutPointSourceId, PoolId, SignedTransaction, Transaction, TxInput, TxOutput, block::timestamp::BlockTimestamp, config::{ - regtest::{genesis_values, GenesisStakingSettings}, EpochIndex, + regtest::{GenesisStakingSettings, genesis_values}, }, output_value::OutputValue, partially_signed_transaction::PartiallySignedTransaction, signature::inputsig::{ - arbitrary_message, + InputWitness, arbitrary_message, authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, - InputWitness, }, stakelock::StakePoolData, tokens::TokenId, - Destination, OutPointSourceId, PoolId, SignedTransaction, Transaction, TxInput, TxOutput, }, - primitives::{Amount, Id, Idable, H256}, + primitives::{Amount, H256, Id, Idable}, }; use crypto::key::Signature; use serialization::{ + Encode as _, hex::{HexDecode, HexEncode}, hex_encoded::HexEncoded, - Encode as _, }; use crate::{RpcTestFunctionsError, RpcTestFunctionsHandle}; diff --git a/test-utils/src/lib.rs b/test-utils/src/lib.rs index 21282b1277..72e219ca03 100644 --- a/test-utils/src/lib.rs +++ b/test-utils/src/lib.rs @@ -26,7 +26,7 @@ use std::{collections::BTreeMap, convert::Infallible}; use hex::ToHex; use itertools::Itertools; -use randomness::{distributions::uniform::SampleRange, Rng, RngExt as _}; +use randomness::{Rng, RngExt as _, distributions::uniform::SampleRange}; pub use basic_test_time_getter::BasicTestTimeGetter; pub use env::{remove_env_var, set_env_var}; @@ -188,7 +188,7 @@ macro_rules! assert_matches { #[cfg(test)] mod tests { use super::*; - use crate::random::{make_seedable_rng, Seed}; + use crate::random::{Seed, make_seedable_rng}; use rstest::rstest; mod match_macro_tests { diff --git a/test-utils/src/random.rs b/test-utils/src/random.rs index 6275c0ba9e..af25d0b9bb 100644 --- a/test-utils/src/random.rs +++ b/test-utils/src/random.rs @@ -17,9 +17,9 @@ use std::{convert::Infallible, num::ParseIntError, str::FromStr}; use rand_chacha::ChaChaRng; -use randomness::{rand_core_utils, IndexedRandom as _, TryCryptoRng, TryRng}; +use randomness::{IndexedRandom as _, TryCryptoRng, TryRng, rand_core_utils}; -pub use randomness::{self, seq::IteratorRandom, CryptoRng, Rng, RngExt, SeedableRng}; +pub use randomness::{self, CryptoRng, Rng, RngExt, SeedableRng, seq::IteratorRandom}; #[derive(Debug, Copy, Clone)] pub struct Seed(pub u64); diff --git a/test-utils/src/test_dir.rs b/test-utils/src/test_dir.rs index 87cfaf2595..778aa73946 100644 --- a/test-utils/src/test_dir.rs +++ b/test-utils/src/test_dir.rs @@ -19,10 +19,10 @@ use std::{ fs, io, path::{Path, PathBuf}, sync::{ + Arc, // Note: we can't use simplified atomics or loom version of std atomics here, // because this code can be called from tests that are not loom-ready. atomic::{AtomicU32, Ordering}, - Arc, }, time::Duration, }; diff --git a/test-utils/src/token_utils.rs b/test-utils/src/token_utils.rs index 96dcd90582..3379981597 100644 --- a/test-utils/src/token_utils.rs +++ b/test-utils/src/token_utils.rs @@ -17,17 +17,17 @@ use strum::IntoEnumIterator as _; use common::{ chain::{ + Destination, config::ChainConfig, tokens::{ IsTokenFreezable, Metadata, NftIssuanceV0, TokenCreator, TokenIssuanceV0, TokenIssuanceV1, TokenTotalSupply, TokenTotalSupplyTag, }, - Destination, }, - primitives::{amount, Amount}, + primitives::{Amount, amount}, }; use crypto::key::{KeyKind, PrivateKey}; -use randomness::{seq::IteratorRandom as _, CryptoRng, Rng, RngExt as _}; +use randomness::{CryptoRng, Rng, RngExt as _, seq::IteratorRandom as _}; use serialization::extras::non_empty_vec::DataOrNoVec; use crate::random_ascii_alphanumeric_string; diff --git a/test/runner/functional.rs b/test/runner/functional.rs index b234a46c67..8d42774afc 100644 --- a/test/runner/functional.rs +++ b/test/runner/functional.rs @@ -20,7 +20,7 @@ //! The framework is taken from Bitcoin and is written in Python. It is ultimately responsible for //! running the tests. All command line arguments are forwarded to it. -use libtest_mimic::{run, Arguments as HarnessArgs, Failed, Trial}; +use libtest_mimic::{Arguments as HarnessArgs, Failed, Trial, run}; use std::env::consts::EXE_SUFFIX; use std::fs; use std::path::PathBuf; diff --git a/tokens-accounting/src/cache.rs b/tokens-accounting/src/cache.rs index c49faa11df..c1eaadd74f 100644 --- a/tokens-accounting/src/cache.rs +++ b/tokens-accounting/src/cache.rs @@ -16,14 +16,15 @@ use accounting::combine_amount_delta; use common::{ chain::{ - tokens::{IsTokenUnfreezable, TokenId, TokenTotalSupply}, Destination, + tokens::{IsTokenUnfreezable, TokenId, TokenTotalSupply}, }, primitives::Amount, }; use logging::log; use crate::{ + FlushableTokensAccountingView, data::{TokenData, TokensAccountingDeltaData}, error::Error, operations::{ @@ -32,7 +33,6 @@ use crate::{ UnfreezeTokenUndo, UnmintTokenUndo, }, view::TokensAccountingView, - FlushableTokensAccountingView, }; pub struct TokensAccountingCache

{ diff --git a/tokens-accounting/src/data.rs b/tokens-accounting/src/data.rs index 21b6494b6c..c0a523e0bf 100644 --- a/tokens-accounting/src/data.rs +++ b/tokens-accounting/src/data.rs @@ -18,11 +18,11 @@ use std::collections::BTreeMap; use accounting::{DeltaAmountCollection, DeltaDataCollection, DeltaDataUndoCollection}; use common::{ chain::{ + Destination, tokens::{ IsTokenFreezable, IsTokenFrozen, IsTokenUnfreezable, TokenId, TokenIssuance, TokenTotalSupply, }, - Destination, }, primitives::Amount, }; diff --git a/tokens-accounting/src/lib.rs b/tokens-accounting/src/lib.rs index 40d6a1d27f..430515dff9 100644 --- a/tokens-accounting/src/lib.rs +++ b/tokens-accounting/src/lib.rs @@ -27,10 +27,10 @@ pub use { TokensAccountingDeltaUndoData, }, error::Error, - operations::{random_undo_for_test, TokenAccountingUndo, TokensAccountingOperations}, + operations::{TokenAccountingUndo, TokensAccountingOperations, random_undo_for_test}, storage::{ - db::TokensAccountingDB, in_memory::InMemoryTokensAccounting, TokensAccountingStorageRead, - TokensAccountingStorageWrite, + TokensAccountingStorageRead, TokensAccountingStorageWrite, db::TokensAccountingDB, + in_memory::InMemoryTokensAccounting, }, view::{FlushableTokensAccountingView, TokensAccountingView}, }; diff --git a/tokens-accounting/src/operations.rs b/tokens-accounting/src/operations.rs index cdecceacc8..9c5a44f158 100644 --- a/tokens-accounting/src/operations.rs +++ b/tokens-accounting/src/operations.rs @@ -18,8 +18,8 @@ use strum::EnumCount; use accounting::DataDeltaUndo; use common::{ chain::{ - tokens::{IsTokenUnfreezable, TokenId}, Destination, + tokens::{IsTokenUnfreezable, TokenId}, }, primitives::{Amount, H256}, }; @@ -110,7 +110,7 @@ pub trait TokensAccountingOperations { fn mint_tokens(&mut self, id: TokenId, amount_to_add: Amount) -> Result; fn unmint_tokens(&mut self, id: TokenId, amount_to_burn: Amount) - -> Result; + -> Result; fn lock_circulating_supply(&mut self, id: TokenId) -> Result; diff --git a/tokens-accounting/src/storage/db.rs b/tokens-accounting/src/storage/db.rs index d7d6235edd..30896fccde 100644 --- a/tokens-accounting/src/storage/db.rs +++ b/tokens-accounting/src/storage/db.rs @@ -16,15 +16,15 @@ use std::{collections::BTreeMap, ops::Neg}; use accounting::{ - combine_amount_delta, combine_data_with_delta, DeltaAmountCollection, DeltaDataUndoCollection, + DeltaAmountCollection, DeltaDataUndoCollection, combine_amount_delta, combine_data_with_delta, }; use common::{chain::tokens::TokenId, primitives::Amount}; use utils::tap_log::TapLog; use crate::{ + FlushableTokensAccountingView, TokenData, TokensAccountingView, data::{TokensAccountingDeltaData, TokensAccountingDeltaUndoData}, error::Error, - FlushableTokensAccountingView, TokenData, TokensAccountingView, }; use super::{TokensAccountingStorageRead, TokensAccountingStorageWrite}; diff --git a/tokens-accounting/src/tests/operations_tests.rs b/tokens-accounting/src/tests/operations_tests.rs index 1356adf77d..575727bacc 100644 --- a/tokens-accounting/src/tests/operations_tests.rs +++ b/tokens-accounting/src/tests/operations_tests.rs @@ -19,17 +19,17 @@ use rstest::rstest; use common::{ chain::{ + Destination, tokens::{ IsTokenFreezable, IsTokenFrozen, IsTokenUnfreezable, TokenId, TokenIssuance, TokenIssuanceV1, TokenTotalSupply, }, - Destination, }, primitives::Amount, }; use randomness::{Rng, RngExt as _}; use test_utils::{ - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, random_ascii_alphanumeric_string, }; diff --git a/utils/benches/benches.rs b/utils/benches/benches.rs index ddd66ec36d..590a8ddc10 100644 --- a/utils/benches/benches.rs +++ b/utils/benches/benches.rs @@ -13,7 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use criterion::{black_box, criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, black_box, criterion_group, criterion_main}; use randomness::make_pseudo_rng; use utils::bloom_filters::rolling_bloom_filter::RollingBloomFilter; diff --git a/utils/build.rs b/utils/build.rs index c51b258f2e..e5c094c937 100644 --- a/utils/build.rs +++ b/utils/build.rs @@ -13,7 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::path::{PathBuf, MAIN_SEPARATOR}; +use std::path::{MAIN_SEPARATOR, PathBuf}; fn main() { let manifest_dir = diff --git a/utils/log_error/src/lib.rs b/utils/log_error/src/lib.rs index fbdc8796fa..12eb6fc2cc 100644 --- a/utils/log_error/src/lib.rs +++ b/utils/log_error/src/lib.rs @@ -17,10 +17,10 @@ use derive_more::Display; use proc_macro::TokenStream; use quote::quote; use syn::{ + Error, ItemFn, LitStr, ReturnType, Token, parse::{Parse, ParseStream}, parse_quote, punctuated::Punctuated, - Error, ItemFn, LitStr, ReturnType, Token, }; /// A macro that logs errors returned by the function to which it is attached, mentioning diff --git a/utils/networking/src/broadcaster.rs b/utils/networking/src/broadcaster.rs index 1ce728b2af..23c398f6c2 100644 --- a/utils/networking/src/broadcaster.rs +++ b/utils/networking/src/broadcaster.rs @@ -16,7 +16,7 @@ //! Broadcaster is a reliable version of [tokio::sync::broadcast]. use tokio::sync::mpsc; -use tokio_stream::{wrappers::UnboundedReceiverStream, Stream}; +use tokio_stream::{Stream, wrappers::UnboundedReceiverStream}; /// A reliable version of [tokio::sync::broadcast], sender part. /// diff --git a/utils/networking/src/ip_or_socket_address.rs b/utils/networking/src/ip_or_socket_address.rs index a1d5e67c24..d4e9653655 100644 --- a/utils/networking/src/ip_or_socket_address.rs +++ b/utils/networking/src/ip_or_socket_address.rs @@ -77,7 +77,7 @@ impl rpc_description::HasValueHint for IpOrSocketAddress { #[cfg(test)] mod tests { - use serde_test::{assert_tokens, Token}; + use serde_test::{Token, assert_tokens}; use super::*; diff --git a/utils/src/atomics/atomic_traits.rs b/utils/src/atomics/atomic_traits.rs index 662479eb19..602d0ecd14 100644 --- a/utils/src/atomics/atomic_traits.rs +++ b/utils/src/atomics/atomic_traits.rs @@ -21,8 +21,8 @@ //! We also omit deprecated functions, such as `compare_and_swap`, and don't support `AtomicPtr`. use crate::sync::atomic::{ - AtomicBool, AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicIsize, AtomicU16, AtomicU32, - AtomicU64, AtomicU8, AtomicUsize, Ordering, + AtomicBool, AtomicI8, AtomicI16, AtomicI32, AtomicI64, AtomicIsize, AtomicU8, AtomicU16, + AtomicU32, AtomicU64, AtomicUsize, Ordering, }; /// A trait that contains basic atomic operations common for all atomic types. diff --git a/utils/src/atomics/simple_atomic.rs b/utils/src/atomics/simple_atomic.rs index 2841915534..6958cbbae4 100644 --- a/utils/src/atomics/simple_atomic.rs +++ b/utils/src/atomics/simple_atomic.rs @@ -35,7 +35,7 @@ //! in this case basically encodes the purpose of the atomic in its type's name and makes //! the orderings a part of the module's interface. -use crate::atomics::{atomic_traits::HasStdAtomic, AtomicNumTrait, AtomicTrait}; +use crate::atomics::{AtomicNumTrait, AtomicTrait, atomic_traits::HasStdAtomic}; use std::marker::PhantomData; use crate::concurrency_impl::sync::atomic::Ordering; diff --git a/utils/src/blockuntilzero.rs b/utils/src/blockuntilzero.rs index eed032d5e6..5ee0d2e69a 100644 --- a/utils/src/blockuntilzero.rs +++ b/utils/src/blockuntilzero.rs @@ -15,7 +15,7 @@ use num_traits::{One, Zero}; use std::{ - sync::{atomic::Ordering, Arc}, + sync::{Arc, atomic::Ordering}, time::Duration, }; diff --git a/utils/src/counttracker.rs b/utils/src/counttracker.rs index c16ea5d654..c548867719 100644 --- a/utils/src/counttracker.rs +++ b/utils/src/counttracker.rs @@ -62,8 +62,8 @@ where #[cfg(test)] mod test { use std::sync::{ - atomic::{AtomicI32, Ordering}, Arc, + atomic::{AtomicI32, Ordering}, }; use super::CountTracker; diff --git a/utils/src/default_data_dir.rs b/utils/src/default_data_dir.rs index 2b7084e740..ef5d2aa4e6 100644 --- a/utils/src/default_data_dir.rs +++ b/utils/src/default_data_dir.rs @@ -44,7 +44,9 @@ pub fn default_data_dir_for_chain(chain_name: &str) -> PathBuf { #[derive(thiserror::Error, Debug)] pub enum PrepareDataDirError { - #[error("Custom data directory '{0}' does not exist. Please create it or use the default data directory.")] + #[error( + "Custom data directory '{0}' does not exist. Please create it or use the default data directory." + )] DoesNotExist(PathBuf), #[error("Failed to create the '{0}' data directory: {1}")] CreateFailed(PathBuf, std::io::Error), @@ -86,7 +88,7 @@ pub fn prepare_data_dir PathBuf>( mod test { use std::io::{Read, Write}; - use randomness::{make_pseudo_rng, RngExt as _}; + use randomness::{RngExt as _, make_pseudo_rng}; use tempfile::TempDir; use super::*; diff --git a/utils/src/exp_rand/test.rs b/utils/src/exp_rand/test.rs index eee2735708..159adc8964 100644 --- a/utils/src/exp_rand/test.rs +++ b/utils/src/exp_rand/test.rs @@ -16,7 +16,7 @@ use super::*; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed, StepRng}; +use test_utils::random::{Seed, StepRng, make_seedable_rng}; #[rstest] #[trace] diff --git a/utils/src/fixed_hash.rs b/utils/src/fixed_hash.rs index ef3d117834..cf09293fbd 100644 --- a/utils/src/fixed_hash.rs +++ b/utils/src/fixed_hash.rs @@ -85,7 +85,7 @@ mod tests { use randomness::RngExt as _; use serialization::{Decode, Encode}; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; construct_fixed_hash! { #[derive(Encode, Decode)] diff --git a/utils/src/maybe_encrypted.rs b/utils/src/maybe_encrypted.rs index 1eb64112a4..a74823fbd8 100644 --- a/utils/src/maybe_encrypted.rs +++ b/utils/src/maybe_encrypted.rs @@ -109,7 +109,7 @@ mod tests { use crypto::symkey::SymmetricKeyKind; use randomness::RngExt; use rstest::rstest; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use super::*; diff --git a/utils/src/qrcode.rs b/utils/src/qrcode.rs index 08d122206c..c0151d93fb 100644 --- a/utils/src/qrcode.rs +++ b/utils/src/qrcode.rs @@ -116,7 +116,9 @@ pub trait QrCode { .expect("QR code SVG addition overflow"); result += &format!( - "\n", dimension); + "\n", + dimension + ); result += "\t\n"; result += "\t { if id == 0 { - return Err(anyhow::anyhow!("ERROR: It is a mistake to run as root (user with uid=0), as it gives the this software power that it does not need and violates good security practices. Either run the program as non-root, or do the VERY NOT RECOMMENDED THING TO DO, and add the flag `{FORCE_ALLOW_ROOT_FLAG}`")); + return Err(anyhow::anyhow!( + "ERROR: It is a mistake to run as root (user with uid=0), as it gives the this software power that it does not need and violates good security practices. Either run the program as non-root, or do the VERY NOT RECOMMENDED THING TO DO, and add the flag `{FORCE_ALLOW_ROOT_FLAG}`" + )); } } Err(e) => log::error!("Failed to get user id to prevent running as root: {e}"), diff --git a/utils/tests/log_error.rs b/utils/tests/log_error.rs index f4da6d2110..320f538622 100644 --- a/utils/tests/log_error.rs +++ b/utils/tests/log_error.rs @@ -89,11 +89,7 @@ mod test_log_error_trait_helpers { use super::*; pub fn failing_func(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } } @@ -216,20 +212,12 @@ mod test_log_error_macro_non_async_funcs_helpers { #[log_error] pub fn func_returns_unit(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } #[log_error] pub fn func_returns_i32(fail: bool) -> Result { - if fail { - Err(SeriousError) - } else { - Ok(42) - } + if fail { Err(SeriousError) } else { Ok(42) } } #[log_error] @@ -243,11 +231,7 @@ mod test_log_error_macro_non_async_funcs_helpers { #[log_error] pub fn nested_funcs_innermost(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } pub const INNERMOST_FUNC_CALL_LINE: u32 = line!() + 4; @@ -267,112 +251,64 @@ mod test_log_error_macro_non_async_funcs_helpers { #[log_error] #[tracing::instrument] pub fn func_with_tracing_instrument_inner(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } // Same as func_with_tracing_instrument_inner, but here the call to tracing::instrument comes first. #[tracing::instrument] #[log_error] pub fn func_with_tracing_instrument_outer(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } #[log_error(level = "trace")] pub fn func_log_level_trace1(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } #[log_error(level = "tRaCe")] pub fn func_log_level_trace2(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } #[log_error(level = "debug")] pub fn func_log_level_debug1(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } #[log_error(level = "dEbUg")] pub fn func_log_level_debug2(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } #[log_error(level = "info")] pub fn func_log_level_info1(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } #[log_error(level = "iNfO")] pub fn func_log_level_info2(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } #[log_error(level = "warn")] pub fn func_log_level_warn1(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } #[log_error(level = "wArN")] pub fn func_log_level_warn2(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } #[log_error(level = "error")] pub fn func_log_level_error1(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } #[log_error(level = "eRrOr")] pub fn func_log_level_error2(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } } @@ -514,20 +450,12 @@ mod test_log_error_macro_async_funcs_helpers { #[log_error] pub async fn func_returns_unit(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } #[log_error] pub async fn func_returns_i32(fail: bool) -> Result { - if fail { - Err(SeriousError) - } else { - Ok(42) - } + if fail { Err(SeriousError) } else { Ok(42) } } #[log_error] @@ -541,11 +469,7 @@ mod test_log_error_macro_async_funcs_helpers { #[log_error] pub async fn nested_funcs_innermost(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } pub const INNERMOST_FUNC_CALL_LINE: u32 = line!() + 4; @@ -577,32 +501,20 @@ mod test_log_error_macro_async_funcs_helpers { #[log_error(level = "trace")] pub async fn func_log_level_trace(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } #[log_error] #[tracing::instrument] pub async fn func_with_tracing_instrument_inner(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } // Same as func_with_tracing_instrument_inner, but here the call to tracing::instrument comes first. #[tracing::instrument] #[log_error] pub async fn func_with_tracing_instrument_outer(fail: bool) -> Result<(), SeriousError> { - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } // Note: for CapturesLifetime cases, `mut self` is important. @@ -613,11 +525,7 @@ mod test_log_error_macro_async_funcs_helpers { pub async fn func(&mut self, fail: bool) -> Result<(), SeriousError> { let _ = self.0.to_owned(); - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } } @@ -629,11 +537,7 @@ mod test_log_error_macro_async_funcs_helpers { let _ = self.0.to_owned(); let _ = self.1.to_owned(); - if fail { - Err(SeriousError) - } else { - Ok(()) - } + if fail { Err(SeriousError) } else { Ok(()) } } } } @@ -853,8 +757,8 @@ mod log_output { }; use logging::{ - init_logging_generic, write_to_make_writer, LogStyle, ValueOrEnvVar, - ValueOrEnvVarWithDefault, WriterSettings, + LogStyle, ValueOrEnvVar, ValueOrEnvVarWithDefault, WriterSettings, init_logging_generic, + write_to_make_writer, }; #[derive(Clone)] diff --git a/utils/typename-derive/src/lib.rs b/utils/typename-derive/src/lib.rs index 2e17393555..b15ef3622a 100644 --- a/utils/typename-derive/src/lib.rs +++ b/utils/typename-derive/src/lib.rs @@ -16,7 +16,7 @@ use itertools::Itertools; use proc_macro::{self, TokenStream}; use quote::quote; -use syn::{parse_macro_input, DeriveInput}; +use syn::{DeriveInput, parse_macro_input}; #[proc_macro_derive(TypeName)] pub fn derive(input: TokenStream) -> TokenStream { diff --git a/utxo/src/cache.rs b/utxo/src/cache.rs index 68238e7f34..56a07742e1 100644 --- a/utxo/src/cache.rs +++ b/utxo/src/cache.rs @@ -14,15 +14,15 @@ // limitations under the License. use crate::{ - utxo_entry::{IsDirty, IsFresh, UtxoEntry}, Error, FlushableUtxoView, Utxo, UtxoSource, UtxosBlockRewardUndo, UtxosTxUndo, UtxosTxUndoWithSources, UtxosView, + utxo_entry::{IsDirty, IsFresh, UtxoEntry}, }; use common::{ chain::{ + GenBlock, OutPointSourceId, Transaction, TxInput, TxOutput, UtxoOutPoint, block::{BlockReward, BlockRewardTransactable}, signature::Signable, - GenBlock, OutPointSourceId, Transaction, TxInput, TxOutput, UtxoOutPoint, }, primitives::{BlockHeight, Id, Idable}, }; @@ -525,13 +525,13 @@ mod unit_test { use common::primitives::H256; use test_utils::{ - random::{make_seedable_rng, Seed}, UnwrapInfallible as _, + random::{Seed, make_seedable_rng}, }; use super::*; - use crate::tests::test_helper::{empty_test_utxos_view, insert_single_entry, Presence}; + use crate::tests::test_helper::{Presence, empty_test_utxos_view, insert_single_entry}; #[rstest] #[trace] diff --git a/utxo/src/error.rs b/utxo/src/error.rs index d10b451c31..8fd95df9c6 100644 --- a/utxo/src/error.rs +++ b/utxo/src/error.rs @@ -14,7 +14,7 @@ // limitations under the License. use common::{ - chain::{block::GenBlock, OutPointSourceId, Transaction}, + chain::{OutPointSourceId, Transaction, block::GenBlock}, primitives::Id, }; use thiserror::Error; diff --git a/utxo/src/lib.rs b/utxo/src/lib.rs index e93ae5c985..060edf28ca 100644 --- a/utxo/src/lib.rs +++ b/utxo/src/lib.rs @@ -24,13 +24,13 @@ mod view; pub use crate::{ cache::{ConsumedUtxoCache, UtxosCache}, error::Error, - storage::{in_memory::UtxosDBInMemoryImpl, UtxosDB, UtxosStorageRead, UtxosStorageWrite}, + storage::{UtxosDB, UtxosStorageRead, UtxosStorageWrite, in_memory::UtxosDBInMemoryImpl}, undo::{ ConsumedUtxosBlockUndo, UtxosBlockRewardUndo, UtxosBlockUndo, UtxosBlockUndoError, UtxosTxUndo, UtxosTxUndoWithSources, }, utxo::{Utxo, UtxoSource}, - view::{flush_to_base, FlushableUtxoView, UtxosView}, + view::{FlushableUtxoView, UtxosView, flush_to_base}, }; #[cfg(test)] diff --git a/utxo/src/storage/test.rs b/utxo/src/storage/test.rs index ae121e5434..2c17a81c91 100644 --- a/utxo/src/storage/test.rs +++ b/utxo/src/storage/test.rs @@ -15,26 +15,26 @@ use super::{in_memory::UtxosDBInMemoryImpl, *}; use crate::{ - tests::test_helper::{convert_to_utxo, create_tx_inputs, create_tx_outputs, create_utxo}, - utxo_entry::{IsDirty, IsFresh, UtxoEntry}, ConsumedUtxoCache, Error::*, FlushableUtxoView, UtxoSource, UtxosBlockUndo, UtxosView, + tests::test_helper::{convert_to_utxo, create_tx_inputs, create_tx_outputs, create_utxo}, + utxo_entry::{IsDirty, IsFresh, UtxoEntry}, }; use common::{ chain::{ - block::{timestamp::BlockTimestamp, BlockReward}, + Block, OutPointSourceId, Transaction, TxInput, + block::{BlockReward, timestamp::BlockTimestamp}, signature::inputsig::InputWitness, signed_transaction::SignedTransaction, - Block, OutPointSourceId, Transaction, TxInput, }, - primitives::{BlockHeight, Id, Idable, H256}, + primitives::{BlockHeight, H256, Id, Idable}, }; use itertools::Itertools; use randomness::{CryptoRng, RngExt as _}; use rstest::rstest; use std::collections::BTreeMap; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; fn create_transactions( rng: &mut impl CryptoRng, diff --git a/utxo/src/tests/mod.rs b/utxo/src/tests/mod.rs index 5499f90aa8..0f058ac6d7 100644 --- a/utxo/src/tests/mod.rs +++ b/utxo/src/tests/mod.rs @@ -24,35 +24,34 @@ use rstest::rstest; use common::{ chain::{ + AccountNonce, AccountSpending, DelegationId, Destination, OutPointSourceId, PoolId, + Transaction, TxInput, TxOutput, UtxoOutPoint, block::{ + Block, BlockReward, ConsensusData, consensus_data::{PoSData, PoWData}, timestamp::BlockTimestamp, - Block, BlockReward, ConsensusData, }, output_value::OutputValue, signature::inputsig::InputWitness, - AccountNonce, AccountSpending, DelegationId, Destination, OutPointSourceId, PoolId, - Transaction, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{Amount, BlockHeight, Compact, Id, Idable, H256}, + primitives::{Amount, BlockHeight, Compact, H256, Id, Idable}, }; use crypto::vrf::VRFKeyKind; -use randomness::{seq, CryptoRng, Rng, RngExt as _}; +use randomness::{CryptoRng, Rng, RngExt as _, seq}; use test_utils::{ - random::{make_seedable_rng, Seed}, UnwrapInfallible as _, + random::{Seed, make_seedable_rng}, }; use crate::{ - flush_to_base, + ConsumedUtxoCache, + Error::{self, *}, + FlushableUtxoView, Utxo, UtxoSource, UtxosCache, UtxosTxUndo, UtxosView, flush_to_base, tests::test_helper::{ - create_tx_outputs, empty_test_utxos_view, Presence::{self, *}, + create_tx_outputs, empty_test_utxos_view, }, utxo_entry::{IsDirty, IsFresh, UtxoEntry}, - ConsumedUtxoCache, - Error::{self, *}, - FlushableUtxoView, Utxo, UtxoSource, UtxosCache, UtxosTxUndo, UtxosView, }; fn make_pool_id(rng: &mut impl Rng) -> PoolId { @@ -506,9 +505,11 @@ fn multiple_update_utxos_test(#[case] seed: Seed) { // let's test `add_utxos` let tx = Transaction::new(0x00, vec![], create_tx_outputs(&mut rng, 10)).unwrap(); - assert!(cache - .add_utxos_from_tx(&tx, UtxoSource::Blockchain(BlockHeight::new(2)), false) - .is_ok()); + assert!( + cache + .add_utxos_from_tx(&tx, UtxoSource::Blockchain(BlockHeight::new(2)), false) + .is_ok() + ); // check that the outputs of tx are added in the cache. tx.outputs().iter().enumerate().for_each(|(i, x)| { @@ -575,14 +576,16 @@ fn check_add_utxos_from_block_reward(#[case] seed: Seed) { let block_reward = BlockReward::new(create_tx_outputs(&mut rng, 10)); let block_id = Id::new(H256::random_using(&mut rng)); - assert!(cache - .add_utxos_from_block_reward( - &block_reward, - UtxoSource::Blockchain(BlockHeight::new(2)), - &block_id, - false - ) - .is_ok()); + assert!( + cache + .add_utxos_from_block_reward( + &block_reward, + UtxoSource::Blockchain(BlockHeight::new(2)), + &block_id, + false + ) + .is_ok() + ); block_reward.outputs().iter().enumerate().for_each(|(i, x)| { let outpoint = UtxoOutPoint::new(OutPointSourceId::BlockReward(block_id), i as u32); diff --git a/utxo/src/tests/simulation.rs b/utxo/src/tests/simulation.rs index f35f6bbc4a..39fe929e6c 100644 --- a/utxo/src/tests/simulation.rs +++ b/utxo/src/tests/simulation.rs @@ -20,8 +20,8 @@ use rstest::rstest; use common::chain::UtxoOutPoint; use randomness::{CryptoRng, RngExt as _}; use test_utils::{ - random::{make_seedable_rng, Seed}, UnwrapInfallible as _, + random::{Seed, make_seedable_rng}, }; use crate::{ConsumedUtxoCache, FlushableUtxoView, UtxosCache, UtxosView}; diff --git a/utxo/src/tests/simulation_with_undo.rs b/utxo/src/tests/simulation_with_undo.rs index de2f39c5ab..3b5253776a 100644 --- a/utxo/src/tests/simulation_with_undo.rs +++ b/utxo/src/tests/simulation_with_undo.rs @@ -18,13 +18,13 @@ use std::{collections::BTreeMap, convert::Infallible}; use rstest::rstest; use common::{ - chain::{block::BlockReward, OutPointSourceId, Transaction, TxInput, UtxoOutPoint}, - primitives::{BlockHeight, Id, Idable, H256}, + chain::{OutPointSourceId, Transaction, TxInput, UtxoOutPoint, block::BlockReward}, + primitives::{BlockHeight, H256, Id, Idable}, }; use randomness::{CryptoRng, RngExt as _}; use test_utils::{ - random::{make_seedable_rng, Seed}, UnwrapInfallible as _, + random::{Seed, make_seedable_rng}, }; use crate::{ diff --git a/utxo/src/tests/test_helper.rs b/utxo/src/tests/test_helper.rs index 974052e29d..5cb8a3b311 100644 --- a/utxo/src/tests/test_helper.rs +++ b/utxo/src/tests/test_helper.rs @@ -19,17 +19,17 @@ use itertools::Itertools; use common::{ chain::{ - output_value::OutputValue, Destination, GenBlock, OutPointSourceId, Transaction, TxInput, - TxOutput, UtxoOutPoint, + Destination, GenBlock, OutPointSourceId, Transaction, TxInput, TxOutput, UtxoOutPoint, + output_value::OutputValue, }, - primitives::{Amount, BlockHeight, Id, H256}, + primitives::{Amount, BlockHeight, H256, Id}, }; use crypto::key::{KeyKind, PrivateKey}; -use randomness::{seq, CryptoRng, Rng, RngExt as _}; +use randomness::{CryptoRng, Rng, RngExt as _, seq}; use crate::{ - utxo_entry::{IsDirty, IsFresh, UtxoEntry}, Utxo, UtxosCache, UtxosView, + utxo_entry::{IsDirty, IsFresh, UtxoEntry}, }; struct EmptyUtxosView { best_block_hash: Id, diff --git a/utxo/src/undo.rs b/utxo/src/undo.rs index a8c915d552..d2f3a85aa8 100644 --- a/utxo/src/undo.rs +++ b/utxo/src/undo.rs @@ -13,7 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::{btree_map::Entry, BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, btree_map::Entry}; use crate::Utxo; use common::{ @@ -197,7 +197,7 @@ pub mod test { use crate::tests::test_helper::create_utxo; use common::primitives::H256; use rstest::rstest; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; #[rstest] #[trace] diff --git a/utxo/src/utxo_entry.rs b/utxo/src/utxo_entry.rs index c6c9cc4527..b159d1bb4e 100644 --- a/utxo/src/utxo_entry.rs +++ b/utxo/src/utxo_entry.rs @@ -35,11 +35,7 @@ pub enum IsFresh { impl From for IsFresh { fn from(v: bool) -> Self { - if v { - IsFresh::Yes - } else { - IsFresh::No - } + if v { IsFresh::Yes } else { IsFresh::No } } } @@ -52,11 +48,7 @@ pub enum IsDirty { impl From for IsDirty { fn from(v: bool) -> Self { - if v { - IsDirty::Yes - } else { - IsDirty::No - } + if v { IsDirty::Yes } else { IsDirty::No } } } @@ -138,7 +130,7 @@ mod unit_test { use super::*; use crate::UtxoSource; use common::{ - chain::{output_value::OutputValue, Destination, TxOutput}, + chain::{Destination, TxOutput, output_value::OutputValue}, primitives::Amount, }; use rstest::rstest; diff --git a/wallet/src/account/currency_grouper/mod.rs b/wallet/src/account/currency_grouper/mod.rs index b4bb14e0ac..3c76c0e9cc 100644 --- a/wallet/src/account/currency_grouper/mod.rs +++ b/wallet/src/account/currency_grouper/mod.rs @@ -14,14 +14,14 @@ // limitations under the License. use crate::{ - destination_getters::{get_tx_output_destination, HtlcSpendingCondition}, WalletError, WalletResult, + destination_getters::{HtlcSpendingCondition, get_tx_output_destination}, }; use std::collections::BTreeMap; use common::{ - chain::{output_value::OutputValue, ChainConfig, Currency, Destination, TxOutput}, + chain::{ChainConfig, Currency, Destination, TxOutput, output_value::OutputValue}, primitives::{Amount, BlockHeight}, }; @@ -53,7 +53,7 @@ pub fn group_outputs( TxOutput::ProduceBlockFromStake(_, _) => { return Err(WalletError::UnsupportedTransactionOutput(Box::new( get_tx_output(&output).clone(), - ))) + ))); } TxOutput::CreateOrder(data) => data.give().clone(), }; @@ -110,7 +110,7 @@ pub fn group_outputs_with_issuance_fee( TxOutput::ProduceBlockFromStake(_, _) => { return Err(WalletError::UnsupportedTransactionOutput(Box::new( get_tx_output(&output).clone(), - ))) + ))); } TxOutput::CreateOrder(data) => data.give().clone(), }; @@ -141,7 +141,7 @@ fn output_spendable_value(output: &TxOutput) -> Result<(Currency, Amount), UtxoS OutputValue::TokenV0(_) => { return Err(UtxoSelectorError::UnsupportedTransactionOutput(Box::new( output.clone(), - ))) + ))); } OutputValue::TokenV1(token_id, output_amount) => { (Currency::Token(*token_id), *output_amount) @@ -160,7 +160,7 @@ fn output_spendable_value(output: &TxOutput) -> Result<(Currency, Amount), UtxoS | TxOutput::CreateOrder(_) => { return Err(UtxoSelectorError::UnsupportedTransactionOutput(Box::new( output.clone(), - ))) + ))); } }; Ok(value) diff --git a/wallet/src/account/mod.rs b/wallet/src/account/mod.rs index 8415440b07..dfb4f5ca29 100644 --- a/wallet/src/account/mod.rs +++ b/wallet/src/account/mod.rs @@ -20,16 +20,20 @@ mod utxo_selector; use std::{ cmp::Reverse, - collections::{btree_map::Entry, BTreeMap, BTreeSet}, + collections::{BTreeMap, BTreeSet, btree_map::Entry}, ops::{Add, Sub}, sync::Arc, }; -use itertools::{izip, Itertools}; +use itertools::{Itertools, izip}; use common::{ - address::{pubkeyhash::PublicKeyHash, Address, RpcAddress}, + Uint256, + address::{Address, RpcAddress, pubkeyhash::PublicKeyHash}, chain::{ + AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, Block, ChainConfig, + Currency, DelegationId, Destination, GenBlock, OrderAccountCommand, OrderId, OrdersVersion, + PoolId, RpcOrderInfo, SignedTransaction, Transaction, TxInput, TxOutput, UtxoOutPoint, block::timestamp::BlockTimestamp, classic_multisig::ClassicMultisigChallenge, htlc::{HashedTimelockContract, HtlcSecret}, @@ -40,27 +44,23 @@ use common::{ IsTokenUnfreezable, NftIssuance, NftIssuanceV0, RPCFungibleTokenInfo, TokenId, TokenIssuance, }, - AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, Block, ChainConfig, - Currency, DelegationId, Destination, GenBlock, OrderAccountCommand, OrderId, OrdersVersion, - PoolId, RpcOrderInfo, SignedTransaction, Transaction, TxInput, TxOutput, UtxoOutPoint, }, primitives::{ - id::{Idable, WithId, H256}, Amount, BlockHeight, Id, + id::{H256, Idable, WithId}, }, size_estimation::{ - input_signature_size, input_signature_size_from_destination, + DestinationInfoProvider, input_signature_size, input_signature_size_from_destination, input_signatures_size_from_destinations, inputs_encoded_size, outputs_encoded_size, - tx_size_with_num_inputs_and_outputs, DestinationInfoProvider, + tx_size_with_num_inputs_and_outputs, }, - Uint256, }; use consensus::PoSGenerateBlockInputData; use crypto::{ key::{ + PrivateKey, PublicKey, extended::ExtendedPublicKey, hdkd::{child_number::ChildNumber, u31::U31}, - PrivateKey, PublicKey, }, vrf::VRFPublicKey, }; @@ -72,34 +72,35 @@ use wallet_storage::{ WalletStorageWriteUnlocked, }; use wallet_types::{ + AccountId, AccountInfo, AccountWalletCreatedTxId, AccountWalletTxId, BlockInfo, KeyPurpose, + KeychainUsageState, WalletTx, account_id::AccountPrefixedId, account_info::{StandaloneAddressDetails, StandaloneAddresses}, partially_signed_transaction::PartiallySignedTransaction, - utxo_types::{get_utxo_type, UtxoState, UtxoStates, UtxoType, UtxoTypes}, + utxo_types::{UtxoState, UtxoStates, UtxoType, UtxoTypes, get_utxo_type}, wallet_tx::{BlockData, TxData, TxState}, with_locked::WithLocked, - AccountId, AccountInfo, AccountWalletCreatedTxId, AccountWalletTxId, BlockInfo, KeyPurpose, - KeychainUsageState, WalletTx, }; use crate::{ - account::utxo_selector::{select_coins, OutputGroup}, - destination_getters::{get_tx_output_destination, HtlcSpendingCondition}, + SendRequest, WalletError, WalletResult, + account::utxo_selector::{OutputGroup, select_coins}, + destination_getters::{HtlcSpendingCondition, get_tx_output_destination}, key_chain::{AccountKeyChains, KeyChainError, VRFAccountKeyChains}, send_request::{ - make_address_output, make_address_output_from_delegation, make_address_output_token, + IssueNftArguments, SelectedInputs, StakePoolCreationArguments, + StakePoolCreationResolvedArguments, make_address_output, + make_address_output_from_delegation, make_address_output_token, make_decommission_stake_pool_output, make_mint_token_outputs, make_stake_output, - make_unmint_token_outputs, IssueNftArguments, SelectedInputs, StakePoolCreationArguments, - StakePoolCreationResolvedArguments, + make_unmint_token_outputs, }, wallet::WalletPoolsFilter, wallet_events::{WalletEvents, WalletEventsNoOp}, - SendRequest, WalletError, WalletResult, }; use self::{ output_cache::{OutputCache, TokenIssuanceData}, - transaction_list::{get_transaction_list, TransactionList}, + transaction_list::{TransactionList, get_transaction_list}, utxo_selector::{PayFee, SelectionResult}, }; @@ -1606,7 +1607,7 @@ impl Account { | Destination::PublicKeyHash(_) | Destination::ScriptHash(_) | Destination::ClassicMultisig(_) => { - return Err(WalletError::StakerDestinationMustBePublicKey) + return Err(WalletError::StakerDestinationMustBePublicKey); } }, None => Destination::PublicKey( @@ -2736,7 +2737,7 @@ fn group_preselected_inputs( OutputValue::TokenV0(_) => { return Err(WalletError::UnsupportedTransactionOutput(Box::new( output.clone(), - ))) + ))); } OutputValue::TokenV1(token_id, output_amount) => { (Currency::Token(*token_id), *output_amount) @@ -2755,7 +2756,7 @@ fn group_preselected_inputs( | TxOutput::CreateOrder(_) => { return Err(WalletError::UnsupportedTransactionOutput(Box::new( output.clone(), - ))) + ))); } }; update_preselected_inputs(currency, value, Currency::Coin, Amount::ZERO)?; diff --git a/wallet/src/account/output_cache/mod.rs b/wallet/src/account/output_cache/mod.rs index 9b99735b2e..ee1bbb75f3 100644 --- a/wallet/src/account/output_cache/mod.rs +++ b/wallet/src/account/output_cache/mod.rs @@ -15,28 +15,28 @@ use std::{ cmp::Reverse, - collections::{btree_map::Entry, BTreeMap, BTreeSet, VecDeque}, + collections::{BTreeMap, BTreeSet, VecDeque, btree_map::Entry}, ops::Add, }; use common::{ chain::{ + AccountCommand, AccountCommandTag, AccountNonce, AccountSpending, AccountType, ChainConfig, + DelegationId, Destination, GenBlock, OrderAccountCommand, OrderAccountCommandTag, OrderId, + OutPointSourceId, PoolId, TokenIdGenerationVersion, Transaction, TxInput, TxOutput, + UtxoOutPoint, block::timestamp::BlockTimestamp, make_delegation_id, make_order_id, make_token_id, make_token_id_with_version, output_value::{OutputValue, RpcOutputValue}, output_values_holder::RpcOutputValuesHolder, stakelock::StakePoolData, tokens::{ - get_referenced_token_ids_ignore_issuance, IsTokenFreezable, IsTokenUnfreezable, - RPCFungibleTokenInfo, RPCIsTokenFrozen, RPCNonFungibleTokenInfo, RPCTokenTotalSupply, - TokenId, TokenIssuance, TokenTotalSupply, + IsTokenFreezable, IsTokenUnfreezable, RPCFungibleTokenInfo, RPCIsTokenFrozen, + RPCNonFungibleTokenInfo, RPCTokenTotalSupply, TokenId, TokenIssuance, TokenTotalSupply, + get_referenced_token_ids_ignore_issuance, }, - AccountCommand, AccountCommandTag, AccountNonce, AccountSpending, AccountType, ChainConfig, - DelegationId, Destination, GenBlock, OrderAccountCommand, OrderAccountCommandTag, OrderId, - OutPointSourceId, PoolId, TokenIdGenerationVersion, Transaction, TxInput, TxOutput, - UtxoOutPoint, }, - primitives::{id::WithId, per_thousand::PerThousand, Amount, BlockHeight, Id, Idable}, + primitives::{Amount, BlockHeight, Id, Idable, id::WithId, per_thousand::PerThousand}, }; use crypto::vrf::VRFPublicKey; use itertools::Itertools; @@ -44,13 +44,13 @@ use rpc_description::HasValueHint; use tx_verifier::transaction_verifier::calculate_tokens_burned_in_outputs; use utils::ensure; use wallet_types::{ - utxo_types::{get_utxo_state, UtxoState, UtxoStates}, + AccountWalletTxId, BlockInfo, WalletTx, + utxo_types::{UtxoState, UtxoStates, get_utxo_state}, wallet_tx::{TxData, TxState}, with_locked::WithLocked, - AccountWalletTxId, BlockInfo, WalletTx, }; -use crate::{destination_getters::get_all_tx_output_destinations, WalletError, WalletResult}; +use crate::{WalletError, WalletResult, destination_getters::get_all_tx_output_destinations}; pub type UtxoWithTxOutput<'a> = (UtxoOutPoint, &'a TxOutput); @@ -930,9 +930,11 @@ impl OutputCache { TxState::Conflicted(..) | TxState::Abandoned | TxState::Confirmed(..) => { - return Err(WalletError::CannotMarkTxAsConflictedIfInState( - *tx.state(), - )) + return Err( + WalletError::CannotMarkTxAsConflictedIfInState( + *tx.state(), + ), + ); } } conflicting_txs_with_descendants @@ -1806,7 +1808,7 @@ impl OutputCache { return Err(WalletError::CannotChangeTransactionState( *state, TxState::Abandoned, - )) + )); } }; diff --git a/wallet/src/account/output_cache/tests.rs b/wallet/src/account/output_cache/tests.rs index d8cd702b6e..979d67ee54 100644 --- a/wallet/src/account/output_cache/tests.rs +++ b/wallet/src/account/output_cache/tests.rs @@ -17,20 +17,20 @@ use rstest::rstest; use strum::IntoEnumIterator as _; -use chainstate_test_framework::{empty_witness, TransactionBuilder}; +use chainstate_test_framework::{TransactionBuilder, empty_witness}; use common::{ address::pubkeyhash::PublicKeyHash, chain::{ + AccountOutPoint, ChainstateUpgradeBuilder, OrderData, TokenIdGenerationVersion, config::{create_unit_test_config, create_unit_test_config_builder}, make_token_id_with_version, signature::inputsig::InputWitness, timelock::OutputTimeLock, tokens::TokenIssuanceV1, - AccountOutPoint, ChainstateUpgradeBuilder, OrderData, TokenIdGenerationVersion, }, }; -use randomness::{seq::IteratorRandom as _, Rng, RngExt as _}; -use test_utils::random::{make_seedable_rng, Seed}; +use randomness::{Rng, RngExt as _, seq::IteratorRandom as _}; +use test_utils::random::{Seed, make_seedable_rng}; use wallet_types::wallet_tx::TxStateTag; use crate::account::output_cache; diff --git a/wallet/src/account/tests.rs b/wallet/src/account/tests.rs index 2af3908892..99735d4273 100644 --- a/wallet/src/account/tests.rs +++ b/wallet/src/account/tests.rs @@ -14,13 +14,13 @@ // limitations under the License. use super::*; -use crate::key_chain::{MasterKeyChain, LOOKAHEAD_SIZE}; +use crate::key_chain::{LOOKAHEAD_SIZE, MasterKeyChain}; use common::chain::config::create_regtest; use crypto::key::hdkd::child_number::ChildNumber; use wallet_storage::{DefaultBackend, Store, TransactionRwUnlocked, Transactional}; +use wallet_types::KeyPurpose::{Change, ReceiveFunds}; use wallet_types::account_info::DEFAULT_ACCOUNT_INDEX; use wallet_types::seed_phrase::StoreSeedPhrase; -use wallet_types::KeyPurpose::{Change, ReceiveFunds}; const MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; diff --git a/wallet/src/account/transaction_list/mod.rs b/wallet/src/account/transaction_list/mod.rs index 84d2a873cf..826263067d 100644 --- a/wallet/src/account/transaction_list/mod.rs +++ b/wallet/src/account/transaction_list/mod.rs @@ -16,16 +16,16 @@ use std::{cmp::Ordering, ops::Add}; use common::{ - chain::{block::timestamp::BlockTimestamp, Currency, Transaction, TxInput, TxOutput}, + chain::{Currency, Transaction, TxInput, TxOutput, block::timestamp::BlockTimestamp}, primitives::{Amount, BlockHeight, Id, Idable}, }; use serde::Serialize; use wallet_types::{ - wallet_tx::{TxData, TxState}, WalletTx, + wallet_tx::{TxData, TxState}, }; -use crate::{key_chain::AccountKeyChains, WalletError, WalletResult}; +use crate::{WalletError, WalletResult, key_chain::AccountKeyChains}; use super::{currency_grouper::group_outputs, output_cache::OutputCache}; diff --git a/wallet/src/account/utxo_selector/mod.rs b/wallet/src/account/utxo_selector/mod.rs index 5b4d0c8471..dc03b8b84b 100644 --- a/wallet/src/account/utxo_selector/mod.rs +++ b/wallet/src/account/utxo_selector/mod.rs @@ -20,9 +20,9 @@ pub use output_group::{OutputGroup, PayFee}; use common::{ chain::{TxInput, TxOutput}, - primitives::{amount::SignedAmount, Amount}, + primitives::{Amount, amount::SignedAmount}, }; -use randomness::{make_pseudo_rng, Rng, RngExt as _, SliceRandom}; +use randomness::{Rng, RngExt as _, SliceRandom, make_pseudo_rng}; use utils::ensure; const TOTAL_TRIES: u32 = 100_000; diff --git a/wallet/src/account/utxo_selector/output_group.rs b/wallet/src/account/utxo_selector/output_group.rs index bb03ae0391..a13240722a 100644 --- a/wallet/src/account/utxo_selector/output_group.rs +++ b/wallet/src/account/utxo_selector/output_group.rs @@ -14,7 +14,7 @@ // limitations under the License. use common::{ - chain::{output_value::OutputValue, TxInput, TxOutput}, + chain::{TxInput, TxOutput, output_value::OutputValue}, primitives::Amount, }; @@ -71,7 +71,7 @@ impl OutputGroup { | TxOutput::CreateOrder(_) => { return Err(UtxoSelectorError::UnsupportedTransactionOutput(Box::new( output.1.clone(), - ))) + ))); } }; let value = output_value.amount(); diff --git a/wallet/src/account/utxo_selector/tests.rs b/wallet/src/account/utxo_selector/tests.rs index 4a358bfe9b..10b6f3ecd5 100644 --- a/wallet/src/account/utxo_selector/tests.rs +++ b/wallet/src/account/utxo_selector/tests.rs @@ -14,12 +14,12 @@ // limitations under the License. use common::{ - chain::{output_value::OutputValue, Destination, GenBlock, OutPointSourceId, UtxoOutPoint}, - primitives::Id, Uint256, + chain::{Destination, GenBlock, OutPointSourceId, UtxoOutPoint, output_value::OutputValue}, + primitives::Id, }; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use super::*; diff --git a/wallet/src/destination_getters.rs b/wallet/src/destination_getters.rs index 9b94a19ad5..61e68ae3bc 100644 --- a/wallet/src/destination_getters.rs +++ b/wallet/src/destination_getters.rs @@ -13,7 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use common::chain::{htlc::HtlcSecret, Destination, PoolId, TxOutput}; +use common::chain::{Destination, PoolId, TxOutput, htlc::HtlcSecret}; use crate::account::PoolData; diff --git a/wallet/src/key_chain/account_key_chain/mod.rs b/wallet/src/key_chain/account_key_chain/mod.rs index 38e3cc0599..77615c8a55 100644 --- a/wallet/src/key_chain/account_key_chain/mod.rs +++ b/wallet/src/key_chain/account_key_chain/mod.rs @@ -15,7 +15,7 @@ use crate::key_chain::leaf_key_chain::LeafKeySoftChain; use crate::key_chain::with_purpose::WithPurpose; -use crate::key_chain::{make_account_path, KeyChainError, KeyChainResult}; +use crate::key_chain::{KeyChainError, KeyChainResult, make_account_path}; use common::address::pubkeyhash::PublicKeyHash; use common::address::{Address, RpcAddress}; use common::chain::classic_multisig::ClassicMultisigChallenge; @@ -42,7 +42,7 @@ use wallet_types::{AccountId, AccountInfo, KeychainUsageState}; use super::vrf_key_chain::{EmptyVrfKeyChain, VrfKeyChain, VrfKeySoftChain}; use super::{ - make_path_to_vrf_key, AccountKeyChains, MasterKeyChain, VRFAccountKeyChains, VRF_INDEX, + AccountKeyChains, MasterKeyChain, VRF_INDEX, VRFAccountKeyChains, make_path_to_vrf_key, }; /// This key chain contains a pool of pre-generated keys and addresses for the usage in a wallet diff --git a/wallet/src/key_chain/account_key_chain/tests.rs b/wallet/src/key_chain/account_key_chain/tests.rs index f5ed126ce1..ac63961f47 100644 --- a/wallet/src/key_chain/account_key_chain/tests.rs +++ b/wallet/src/key_chain/account_key_chain/tests.rs @@ -14,7 +14,7 @@ // limitations under the License. use super::*; -use crate::key_chain::{MasterKeyChain, LOOKAHEAD_SIZE}; +use crate::key_chain::{LOOKAHEAD_SIZE, MasterKeyChain}; use common::chain::config::create_mainnet; use crypto::key::secp256k1::Secp256k1PublicKey; use rstest::rstest; diff --git a/wallet/src/key_chain/leaf_key_chain/mod.rs b/wallet/src/key_chain/leaf_key_chain/mod.rs index d68c0e2a96..6f82e14427 100644 --- a/wallet/src/key_chain/leaf_key_chain/mod.rs +++ b/wallet/src/key_chain/leaf_key_chain/mod.rs @@ -14,15 +14,15 @@ // limitations under the License. use crate::key_chain::with_purpose::WithPurpose; -use crate::key_chain::{get_purpose_and_index, KeyChainError, KeyChainResult}; -use common::address::pubkeyhash::PublicKeyHash; +use crate::key_chain::{KeyChainError, KeyChainResult, get_purpose_and_index}; use common::address::Address; +use common::address::pubkeyhash::PublicKeyHash; use common::chain::{ChainConfig, Destination}; +use crypto::key::PublicKey; use crypto::key::extended::ExtendedPublicKey; use crypto::key::hdkd::child_number::ChildNumber; use crypto::key::hdkd::derivable::Derivable; use crypto::key::hdkd::u31::U31; -use crypto::key::PublicKey; use std::collections::BTreeMap; use std::sync::Arc; use utils::const_value::ConstValue; diff --git a/wallet/src/key_chain/master_key_chain/mod.rs b/wallet/src/key_chain/master_key_chain/mod.rs index 5eb67449c0..1667a8d7de 100644 --- a/wallet/src/key_chain/master_key_chain/mod.rs +++ b/wallet/src/key_chain/master_key_chain/mod.rs @@ -13,7 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::key_chain::{KeyChainError, KeyChainResult, DEFAULT_KEY_KIND}; +use crate::key_chain::{DEFAULT_KEY_KIND, KeyChainError, KeyChainResult}; use common::chain::ChainConfig; use crypto::key::extended::ExtendedPrivateKey; use crypto::key::hdkd::derivable::Derivable; diff --git a/wallet/src/key_chain/mod.rs b/wallet/src/key_chain/mod.rs index 4684dbd9b9..5f4733e168 100644 --- a/wallet/src/key_chain/mod.rs +++ b/wallet/src/key_chain/mod.rs @@ -212,7 +212,7 @@ where /// Find the corresponding public key for a given public key hash fn get_public_key_from_public_key_hash(&self, pubkey_hash: &PublicKeyHash) - -> Option; + -> Option; /// Derive addresses until there are lookahead unused ones fn top_up_all(&mut self, db_tx: &mut impl WalletStorageWriteLocked) -> KeyChainResult<()>; diff --git a/wallet/src/key_chain/tests.rs b/wallet/src/key_chain/tests.rs index 5a627b6ece..452a777fed 100644 --- a/wallet/src/key_chain/tests.rs +++ b/wallet/src/key_chain/tests.rs @@ -16,11 +16,11 @@ use super::*; use common::chain::config::{create_mainnet, create_unit_test_config}; use common::{address::pubkeyhash::PublicKeyHash, chain::Destination}; +use crypto::key::PublicKey; use crypto::key::extended::ExtendedPublicKey; use crypto::key::hdkd::derivable::Derivable; use crypto::key::hdkd::u31::U31; use crypto::key::secp256k1::Secp256k1PublicKey; -use crypto::key::PublicKey; use rstest::rstest; use std::str::FromStr; use std::sync::Arc; @@ -29,7 +29,7 @@ use wallet_storage::{ DefaultBackend, Store, TransactionRwLocked, TransactionRwUnlocked, Transactional, }; use wallet_types::seed_phrase::StoreSeedPhrase; -use wallet_types::{account_info::DEFAULT_ACCOUNT_INDEX, AccountInfo}; +use wallet_types::{AccountInfo, account_info::DEFAULT_ACCOUNT_INDEX}; const MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; @@ -261,9 +261,11 @@ fn top_up_and_lookahead(#[case] purpose: KeyPurpose) { let mut issued_key = key_chain.issue_key(&mut db_tx, purpose).unwrap(); // Mark the last key as used - assert!(key_chain - .mark_public_key_as_used(&mut db_tx, &issued_key.clone().into_public_key()) - .unwrap()); + assert!( + key_chain + .mark_public_key_as_used(&mut db_tx, &issued_key.clone().into_public_key()) + .unwrap() + ); { let leaf_keys = key_chain.get_leaf_key_chain(purpose); @@ -285,9 +287,11 @@ fn top_up_and_lookahead(#[case] purpose: KeyPurpose) { } // Mark the last key as used - assert!(key_chain - .mark_public_key_as_used(&mut db_tx, &issued_key.into_public_key()) - .unwrap()); + assert!( + key_chain + .mark_public_key_as_used(&mut db_tx, &issued_key.into_public_key()) + .unwrap() + ); { let leaf_keys = key_chain.get_leaf_key_chain(purpose); diff --git a/wallet/src/key_chain/vrf_key_chain/mod.rs b/wallet/src/key_chain/vrf_key_chain/mod.rs index b11da1f6bd..ae651790b0 100644 --- a/wallet/src/key_chain/vrf_key_chain/mod.rs +++ b/wallet/src/key_chain/vrf_key_chain/mod.rs @@ -25,9 +25,9 @@ use std::sync::Arc; use utils::const_value::ConstValue; use utils::ensure; use wallet_storage::{WalletStorageReadLocked, WalletStorageWriteLocked}; +use wallet_types::AccountId; use wallet_types::account_info::AccountVrfKeys; use wallet_types::keys::KeychainUsageState; -use wallet_types::AccountId; /// A child key hierarchy for an AccountKeyChain. This normally implements the receiving and change /// addresses key chains. It uses soft derivation to generate addresses (xpub). diff --git a/wallet/src/send_request/mod.rs b/wallet/src/send_request/mod.rs index 814e63e3d6..a62a7ed24c 100644 --- a/wallet/src/send_request/mod.rs +++ b/wallet/src/send_request/mod.rs @@ -18,14 +18,14 @@ use std::{collections::BTreeMap, mem::take}; use common::{ address::Address, chain::{ + ChainConfig, Currency, Destination, PoolId, Transaction, TxInput, TxOutput, UtxoOutPoint, htlc::HtlcSecret, output_value::OutputValue, stakelock::StakePoolData, timelock::OutputTimeLock::ForBlockCount, tokens::{Metadata, TokenId, TokenIssuance}, - ChainConfig, Currency, Destination, PoolId, Transaction, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight}, + primitives::{Amount, BlockHeight, per_thousand::PerThousand}, }; use crypto::vrf::VRFPublicKey; use utils::ensure; @@ -34,9 +34,9 @@ use wallet_types::partially_signed_transaction::{ }; use crate::{ - account::PoolData, - destination_getters::{get_tx_output_destination, HtlcSpendingCondition}, WalletError, WalletResult, + account::PoolData, + destination_getters::{HtlcSpendingCondition, get_tx_output_destination}, }; /// The `SendRequest` struct provides the necessary information to the wallet diff --git a/wallet/src/signer/hardware_signer_utils.rs b/wallet/src/signer/hardware_signer_utils.rs index 9a036c710f..139e7997bc 100644 --- a/wallet/src/signer/hardware_signer_utils.rs +++ b/wallet/src/signer/hardware_signer_utils.rs @@ -19,22 +19,22 @@ use crate::signer::{DestinationSigError, SignatureStatus, SignerError, SignerRes use common::{ chain::{ + ChainConfig, DestinationTag, signature::inputsig::{ arbitrary_message::ArbitraryMessageSignature, authorize_pubkey_spend::AuthorizedPublicKeySpend, authorize_pubkeyhash_spend::AuthorizedPublicKeyHashSpend, classical_multisig::authorize_classical_multisig::{ - sign_classical_multisig_spending, AuthorizedClassicalMultisigSpend, - ClassicalMultisigCompletionStatus, + AuthorizedClassicalMultisigSpend, ClassicalMultisigCompletionStatus, + sign_classical_multisig_spending, }, }, - ChainConfig, DestinationTag, }, primitives::H256, }; use crypto::key::{ - extended::ExtendedPublicKey, signature::SignatureKind, PrivateKey, SigAuxDataProvider, - Signature, SignatureError, + PrivateKey, SigAuxDataProvider, Signature, SignatureError, extended::ExtendedPublicKey, + signature::SignatureKind, }; use serialization::Encode; diff --git a/wallet/src/signer/ledger_signer/ledger_messages.rs b/wallet/src/signer/ledger_signer/ledger_messages.rs index 8fc5a9472a..efdbcc5b0a 100644 --- a/wallet/src/signer/ledger_signer/ledger_messages.rs +++ b/wallet/src/signer/ledger_signer/ledger_messages.rs @@ -19,7 +19,7 @@ use crate::signer::ledger_signer::LedgerError; use crypto::key::{ extended::ExtendedPublicKey, hdkd::{chain_code::ChainCode, derivation_path::DerivationPath}, - secp256k1::{extended_keys::Secp256k1ExtendedPublicKey, Secp256k1PublicKey}, + secp256k1::{Secp256k1PublicKey, extended_keys::Secp256k1ExtendedPublicKey}, }; use utils::ensure; diff --git a/wallet/src/signer/ledger_signer/mod.rs b/wallet/src/signer/ledger_signer/mod.rs index 1ec3d2cebb..49b99fd1e6 100644 --- a/wallet/src/signer/ledger_signer/mod.rs +++ b/wallet/src/signer/ledger_signer/mod.rs @@ -18,26 +18,30 @@ mod ledger_messages; use std::{collections::BTreeMap, sync::Arc}; use crate::{ - key_chain::{make_account_path, AccountKeyChainImplHardware, AccountKeyChains, FoundPubKey}, + Account, WalletResult, + key_chain::{AccountKeyChainImplHardware, AccountKeyChains, FoundPubKey, make_account_path}, signer::{ + Signer, SignerError, SignerProvider, SignerResult, hardware_signer_utils::{ - arbitrary_message_signature_from_raw_sig, sign_with_standalone_private_keys, - StandaloneInput, StandaloneInputs, + StandaloneInput, StandaloneInputs, arbitrary_message_signature_from_raw_sig, + sign_with_standalone_private_keys, }, ledger_signer::ledger_messages::{ - check_current_app, get_extended_public_key, get_extended_public_key_raw, - sign_challenge, sign_tx, LedgerMessagesError, + LedgerMessagesError, check_current_app, get_extended_public_key, + get_extended_public_key_raw, sign_challenge, sign_tx, }, utils::{is_htlc_utxo, produce_uniparty_signature_for_input}, - Signer, SignerError, SignerProvider, SignerResult, }, - Account, WalletResult, }; use common::{ chain::{ + AccountCommand, ChainConfig, Destination, DestinationTag, OrderAccountCommand, + SignedTransactionIntent, Transaction, TxInput, TxOutput, config::ChainType, signature::{ + DestinationSigError, inputsig::{ + InputWitness, arbitrary_message::ArbitraryMessageSignature, authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, authorize_pubkey_spend::AuthorizedPublicKeySpend, @@ -47,22 +51,18 @@ use common::{ multisig_partial_signature::{self, PartiallySignedMultisigChallenge}, }, standard_signature::StandardInputSignature, - InputWitness, }, sighash::{sighashtype::SigHashType, signature_hash}, - DestinationSigError, }, - AccountCommand, ChainConfig, Destination, DestinationTag, OrderAccountCommand, - SignedTransactionIntent, Transaction, TxInput, TxOutput, }, - primitives::{BlockHeight, Idable, H256}, + primitives::{BlockHeight, H256, Idable}, primitives_converters::TryConvertInto as _, }; use crypto::key::{ + SigAuxDataProvider, Signature, SignatureError, extended::ExtendedPublicKey, hdkd::{derivable::Derivable, u31::U31}, signature::SignatureKind, - SigAuxDataProvider, Signature, SignatureError, }; use serialization::Encode; use utils::ensure; @@ -70,6 +70,7 @@ use wallet_storage::{ WalletStorageReadLocked, WalletStorageReadUnlocked, WalletStorageWriteUnlocked, }; use wallet_types::{ + AccountId, account_info::DEFAULT_ACCOUNT_INDEX, hw_data::{ HardwareWalletData, HardwareWalletFullInfo, LedgerData, LedgerFullInfo, LedgerModel, @@ -78,12 +79,11 @@ use wallet_types::{ PartiallySignedTransaction, PtxAdditionalInfo, TokensAdditionalInfo, }, signature_status::SignatureStatus, - AccountId, }; use async_trait::async_trait; -use itertools::{izip, Itertools}; -use ledger_lib::{info::Model, Exchange, Filters, LedgerHandle, LedgerProvider, Transport}; +use itertools::{Itertools, izip}; +use ledger_lib::{Exchange, Filters, LedgerHandle, LedgerProvider, Transport, info::Model}; use mintlayer_ledger_messages::{ AdditionalOrderInfo, AdditionalUtxoInfo, AddrType, Bip32Path as LedgerBip32Path, CoinType, InputAddressPath as LedgerInputAddressPath, SighashInputCommitment as LSighashInputCommitment, @@ -99,7 +99,9 @@ pub enum LedgerError { NoDeviceFound, #[error("Device timeout")] DeviceTimeout, - #[error("A different app is currently open on your Ledger device: \"{0}\". Please close it and open the Mintlayer app instead.")] + #[error( + "A different app is currently open on your Ledger device: \"{0}\". Please close it and open the Mintlayer app instead." + )] DifferentActiveApp(String), #[error("Received an invalid response from the Ledger device")] InvalidResponse, @@ -113,9 +115,13 @@ pub enum LedgerError { ApduMessageTooLong, #[error("Invalid public key returned from Ledger")] InvalidKey, - #[error("The file being loaded is a software wallet and cannot be used with the connected Ledger wallet")] + #[error( + "The file being loaded is a software wallet and cannot be used with the connected Ledger wallet" + )] WalletFileIsSoftwareWallet, - #[error("The file being loaded is a trezor wallet and cannot be used with the connected Ledger wallet")] + #[error( + "The file being loaded is a trezor wallet and cannot be used with the connected Ledger wallet" + )] WalletFileIsTrezorWallet, #[error("Public keys mismatch - wrong device or passphrase")] HardwareWalletDifferentMnemonicOrPassphrase, diff --git a/wallet/src/signer/ledger_signer/tests/mod.rs b/wallet/src/signer/ledger_signer/tests/mod.rs index 45584f7a8d..f12124f7ef 100644 --- a/wallet/src/signer/ledger_signer/tests/mod.rs +++ b/wallet/src/signer/ledger_signer/tests/mod.rs @@ -24,46 +24,46 @@ use std::{ use async_trait::async_trait; use ledger_lib::{ - transport::{TcpDevice, TcpInfo, TcpTransport}, Device as _, Transport, + transport::{TcpDevice, TcpInfo, TcpTransport}, }; use mintlayer_ledger_messages::CoinType; use rstest::rstest; use tokio::{ sync::{ - mpsc::{self, Sender}, Mutex, + mpsc::{self, Sender}, }, time::sleep, }; use crate::signer::{ + SignerError, SignerResult, ledger_signer::{ + LedgerError, LedgerFinder, LedgerSigner, ledger_messages::{ check_current_app, get_extended_public_key, get_extended_public_key_raw, }, - LedgerError, LedgerFinder, LedgerSigner, }, tests::{ generic_fixed_signature_tests::test_fixed_signatures_generic_no_legacy, generic_tests::{ - sign_message_test_params, test_sign_message_generic, test_sign_transaction_generic, - test_sign_transaction_intent_generic, MessageToSign, + MessageToSign, sign_message_test_params, test_sign_message_generic, + test_sign_transaction_generic, test_sign_transaction_intent_generic, }, make_deterministic_software_signer, no_another_signer, }, - SignerError, SignerResult, }; -use common::chain::{config::create_mainnet, ChainConfig, SighashInputCommitmentVersion}; +use common::chain::{ChainConfig, SighashInputCommitmentVersion, config::create_mainnet}; use crypto::key::{ - hdkd::{derivation_path::DerivationPath, u31::U31}, PredefinedSigAuxDataProvider, SigAuxDataProvider, + hdkd::{derivation_path::DerivationPath, u31::U31}, }; use logging::log; use randomness::make_true_rng; use serialization::hex::HexEncode; use speculos::{Device, Handle}; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use utils::env_utils::{bool_from_env, get_from_env}; use wallet_storage::WalletStorageReadLocked; use wallet_types::hw_data::LedgerData; @@ -322,7 +322,9 @@ async fn test_sign_transaction( #[case] seed: Seed, #[case] input_commitments_version: SighashInputCommitmentVersion, ) { - log::debug!("test_sign_transaction, seed = {seed:?}, input_commitments_version = {input_commitments_version:?}"); + log::debug!( + "test_sign_transaction, seed = {seed:?}, input_commitments_version = {input_commitments_version:?}" + ); let (auto_confirmer_handle, control_msg_tx, make_ledger_signer) = setup(false).await; @@ -403,7 +405,9 @@ async fn test_sign_transaction_sig_consistency( #[case] seed: Seed, #[case] input_commitments_version: SighashInputCommitmentVersion, ) { - log::debug!("test_sign_transaction_sig_consistency, seed = {seed:?}, input_commitments_version = {input_commitments_version:?}"); + log::debug!( + "test_sign_transaction_sig_consistency, seed = {seed:?}, input_commitments_version = {input_commitments_version:?}" + ); let (auto_confirmer_handle, control_msg_tx, make_ledger_signer) = setup(true).await; diff --git a/wallet/src/signer/mod.rs b/wallet/src/signer/mod.rs index 80a6dbaabd..4840d70ab7 100644 --- a/wallet/src/signer/mod.rs +++ b/wallet/src/signer/mod.rs @@ -23,15 +23,15 @@ use async_trait::async_trait; use common::{ address::AddressError, chain::{ + ChainConfig, Destination, SignedTransactionIntent, SignedTransactionIntentError, + Transaction, UtxoOutPoint, signature::{ + DestinationSigError, inputsig::{ arbitrary_message::{ArbitraryMessageSignature, SignArbitraryMessageError}, classical_multisig::multisig_partial_signature::PartiallySignedMultisigStructureError, }, - DestinationSigError, }, - ChainConfig, Destination, SignedTransactionIntent, SignedTransactionIntentError, - Transaction, UtxoOutPoint, }, primitives::BlockHeight, primitives_converters::PrimitivesConvertersError, @@ -41,19 +41,19 @@ use wallet_storage::{ WalletStorageReadLocked, WalletStorageReadUnlocked, WalletStorageWriteUnlocked, }; use wallet_types::{ + AccountId, hw_data::HardwareWalletFullInfo, partially_signed_transaction::{ PartiallySignedTransaction, PartiallySignedTransactionError, TokensAdditionalInfo, }, signature_status::SignatureStatus, - AccountId, }; #[cfg(feature = "ledger")] use crate::signer::ledger_signer::LedgerError; use crate::{ - key_chain::{AccountKeyChains, KeyChainError}, Account, WalletResult, + key_chain::{AccountKeyChains, KeyChainError}, }; #[cfg(any(feature = "trezor", feature = "ledger"))] diff --git a/wallet/src/signer/software_signer/mod.rs b/wallet/src/signer/software_signer/mod.rs index b163a34aa5..7cbed1511b 100644 --- a/wallet/src/signer/software_signer/mod.rs +++ b/wallet/src/signer/software_signer/mod.rs @@ -20,33 +20,33 @@ use itertools::Itertools; use common::{ chain::{ + ChainConfig, Destination, SignedTransactionIntent, Transaction, TxOutput, config::ChainType, htlc::HtlcSecret, signature::{ + DestinationSigError, inputsig::{ + InputWitness, arbitrary_message::ArbitraryMessageSignature, classical_multisig::{ authorize_classical_multisig::{ - sign_classical_multisig_spending, AuthorizedClassicalMultisigSpend, - ClassicalMultisigCompletionStatus, + AuthorizedClassicalMultisigSpend, ClassicalMultisigCompletionStatus, + sign_classical_multisig_spending, }, encode_decode_multisig_spend::{decode_multisig_spend, encode_multisig_spend}, }, - InputWitness, }, sighash::{ input_commitments::SighashInputCommitment, sighashtype::SigHashType, signature_hash, }, - DestinationSigError, }, - ChainConfig, Destination, SignedTransactionIntent, Transaction, TxOutput, }, primitives::BlockHeight, }; use crypto::key::{ + PredefinedSigAuxDataProvider, PrivateKey, SigAuxDataProvider, extended::{ExtendedPrivateKey, ExtendedPublicKey}, hdkd::{derivable::Derivable, u31::U31}, - PredefinedSigAuxDataProvider, PrivateKey, SigAuxDataProvider, }; use randomness::make_true_rng; use utils::ensure; @@ -54,24 +54,24 @@ use wallet_storage::{ WalletStorageReadLocked, WalletStorageReadUnlocked, WalletStorageWriteUnlocked, }; use wallet_types::{ + AccountId, hw_data::HardwareWalletFullInfo, partially_signed_transaction::{PartiallySignedTransaction, TokensAdditionalInfo}, seed_phrase::StoreSeedPhrase, signature_status::SignatureStatus, wallet_type::WalletType, - AccountId, }; use crate::{ + Account, WalletError, WalletResult, key_chain::{ - make_account_path, AccountKeyChainImplSoftware, AccountKeyChains, FoundPubKey, - MasterKeyChain, + AccountKeyChainImplSoftware, AccountKeyChains, FoundPubKey, MasterKeyChain, + make_account_path, }, signer::utils::produce_uniparty_signature_for_input, - Account, WalletError, WalletResult, }; -use super::{utils::is_htlc_utxo, Signer, SignerError, SignerProvider, SignerResult}; +use super::{Signer, SignerError, SignerProvider, SignerResult, utils::is_htlc_utxo}; pub struct SoftwareSigner { chain_config: Arc, diff --git a/wallet/src/signer/software_signer/tests.rs b/wallet/src/signer/software_signer/tests.rs index bf4a8acb22..ecee835161 100644 --- a/wallet/src/signer/software_signer/tests.rs +++ b/wallet/src/signer/software_signer/tests.rs @@ -16,16 +16,16 @@ use rstest::rstest; use common::chain::SighashInputCommitmentVersion; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use crate::signer::tests::{ generic_fixed_signature_tests::{ - test_fixed_signatures_generic, test_fixed_signatures_generic2, - test_fixed_signatures_generic_htlc_refunding, test_fixed_signatures_generic_no_legacy, + test_fixed_signatures_generic, test_fixed_signatures_generic_htlc_refunding, + test_fixed_signatures_generic_no_legacy, test_fixed_signatures_generic2, }, generic_tests::{ - test_sign_message_generic, test_sign_transaction_generic, - test_sign_transaction_intent_generic, MessageToSign, + MessageToSign, test_sign_message_generic, test_sign_transaction_generic, + test_sign_transaction_intent_generic, }, make_deterministic_software_signer, make_software_signer, no_another_signer, }; diff --git a/wallet/src/signer/tests/generic_fixed_signature_tests.rs b/wallet/src/signer/tests/generic_fixed_signature_tests.rs index 352a5c4d45..19dd3424c9 100644 --- a/wallet/src/signer/tests/generic_fixed_signature_tests.rs +++ b/wallet/src/signer/tests/generic_fixed_signature_tests.rs @@ -15,13 +15,16 @@ use std::{num::NonZeroU8, sync::Arc}; -use itertools::{izip, Itertools as _}; +use itertools::{Itertools as _, izip}; use ::secp256k1::schnorr; use common::{ address::pubkeyhash::PublicKeyHash, chain::{ - self, + self, AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, ChainConfig, + ChainstateUpgradeBuilder, DelegationId, Destination, NetUpgrades, OrderAccountCommand, + OrderData, OrderId, OutPointSourceId, PoolId, SighashInputCommitmentVersion, Transaction, + TxInput, TxOutput, UtxoOutPoint, block::timestamp::BlockTimestamp, classic_multisig::ClassicMultisigChallenge, config::ChainType, @@ -29,11 +32,12 @@ use common::{ output_value::OutputValue, signature::{ inputsig::{ + InputWitness, authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, authorize_pubkey_spend::AuthorizedPublicKeySpend, authorize_pubkeyhash_spend::AuthorizedPublicKeyHashSpend, classical_multisig::authorize_classical_multisig::AuthorizedClassicalMultisigSpend, - standard_signature::StandardInputSignature, InputWitness, + standard_signature::StandardInputSignature, }, sighash::sighashtype::SigHashType, }, @@ -43,45 +47,41 @@ use common::{ IsTokenUnfreezable, Metadata, NftIssuance, NftIssuanceV0, TokenId, TokenIssuance, TokenIssuanceV1, }, - AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, ChainConfig, - ChainstateUpgradeBuilder, DelegationId, Destination, NetUpgrades, OrderAccountCommand, - OrderData, OrderId, OutPointSourceId, PoolId, SighashInputCommitmentVersion, Transaction, - TxInput, TxOutput, UtxoOutPoint, }, - primitives::{id::hash_encoded, per_thousand::PerThousand, Amount, BlockHeight, Id, H256}, + primitives::{Amount, BlockHeight, H256, Id, id::hash_encoded, per_thousand::PerThousand}, }; use crypto::{ key::{ + PrivateKey, PublicKey, Signature, hdkd::u31::U31, secp256k1::{Secp256k1PrivateKey, Secp256k1PublicKey}, signature::SignatureKind, - PrivateKey, PublicKey, Signature, }, vrf::{VRFPrivateKey, VRFPublicKey}, }; use logging::log; use randomness::{CryptoRng, RngExt as _}; -use serialization::{extras::non_empty_vec::DataOrNoVec, Encode as _}; +use serialization::{Encode as _, extras::non_empty_vec::DataOrNoVec}; use test_utils::{assert_matches_return_val, random_ascii_alphanumeric_string}; use wallet_storage::{DefaultBackend, Store, TransactionRwUnlocked, Transactional}; use wallet_types::{ + BlockInfo, KeyPurpose, account_info::DEFAULT_ACCOUNT_INDEX, partially_signed_transaction::{ OrderAdditionalInfo, PoolAdditionalInfo, PtxAdditionalInfo, TokenAdditionalInfo, TokensAdditionalInfo, }, seed_phrase::StoreSeedPhrase, - BlockInfo, KeyPurpose, }; use crate::{ + Account, SendRequest, account::PoolData, - key_chain::{AccountKeyChains, MasterKeyChain, LOOKAHEAD_SIZE}, + key_chain::{AccountKeyChains, LOOKAHEAD_SIZE, MasterKeyChain}, signer::{ - tests::{account_from_mnemonic, MNEMONIC}, Signer, + tests::{MNEMONIC, account_from_mnemonic}, }, - Account, SendRequest, }; lazy_static::lazy_static! { @@ -412,8 +412,14 @@ where let expected_sigs = { let multisig = { let sigs_hex = [ - (0, "7a99714dc6cc917faa2afded8028159a5048caf6f8382f67e6b61623fbe62c60423f8f7983f88f40c6f42924594f3de492a232e9e703b241c3b17b130f8daa59"), - (2, "0a0a17d71bc98fa5c24ea611c856d0d08c6a765ea3c4c8f068668e0bdff710b82b0d2eead83d059386cd3cbdf4308418d4b81e6f52c001a9141ec477a8d24845"), + ( + 0, + "7a99714dc6cc917faa2afded8028159a5048caf6f8382f67e6b61623fbe62c60423f8f7983f88f40c6f42924594f3de492a232e9e703b241c3b17b130f8daa59", + ), + ( + 2, + "0a0a17d71bc98fa5c24ea611c856d0d08c6a765ea3c4c8f068668e0bdff710b82b0d2eead83d059386cd3cbdf4308418d4b81e6f52c001a9141ec477a8d24845", + ), ]; make_multisig_spend_sig(challenge, sigs_hex) }; @@ -963,16 +969,31 @@ pub async fn test_fixed_signatures_generic2( SighashInputCommitmentVersion::V0 => { let htlc_multisig = { let sigs_hex = [ - (0, "0ff63e871249f4b6d8de07216617054c71a4b341e11afd405712cc108cb8e315f4b577444a29a81126aab9b7ad426594c2b39e5bc2e11169b1c64e62524620fe"), - (1, "cd190e9a746aefb9ccec04a178017db55154f6370993139819ab270e988ff2c510b5bbcd95da31dff124f22b323bc3547ec15045e92552f7a951433c064d07f0"), + ( + 0, + "0ff63e871249f4b6d8de07216617054c71a4b341e11afd405712cc108cb8e315f4b577444a29a81126aab9b7ad426594c2b39e5bc2e11169b1c64e62524620fe", + ), + ( + 1, + "cd190e9a746aefb9ccec04a178017db55154f6370993139819ab270e988ff2c510b5bbcd95da31dff124f22b323bc3547ec15045e92552f7a951433c064d07f0", + ), ]; make_htlc_multisig_refund_sig(htlc_multisig_challenge, sigs_hex) }; let multisig = { let sigs_hex = [ - (1, "e94989eddcbb19eb87a02935a6b9e09e0cb0537d5aadf2d8bb37872949176820970c6d69320712be192805ad4609020237e46e461c0aeb42712f5feaceee5fd8"), - (2, "90da875f04bc2db203e5a4c322514bb17d01870a34f40bba5922439580db156c4d9b455ce2b2ceb8e070541fb7a503752dfbc670ac32c858c462044e1ac8e421"), - (3, "1ae75282887fcdca2f9cccbca269db14d368fd29658b92e32af98c9488ab6745cfd54dacafc91fcf63dbce69d196716345fd0d9cbcff25ef251286ab1bea025e") + ( + 1, + "e94989eddcbb19eb87a02935a6b9e09e0cb0537d5aadf2d8bb37872949176820970c6d69320712be192805ad4609020237e46e461c0aeb42712f5feaceee5fd8", + ), + ( + 2, + "90da875f04bc2db203e5a4c322514bb17d01870a34f40bba5922439580db156c4d9b455ce2b2ceb8e070541fb7a503752dfbc670ac32c858c462044e1ac8e421", + ), + ( + 3, + "1ae75282887fcdca2f9cccbca269db14d368fd29658b92e32af98c9488ab6745cfd54dacafc91fcf63dbce69d196716345fd0d9cbcff25ef251286ab1bea025e", + ), ]; make_multisig_spend_sig(multisig_challenge, sigs_hex) }; @@ -1049,16 +1070,31 @@ pub async fn test_fixed_signatures_generic2( SighashInputCommitmentVersion::V1 => { let htlc_multisig = { let sigs_hex = [ - (0, "dbc526968f2506a1682cff368c2bb805f426dffbf85bcfc175b67f97444c0cb7285d1d80f582ae8192f7c329d895182a454735ffa9debbfbdf8517f9f3b5ddfc"), - (1, "2a9dabb9953ba0b7fb66b0cad67a569f8df8947b07e41a46b640a0addc19b0131b6b2f46d3d784a5ba66d991b3e3af9ac7d6720c7d80cc6040892226a7b41669"), + ( + 0, + "dbc526968f2506a1682cff368c2bb805f426dffbf85bcfc175b67f97444c0cb7285d1d80f582ae8192f7c329d895182a454735ffa9debbfbdf8517f9f3b5ddfc", + ), + ( + 1, + "2a9dabb9953ba0b7fb66b0cad67a569f8df8947b07e41a46b640a0addc19b0131b6b2f46d3d784a5ba66d991b3e3af9ac7d6720c7d80cc6040892226a7b41669", + ), ]; make_htlc_multisig_refund_sig(htlc_multisig_challenge, sigs_hex) }; let multisig = { let sigs_hex = [ - (1, "8aacc97858a80bb779b000f18bf82c984977ca2a4d8560ae72421c9cd9cb7b513d35a62123553e0d24c0249eb2e04d2f99fe38eb41505a1081cd2d684a8a45d2"), - (2, "c13c5bb22e719b5c7966aa9b58c2ae8e6bf3f848e62df19d38c4d41c7acd9d48eda1e13f18a25c9524904c4866143a95fd963606b5a77979a6dfc04cdebc979d"), - (3, "93b5538c13a981dc8d6978361f13627603464de82d45f966de78b829a87eab642087b5bbc5b3aed5a888b8387491fe7fcd27f3e69bf7a70e5d12f004691da173") + ( + 1, + "8aacc97858a80bb779b000f18bf82c984977ca2a4d8560ae72421c9cd9cb7b513d35a62123553e0d24c0249eb2e04d2f99fe38eb41505a1081cd2d684a8a45d2", + ), + ( + 2, + "c13c5bb22e719b5c7966aa9b58c2ae8e6bf3f848e62df19d38c4d41c7acd9d48eda1e13f18a25c9524904c4866143a95fd963606b5a77979a6dfc04cdebc979d", + ), + ( + 3, + "93b5538c13a981dc8d6978361f13627603464de82d45f966de78b829a87eab642087b5bbc5b3aed5a888b8387491fe7fcd27f3e69bf7a70e5d12f004691da173", + ), ]; make_multisig_spend_sig(multisig_challenge, sigs_hex) }; @@ -1587,80 +1623,95 @@ pub async fn test_fixed_signatures_generic_no_legacy( let expected_sigs = { let htlc_multisig = { let sigs_hex = [ - (0, "3b603dac168db6061361b7352d25a60b1aa6d9d5c270f6a0177158046d0721c8fee6dfd61c9d2c90c66cc578cd963fd89ca7aef068126a34bdd71b839dadd244"), - (1, "da4d613bdd1d3827b11a44af75458f28d9fd2951131967701acf7708219b0ea2cd71b244a639984aeb7f5ef70f7267bf37af5d62953716562bde7f99b19988ac"), - ]; + ( + 0, + "3b603dac168db6061361b7352d25a60b1aa6d9d5c270f6a0177158046d0721c8fee6dfd61c9d2c90c66cc578cd963fd89ca7aef068126a34bdd71b839dadd244", + ), + ( + 1, + "da4d613bdd1d3827b11a44af75458f28d9fd2951131967701acf7708219b0ea2cd71b244a639984aeb7f5ef70f7267bf37af5d62953716562bde7f99b19988ac", + ), + ]; make_htlc_multisig_refund_sig(htlc_multisig_challenge, sigs_hex) }; let multisig = { let sigs_hex = [ - (1, "ade634188ba99611be5ed37d92b4e41df7d7c5b1c82bc7a48d0b767ad2dca7c10eb4dee6592d1a3cbb46d7db3945bb79f1fa3461cda8c8685dc8ffbae2214880"), - (2, "ba2d3986fb2c7e9c283831e35bf9abad1cd3aa16a8490248ac2fc6b56e2117c42c87dcf687ec68f932fa36dc5dc3bc8b9e72aab2c77154c13d3c64d17ef9cd6e"), - (3, "8430765edd8926d5259e8df0a42b24f76d97471213318da81e4f620800766079a2747c6330354eab5e964945a6183e78e58db5bb06d20834969f3a2b359f2f5d") - ]; + ( + 1, + "ade634188ba99611be5ed37d92b4e41df7d7c5b1c82bc7a48d0b767ad2dca7c10eb4dee6592d1a3cbb46d7db3945bb79f1fa3461cda8c8685dc8ffbae2214880", + ), + ( + 2, + "ba2d3986fb2c7e9c283831e35bf9abad1cd3aa16a8490248ac2fc6b56e2117c42c87dcf687ec68f932fa36dc5dc3bc8b9e72aab2c77154c13d3c64d17ef9cd6e", + ), + ( + 3, + "8430765edd8926d5259e8df0a42b24f76d97471213318da81e4f620800766079a2747c6330354eab5e964945a6183e78e58db5bb06d20834969f3a2b359f2f5d", + ), + ]; make_multisig_spend_sig(multisig_challenge, sigs_hex) }; vec![ - Some(InputWitness::Standard(make_pub_key_hash_spend_sig( - find_pub_key_for_pkh_dest(&account1_dest4, &account1), - "ee6099727b2ccc20310f4a202b163553717042d8834617273610a617d206e111c702f747161c5e6cf08a29adc0a7d84f42828b9a57115ab68dd7f9ef0652296d", - ))), - Some(InputWitness::Standard(make_pub_key_spend_sig( - "ba2d3986fb2c7e9c283831e35bf9abad1cd3aa16a8490248ac2fc6b56e2117c42c87dcf687ec68f932fa36dc5dc3bc8b9e72aab2c77154c13d3c64d17ef9cd6e", - ))), - Some(InputWitness::Standard(make_pub_key_hash_spend_sig( - find_pub_key_for_pkh_dest(&decommission_dest, &account1), - "7db9e5a05b66818b222d01da4793bdf6bc1ff14c2dde434ae63e37f33d95363c81f2fd6ed36a984d5f5cf233e4f9d384f00c42d5619632dbdda4817777d763f7", - ))), - Some(InputWitness::Standard(make_htlc_pub_key_spend_sig( - htlc_secret, - "7fb4da18ae9927d62ae07513948fa76a655838fc9780287a4062bb9693d477bcfd0788a2c09ea3992ea92df5919e399899645c57d0f064cbb42dbe4577753338", - ))), - Some(InputWitness::Standard(htlc_multisig)), - Some(InputWitness::Standard(multisig)), - Some(InputWitness::Standard(make_pub_key_hash_spend_sig( - find_pub_key_for_pkh_dest(&acc_dests[0], &account1), - "89e7f9bd71ac50d5e1bb1427c466807ccbf7848c72517fdefcf94b9e941b1817be394a069e260c1f6831021dd8117f6c39920a3340bcfc798219d1b2d9dc55ff", - ))), - Some(InputWitness::Standard(make_pub_key_hash_spend_sig( - find_pub_key_for_pkh_dest(&acc_dests[1], &account1), - "03b50188f8f0989ab8831281655c9c27e61b3faf2ad3fe8e143887cccd7e6bf08eb12a8b8d017746c888ef9723a42a3722be985ff93195ac7da833c9f381de3d", - ))), - Some(InputWitness::Standard(make_pub_key_hash_spend_sig( - find_pub_key_for_pkh_dest(&acc_dests[2], &account1), - "358cc6a6e9502725688b9c71fa2f5801f79dfb8bac0373cacb25574b39134ceedbff20b25f420794999603adb1f84c916834389d7f7c6e36220b00b410e3fc1a", - ))), - Some(InputWitness::Standard(make_pub_key_hash_spend_sig( - find_pub_key_for_pkh_dest(&acc_dests[3], &account1), - "32d3e7c4906bfeef7bdfe8f59f9a9fc0a56dc0f3f3a3f1a800a6c93a18b53af1596d20f01453bdb1c0e9da84350d41c9ceb759d4486505da7277f088a43cd495", - ))), - Some(InputWitness::Standard(make_pub_key_hash_spend_sig( - find_pub_key_for_pkh_dest(&acc_dests[4], &account1), - "8a5f0104dd95d4c90a9ab81bf2de6fd8a62b5d47756c6b52c34f036f35740bff5a89024c559656a77011863632e57956097c0f9b2ab62e7741f6272a3b2aedd2", - ))), - Some(InputWitness::Standard(make_pub_key_hash_spend_sig( - find_pub_key_for_pkh_dest(&acc_dests[5], &account1), - "b939110eb9c76364a7f70bd7ad2549728da081b63155a93f9d073a0316a50996c354ea7d667addd8190775c1f47eb5078696d8476a65eaffffd3f369bb3d416a", - ))), - Some(InputWitness::Standard(make_pub_key_hash_spend_sig( - find_pub_key_for_pkh_dest(&acc_dests[6], &account1), - "abb20462e7be8fbf7995fa9f71943447795f3f59b04eb067887f714431a48b64fe5bb280b045167c2b78d049bc478be686678974a9f91ea2705d71a99b782f9f", - ))), - Some(InputWitness::Standard(make_pub_key_hash_spend_sig( - find_pub_key_for_pkh_dest(&acc_dests[7], &account1), - "035af1829e02d003abcb2816680f8ac25b1d4c16ec09852e89bc551cc0f7a4cd1e14d7e840c451d2c6b8113cd90f6162b0ebdb4d21999f5c55ffb174405812fa", - ))), - Some(InputWitness::Standard(make_pub_key_hash_spend_sig( - find_pub_key_for_pkh_dest(&acc_dests[8], &account1), - "bec8014f5d25ffcc96d186d2e355c1526a2f301efcbcfde82d4e9f7a57f212f0df2be7fc739be8b9de1c5a27e5e76cf47e01117368f6bcb1c2512d0aabb65805", - ))), - Some(InputWitness::Standard(make_pub_key_hash_spend_sig( - find_pub_key_for_pkh_dest(&acc_dests[9], &account1), - "769435a863811adcacd5593d763c938d488318a2fb664c0e039cf93d9b0d704770214f58edd35d67e1e52b4da37c7c704e852b0d2f620d0a87b312ac5ac46dae", - ))), - Some(InputWitness::NoSignature(None)), - ] + Some(InputWitness::Standard(make_pub_key_hash_spend_sig( + find_pub_key_for_pkh_dest(&account1_dest4, &account1), + "ee6099727b2ccc20310f4a202b163553717042d8834617273610a617d206e111c702f747161c5e6cf08a29adc0a7d84f42828b9a57115ab68dd7f9ef0652296d", + ))), + Some(InputWitness::Standard(make_pub_key_spend_sig( + "ba2d3986fb2c7e9c283831e35bf9abad1cd3aa16a8490248ac2fc6b56e2117c42c87dcf687ec68f932fa36dc5dc3bc8b9e72aab2c77154c13d3c64d17ef9cd6e", + ))), + Some(InputWitness::Standard(make_pub_key_hash_spend_sig( + find_pub_key_for_pkh_dest(&decommission_dest, &account1), + "7db9e5a05b66818b222d01da4793bdf6bc1ff14c2dde434ae63e37f33d95363c81f2fd6ed36a984d5f5cf233e4f9d384f00c42d5619632dbdda4817777d763f7", + ))), + Some(InputWitness::Standard(make_htlc_pub_key_spend_sig( + htlc_secret, + "7fb4da18ae9927d62ae07513948fa76a655838fc9780287a4062bb9693d477bcfd0788a2c09ea3992ea92df5919e399899645c57d0f064cbb42dbe4577753338", + ))), + Some(InputWitness::Standard(htlc_multisig)), + Some(InputWitness::Standard(multisig)), + Some(InputWitness::Standard(make_pub_key_hash_spend_sig( + find_pub_key_for_pkh_dest(&acc_dests[0], &account1), + "89e7f9bd71ac50d5e1bb1427c466807ccbf7848c72517fdefcf94b9e941b1817be394a069e260c1f6831021dd8117f6c39920a3340bcfc798219d1b2d9dc55ff", + ))), + Some(InputWitness::Standard(make_pub_key_hash_spend_sig( + find_pub_key_for_pkh_dest(&acc_dests[1], &account1), + "03b50188f8f0989ab8831281655c9c27e61b3faf2ad3fe8e143887cccd7e6bf08eb12a8b8d017746c888ef9723a42a3722be985ff93195ac7da833c9f381de3d", + ))), + Some(InputWitness::Standard(make_pub_key_hash_spend_sig( + find_pub_key_for_pkh_dest(&acc_dests[2], &account1), + "358cc6a6e9502725688b9c71fa2f5801f79dfb8bac0373cacb25574b39134ceedbff20b25f420794999603adb1f84c916834389d7f7c6e36220b00b410e3fc1a", + ))), + Some(InputWitness::Standard(make_pub_key_hash_spend_sig( + find_pub_key_for_pkh_dest(&acc_dests[3], &account1), + "32d3e7c4906bfeef7bdfe8f59f9a9fc0a56dc0f3f3a3f1a800a6c93a18b53af1596d20f01453bdb1c0e9da84350d41c9ceb759d4486505da7277f088a43cd495", + ))), + Some(InputWitness::Standard(make_pub_key_hash_spend_sig( + find_pub_key_for_pkh_dest(&acc_dests[4], &account1), + "8a5f0104dd95d4c90a9ab81bf2de6fd8a62b5d47756c6b52c34f036f35740bff5a89024c559656a77011863632e57956097c0f9b2ab62e7741f6272a3b2aedd2", + ))), + Some(InputWitness::Standard(make_pub_key_hash_spend_sig( + find_pub_key_for_pkh_dest(&acc_dests[5], &account1), + "b939110eb9c76364a7f70bd7ad2549728da081b63155a93f9d073a0316a50996c354ea7d667addd8190775c1f47eb5078696d8476a65eaffffd3f369bb3d416a", + ))), + Some(InputWitness::Standard(make_pub_key_hash_spend_sig( + find_pub_key_for_pkh_dest(&acc_dests[6], &account1), + "abb20462e7be8fbf7995fa9f71943447795f3f59b04eb067887f714431a48b64fe5bb280b045167c2b78d049bc478be686678974a9f91ea2705d71a99b782f9f", + ))), + Some(InputWitness::Standard(make_pub_key_hash_spend_sig( + find_pub_key_for_pkh_dest(&acc_dests[7], &account1), + "035af1829e02d003abcb2816680f8ac25b1d4c16ec09852e89bc551cc0f7a4cd1e14d7e840c451d2c6b8113cd90f6162b0ebdb4d21999f5c55ffb174405812fa", + ))), + Some(InputWitness::Standard(make_pub_key_hash_spend_sig( + find_pub_key_for_pkh_dest(&acc_dests[8], &account1), + "bec8014f5d25ffcc96d186d2e355c1526a2f301efcbcfde82d4e9f7a57f212f0df2be7fc739be8b9de1c5a27e5e76cf47e01117368f6bcb1c2512d0aabb65805", + ))), + Some(InputWitness::Standard(make_pub_key_hash_spend_sig( + find_pub_key_for_pkh_dest(&acc_dests[9], &account1), + "769435a863811adcacd5593d763c938d488318a2fb664c0e039cf93d9b0d704770214f58edd35d67e1e52b4da37c7c704e852b0d2f620d0a87b312ac5ac46dae", + ))), + Some(InputWitness::NoSignature(None)), + ] }; assert_eq!(ptx.witnesses().len(), expected_sigs.len()); @@ -1958,24 +2009,38 @@ pub async fn test_fixed_signatures_generic_htlc_refunding( find_pub_key_for_pkh_dest(&decommission_dest, &account1), "3ed693bc5fcec032ea40453dd0542a696b9765728cbc279ae73dee69bfec9538ad62a99fe3bf52315c06186e0d60a1a315f5c0856ac0280acc4365e6558ba452", ))), - Some(InputWitness::Standard(make_htlc_uniparty_pub_key_refund_sig( - "d929e839b1e219039d5b9bfd59b70e18e4da37c4341d137b8c316ed8449a0c7a725f911066524014db257a7d92d2f629f14c71d16a9c577add4a43c9778cbb5e", - ))), - Some(InputWitness::Standard(make_htlc_uniparty_pub_key_hash_refund_sig( - standalone_pk, - "d929e839b1e219039d5b9bfd59b70e18e4da37c4341d137b8c316ed8449a0c7a725f911066524014db257a7d92d2f629f14c71d16a9c577add4a43c9778cbb5e", - ))), - Some(InputWitness::Standard(make_htlc_uniparty_pub_key_refund_sig( - "da9982cf034cb550961077a4647d2d6d0398d93cfbce12a223487e7314a5c94b1b8d8f1aca6a071ee4581602621467512e1e98a4160e0a66b67554459641a0ae", - ))), - Some(InputWitness::Standard(make_htlc_uniparty_pub_key_hash_refund_sig( - account1_pk, - "da9982cf034cb550961077a4647d2d6d0398d93cfbce12a223487e7314a5c94b1b8d8f1aca6a071ee4581602621467512e1e98a4160e0a66b67554459641a0ae", - ))), + Some(InputWitness::Standard( + make_htlc_uniparty_pub_key_refund_sig( + "d929e839b1e219039d5b9bfd59b70e18e4da37c4341d137b8c316ed8449a0c7a725f911066524014db257a7d92d2f629f14c71d16a9c577add4a43c9778cbb5e", + ), + )), + Some(InputWitness::Standard( + make_htlc_uniparty_pub_key_hash_refund_sig( + standalone_pk, + "d929e839b1e219039d5b9bfd59b70e18e4da37c4341d137b8c316ed8449a0c7a725f911066524014db257a7d92d2f629f14c71d16a9c577add4a43c9778cbb5e", + ), + )), + Some(InputWitness::Standard( + make_htlc_uniparty_pub_key_refund_sig( + "da9982cf034cb550961077a4647d2d6d0398d93cfbce12a223487e7314a5c94b1b8d8f1aca6a071ee4581602621467512e1e98a4160e0a66b67554459641a0ae", + ), + )), + Some(InputWitness::Standard( + make_htlc_uniparty_pub_key_hash_refund_sig( + account1_pk, + "da9982cf034cb550961077a4647d2d6d0398d93cfbce12a223487e7314a5c94b1b8d8f1aca6a071ee4581602621467512e1e98a4160e0a66b67554459641a0ae", + ), + )), Some(InputWitness::Standard({ let sigs_hex = [ - (0, "da9982cf034cb550961077a4647d2d6d0398d93cfbce12a223487e7314a5c94b1b8d8f1aca6a071ee4581602621467512e1e98a4160e0a66b67554459641a0ae"), - (1, "23f110161a7c9097127812a98b024c599248a53578d35ee3bfac3e723d56011577ccef5be3a7151bb56381b3efc31e72bc9a83f755456f15eb3a044100d14b9b"), + ( + 0, + "da9982cf034cb550961077a4647d2d6d0398d93cfbce12a223487e7314a5c94b1b8d8f1aca6a071ee4581602621467512e1e98a4160e0a66b67554459641a0ae", + ), + ( + 1, + "23f110161a7c9097127812a98b024c599248a53578d35ee3bfac3e723d56011577ccef5be3a7151bb56381b3efc31e72bc9a83f755456f15eb3a044100d14b9b", + ), ]; make_htlc_multisig_refund_sig(htlc_multisig_challenge, sigs_hex) })), @@ -1987,24 +2052,38 @@ pub async fn test_fixed_signatures_generic_htlc_refunding( find_pub_key_for_pkh_dest(&decommission_dest, &account1), "da5f561569793b95558e8cdbcd62717223bfc338ef6b638b04cd3bf9143f356a4f8dd511fd3d297d629d58956046e13d9425e1122c14b3966743145a9baf29a0", ))), - Some(InputWitness::Standard(make_htlc_uniparty_pub_key_refund_sig( - "37c991c15d447d1c9918f3a61c55a8b3231b94e2087ac799f08651ec2f69c940638a0e77c20f479913c2d7059e424089672d20b6d586f27be78598c723eaf999", - ))), - Some(InputWitness::Standard(make_htlc_uniparty_pub_key_hash_refund_sig( - standalone_pk, - "37c991c15d447d1c9918f3a61c55a8b3231b94e2087ac799f08651ec2f69c940638a0e77c20f479913c2d7059e424089672d20b6d586f27be78598c723eaf999", - ))), - Some(InputWitness::Standard(make_htlc_uniparty_pub_key_refund_sig( - "1a7017dc145b67099b7fc51b45982a2a8388a366e0c3760471ce5cfe3a02821e2fc8438b41d631fcafb0b1bf0a1a709489064ca166113e648c14b09e214fc9e3", - ))), - Some(InputWitness::Standard(make_htlc_uniparty_pub_key_hash_refund_sig( - account1_pk, - "1a7017dc145b67099b7fc51b45982a2a8388a366e0c3760471ce5cfe3a02821e2fc8438b41d631fcafb0b1bf0a1a709489064ca166113e648c14b09e214fc9e3", - ))), + Some(InputWitness::Standard( + make_htlc_uniparty_pub_key_refund_sig( + "37c991c15d447d1c9918f3a61c55a8b3231b94e2087ac799f08651ec2f69c940638a0e77c20f479913c2d7059e424089672d20b6d586f27be78598c723eaf999", + ), + )), + Some(InputWitness::Standard( + make_htlc_uniparty_pub_key_hash_refund_sig( + standalone_pk, + "37c991c15d447d1c9918f3a61c55a8b3231b94e2087ac799f08651ec2f69c940638a0e77c20f479913c2d7059e424089672d20b6d586f27be78598c723eaf999", + ), + )), + Some(InputWitness::Standard( + make_htlc_uniparty_pub_key_refund_sig( + "1a7017dc145b67099b7fc51b45982a2a8388a366e0c3760471ce5cfe3a02821e2fc8438b41d631fcafb0b1bf0a1a709489064ca166113e648c14b09e214fc9e3", + ), + )), + Some(InputWitness::Standard( + make_htlc_uniparty_pub_key_hash_refund_sig( + account1_pk, + "1a7017dc145b67099b7fc51b45982a2a8388a366e0c3760471ce5cfe3a02821e2fc8438b41d631fcafb0b1bf0a1a709489064ca166113e648c14b09e214fc9e3", + ), + )), Some(InputWitness::Standard({ let sigs_hex = [ - (0, "1a7017dc145b67099b7fc51b45982a2a8388a366e0c3760471ce5cfe3a02821e2fc8438b41d631fcafb0b1bf0a1a709489064ca166113e648c14b09e214fc9e3"), - (1, "f0794522d14c73ae2cba145afac92df27c279b915ff3f6a0709064b23defdb73d8b8a621c96ce6fd045439a1bbb7a85926471537da8590fac35311560eada405"), + ( + 0, + "1a7017dc145b67099b7fc51b45982a2a8388a366e0c3760471ce5cfe3a02821e2fc8438b41d631fcafb0b1bf0a1a709489064ca166113e648c14b09e214fc9e3", + ), + ( + 1, + "f0794522d14c73ae2cba145afac92df27c279b915ff3f6a0709064b23defdb73d8b8a621c96ce6fd045439a1bbb7a85926471537da8590fac35311560eada405", + ), ]; make_htlc_multisig_refund_sig(htlc_multisig_challenge, sigs_hex) })), diff --git a/wallet/src/signer/tests/generic_tests.rs b/wallet/src/signer/tests/generic_tests.rs index 2c2f5dadf4..ffb213703a 100644 --- a/wallet/src/signer/tests/generic_tests.rs +++ b/wallet/src/signer/tests/generic_tests.rs @@ -19,19 +19,23 @@ use std::{ sync::Arc, }; -use itertools::{izip, Itertools as _}; +use itertools::{Itertools as _, izip}; use common::{ chain::{ - self, + self, AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, ChainConfig, + ChainstateUpgradeBuilder, Currency, DelegationId, Destination, GenBlock, NetUpgrades, + OrderAccountCommand, OrderData, OrderId, OutPointSourceId, PoolId, + SighashInputCommitmentVersion, SignedTransactionIntent, Transaction, TxInput, TxOutput, + UtxoOutPoint, block::timestamp::BlockTimestamp, classic_multisig::ClassicMultisigChallenge, - config::{create_regtest, ChainType}, + config::{ChainType, create_regtest}, htlc::{HashedTimelockContract, HtlcSecret}, output_value::OutputValue, signature::{ - inputsig::arbitrary_message::produce_message_challenge, DestinationSigError, - Transactable, + DestinationSigError, Transactable, + inputsig::arbitrary_message::produce_message_challenge, }, stakelock::StakePoolData, timelock::OutputTimeLock, @@ -39,16 +43,11 @@ use common::{ IsTokenFreezable, IsTokenUnfreezable, Metadata, NftIssuance, NftIssuanceV0, TokenId, TokenIssuance, TokenIssuanceV1, TokenTotalSupply, }, - AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, ChainConfig, - ChainstateUpgradeBuilder, Currency, DelegationId, Destination, GenBlock, NetUpgrades, - OrderAccountCommand, OrderData, OrderId, OutPointSourceId, PoolId, - SighashInputCommitmentVersion, SignedTransactionIntent, Transaction, TxInput, TxOutput, - UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight, Id, Idable, H256}, + primitives::{Amount, BlockHeight, H256, Id, Idable, per_thousand::PerThousand}, }; use crypto::{ - key::{hdkd::u31::U31, KeyKind, PrivateKey}, + key::{KeyKind, PrivateKey, hdkd::u31::U31}, vrf::VRFPrivateKey, }; use logging::log; @@ -61,19 +60,19 @@ use test_utils::{ use tx_verifier::error::{InputCheckErrorPayload, ScriptError}; use wallet_storage::{DefaultBackend, Store, TransactionRwUnlocked, Transactional}; use wallet_types::{ + BlockInfo, KeyPurpose, account_info::DEFAULT_ACCOUNT_INDEX, partially_signed_transaction::{ OrderAdditionalInfo, PoolAdditionalInfo, PtxAdditionalInfo, TokenAdditionalInfo, TokensAdditionalInfo, }, - BlockInfo, KeyPurpose, }; use crate::{ + Account, SendRequest, account::PoolData, key_chain::AccountKeyChains, - signer::{tests::account_from_mnemonic, Signer, SignerError}, - Account, SendRequest, + signer::{Signer, SignerError, tests::account_from_mnemonic}, }; #[derive(Debug)] diff --git a/wallet/src/signer/tests/mod.rs b/wallet/src/signer/tests/mod.rs index f7614cb553..765dfc6e08 100644 --- a/wallet/src/signer/tests/mod.rs +++ b/wallet/src/signer/tests/mod.rs @@ -19,14 +19,14 @@ pub mod generic_tests; use std::sync::Arc; use common::chain::ChainConfig; -use crypto::key::{hdkd::u31::U31, PredefinedSigAuxDataProvider}; +use crypto::key::{PredefinedSigAuxDataProvider, hdkd::u31::U31}; use wallet_storage::StoreTxRwUnlocked; use wallet_types::seed_phrase::StoreSeedPhrase; use crate::{ - key_chain::{AccountKeyChainImplSoftware, MasterKeyChain, LOOKAHEAD_SIZE}, - signer::software_signer::SoftwareSigner, Account, + key_chain::{AccountKeyChainImplSoftware, LOOKAHEAD_SIZE, MasterKeyChain}, + signer::software_signer::SoftwareSigner, }; const MNEMONIC: &str = diff --git a/wallet/src/signer/trezor_signer/mod.rs b/wallet/src/signer/trezor_signer/mod.rs index eb6b0644d6..3783c8b037 100644 --- a/wallet/src/signer/trezor_signer/mod.rs +++ b/wallet/src/signer/trezor_signer/mod.rs @@ -19,15 +19,20 @@ use std::{ }; use async_trait::async_trait; -use itertools::{izip, Itertools}; +use itertools::{Itertools, izip}; use common::{ address::Address, chain::{ + AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, ChainConfig, Destination, + OrderAccountCommand, OutPointSourceId, SighashInputCommitmentVersion, + SignedTransactionIntent, Transaction, TxInput, TxOutput, UtxoOutPoint, config::ChainType, output_value::OutputValue, signature::{ + DestinationSigError, inputsig::{ + InputWitness, arbitrary_message::ArbitraryMessageSignature, authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, authorize_pubkey_spend::AuthorizedPublicKeySpend, @@ -37,35 +42,29 @@ use common::{ multisig_partial_signature::{self, PartiallySignedMultisigChallenge}, }, standard_signature::StandardInputSignature, - InputWitness, }, sighash::{sighashtype::SigHashType, signature_hash}, - DestinationSigError, }, timelock::OutputTimeLock, tokens::{NftIssuance, TokenId, TokenIssuance, TokenTotalSupply}, - AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, ChainConfig, Destination, - OrderAccountCommand, OutPointSourceId, SighashInputCommitmentVersion, - SignedTransactionIntent, Transaction, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{BlockHeight, Idable, H256}, + primitives::{BlockHeight, H256, Idable}, }; use crypto::key::{ + SigAuxDataProvider, Signature, SignatureError, extended::ExtendedPublicKey, hdkd::{chain_code::ChainCode, derivable::Derivable, u31::U31}, - secp256k1::{extended_keys::Secp256k1ExtendedPublicKey, Secp256k1PublicKey}, + secp256k1::{Secp256k1PublicKey, extended_keys::Secp256k1ExtendedPublicKey}, signature::SignatureKind, - SigAuxDataProvider, Signature, SignatureError, }; use logging::log; use randomness::make_true_rng; use serialization::Encode; use trezor_client::{ - client::{mintlayer::MintlayerSignature, TransactionId}, + Features, Model, + client::{TransactionId, mintlayer::MintlayerSignature}, find_devices, protos::{ - features::Capability, - mintlayer_tx_ack::{MintlayerTxInput, MintlayerTxOutput}, MintlayerAccountCommandTxInput, MintlayerAccountSpendingDelegationBalance, MintlayerAccountTxInput, MintlayerAddressPath, MintlayerAddressType, MintlayerBurnTxOutput, MintlayerChainType, MintlayerChangeTokenAuthority, MintlayerChangeTokenMetadataUri, @@ -78,18 +77,20 @@ use trezor_client::{ MintlayerOrderCommandTxInput, MintlayerOutputValue, MintlayerProduceBlockFromStakeTxOutput, MintlayerTokenOutputValue, MintlayerTokenTotalSupply, MintlayerTokenTotalSupplyType, MintlayerUnfreezeToken, MintlayerUnmintTokens, MintlayerUtxoType, + features::Capability, + mintlayer_tx_ack::{MintlayerTxInput, MintlayerTxOutput}, }, - Features, Model, }; use trezor_client::{ - protos::{MintlayerTransferTxOutput, MintlayerUtxoTxInput}, Trezor, + protos::{MintlayerTransferTxOutput, MintlayerUtxoTxInput}, }; use utils::ensure; use wallet_storage::{ WalletStorageReadLocked, WalletStorageReadUnlocked, WalletStorageWriteUnlocked, }; use wallet_types::{ + AccountId, account_info::DEFAULT_ACCOUNT_INDEX, hw_data::{HardwareWalletData, HardwareWalletFullInfo, TrezorFullInfo}, partially_signed_transaction::{ @@ -97,22 +98,21 @@ use wallet_types::{ TokensAdditionalInfo, }, signature_status::SignatureStatus, - AccountId, }; use crate::{ - key_chain::{make_account_path, AccountKeyChainImplHardware, AccountKeyChains, FoundPubKey}, + Account, WalletError, WalletResult, + key_chain::{AccountKeyChainImplHardware, AccountKeyChains, FoundPubKey, make_account_path}, signer::{ hardware_signer_utils::{ - arbitrary_message_signature_from_raw_sig, sign_with_standalone_private_keys, - StandaloneInput, StandaloneInputs, + StandaloneInput, StandaloneInputs, arbitrary_message_signature_from_raw_sig, + sign_with_standalone_private_keys, }, utils::produce_uniparty_signature_for_input, }, - Account, WalletError, WalletResult, }; -use super::{utils::is_htlc_utxo, Signer, SignerError, SignerProvider, SignerResult}; +use super::{Signer, SignerError, SignerProvider, SignerResult, utils::is_htlc_utxo}; const REQUIRED_FIRMWARE_MAJOR_VERSION: u32 = 1; @@ -138,7 +138,9 @@ pub enum TrezorError { NoUniqueDeviceFound(Vec), #[error("Cannot get the supported features for the connected Trezor device")] CannotGetDeviceFeatures, - #[error("The connected Trezor device does not support the Mintlayer capabilities, please install the correct firmware")] + #[error( + "The connected Trezor device does not support the Mintlayer capabilities, please install the correct firmware" + )] MintlayerFeaturesNotSupported, #[error("Trezor device error: {0}")] DeviceError(String), @@ -152,14 +154,18 @@ pub enum TrezorError { MultipleSignaturesReturned, #[error("A multisig signature was returned for a single address from Device")] MultisigSignatureReturned, - #[error("The file being loaded is a Ledger wallet and cannot be used with the connected Trezor wallet")] + #[error( + "The file being loaded is a Ledger wallet and cannot be used with the connected Trezor wallet" + )] WalletFileIsLedgerWallet, - #[error("The file being loaded is a software wallet and cannot be used with the connected Trezor wallet")] + #[error( + "The file being loaded is a software wallet and cannot be used with the connected Trezor wallet" + )] WalletFileIsSoftwareWallet, #[error( "Public keys mismatch - wrong device or passphrase.\n\ Last used device id: \"{file_device_id}\", connected device id: \"{connected_device_id}\".\n\ - Last used device name: \"{file_device_name}\", connected device name: \"{connected_device_name}\".", + Last used device name: \"{file_device_name}\", connected device name: \"{connected_device_name}\"." )] HardwareWalletDifferentMnemonicOrPassphrase { file_device_id: String, @@ -167,7 +173,9 @@ pub enum TrezorError { file_device_name: String, connected_device_name: String, }, - #[error("The file being loaded corresponds to the connected hardware wallet, but public keys are different. Maybe a wrong passphrase was entered?")] + #[error( + "The file being loaded corresponds to the connected hardware wallet, but public keys are different. Maybe a wrong passphrase was entered?" + )] HardwareWalletDifferentPassphrase, #[error("Missing hardware wallet data in database")] MissingHardwareWalletData, diff --git a/wallet/src/signer/trezor_signer/test_utils/auto_confirmer.rs b/wallet/src/signer/trezor_signer/test_utils/auto_confirmer.rs index 75a8afaf3d..b1a2983cee 100644 --- a/wallet/src/signer/trezor_signer/test_utils/auto_confirmer.rs +++ b/wallet/src/signer/trezor_signer/test_utils/auto_confirmer.rs @@ -16,13 +16,13 @@ use std::{ fmt::Write as _, sync::Arc, - thread::{sleep, JoinHandle}, + thread::{JoinHandle, sleep}, time::Duration, }; use trezor_client::protos::{ - debug_link_decision::DebugButton, debug_link_get_state::DebugWaitType, DebugLinkDecision, - DebugLinkGetState, + DebugLinkDecision, DebugLinkGetState, debug_link_decision::DebugButton, + debug_link_get_state::DebugWaitType, }; use logging::log; diff --git a/wallet/src/signer/trezor_signer/test_utils/mod.rs b/wallet/src/signer/trezor_signer/test_utils/mod.rs index 2e29200895..04165a1eb9 100644 --- a/wallet/src/signer/trezor_signer/test_utils/mod.rs +++ b/wallet/src/signer/trezor_signer/test_utils/mod.rs @@ -17,8 +17,8 @@ mod auto_confirmer; use itertools::Itertools as _; use trezor_client::{ - transport::{udp::UdpTransport, webusb::WebUsbTransport}, AvailableDevice, Model, Trezor, TrezorMessage, + transport::{udp::UdpTransport, webusb::WebUsbTransport}, }; use logging::log; diff --git a/wallet/src/signer/trezor_signer/tests.rs b/wallet/src/signer/trezor_signer/tests.rs index 6ccdaab64a..0255e3689c 100644 --- a/wallet/src/signer/trezor_signer/tests.rs +++ b/wallet/src/signer/trezor_signer/tests.rs @@ -18,24 +18,24 @@ use std::sync::{Arc, Mutex}; use rstest::rstest; use serial_test::serial; -use ::test_utils::random::{make_seedable_rng, Seed}; +use ::test_utils::random::{Seed, make_seedable_rng}; use common::chain::{ChainConfig, SighashInputCommitmentVersion}; -use crypto::key::{hdkd::u31::U31, PredefinedSigAuxDataProvider}; +use crypto::key::{PredefinedSigAuxDataProvider, hdkd::u31::U31}; use logging::log; use crate::signer::{ tests::{ generic_fixed_signature_tests::{ - test_fixed_signatures_generic, test_fixed_signatures_generic2, - test_fixed_signatures_generic_htlc_refunding, test_fixed_signatures_generic_no_legacy, + test_fixed_signatures_generic, test_fixed_signatures_generic_htlc_refunding, + test_fixed_signatures_generic_no_legacy, test_fixed_signatures_generic2, }, generic_tests::{ - sign_message_test_params, test_sign_message_generic, test_sign_transaction_generic, - test_sign_transaction_intent_generic, MessageToSign, + MessageToSign, sign_message_test_params, test_sign_message_generic, + test_sign_transaction_generic, test_sign_transaction_intent_generic, }, make_deterministic_software_signer, no_another_signer, }, - trezor_signer::{test_utils::find_test_device_and_connect, TrezorSigner}, + trezor_signer::{TrezorSigner, test_utils::find_test_device_and_connect}, }; use super::test_utils::maybe_spawn_auto_confirmer; @@ -121,7 +121,9 @@ async fn test_sign_transaction( #[case] seed: Seed, #[case] input_commitments_version: SighashInputCommitmentVersion, ) { - log::debug!("test_sign_transaction, seed = {seed:?}, input_commitments_version = {input_commitments_version:?}"); + log::debug!( + "test_sign_transaction, seed = {seed:?}, input_commitments_version = {input_commitments_version:?}" + ); let _join_guard = maybe_spawn_auto_confirmer(); @@ -164,7 +166,9 @@ async fn test_fixed_signatures2( #[case] seed: Seed, #[case] input_commitments_version: SighashInputCommitmentVersion, ) { - log::debug!("test_fixed_signatures2, seed = {seed:?}, input_commitments_version = {input_commitments_version:?}"); + log::debug!( + "test_fixed_signatures2, seed = {seed:?}, input_commitments_version = {input_commitments_version:?}" + ); let _join_guard = maybe_spawn_auto_confirmer(); @@ -200,7 +204,9 @@ async fn test_fixed_signatures_htlc_refunding( #[case] seed: Seed, #[case] input_commitments_version: SighashInputCommitmentVersion, ) { - log::debug!("test_fixed_signatures_htlc_refunding, seed = {seed:?}, input_commitments_version = {input_commitments_version:?}"); + log::debug!( + "test_fixed_signatures_htlc_refunding, seed = {seed:?}, input_commitments_version = {input_commitments_version:?}" + ); let _join_guard = maybe_spawn_auto_confirmer(); @@ -267,7 +273,9 @@ async fn test_sign_transaction_sig_consistency( #[case] seed: Seed, #[case] input_commitments_version: SighashInputCommitmentVersion, ) { - log::debug!("test_sign_transaction_sig_consistency, seed = {seed:?}, input_commitments_version = {input_commitments_version:?}"); + log::debug!( + "test_sign_transaction_sig_consistency, seed = {seed:?}, input_commitments_version = {input_commitments_version:?}" + ); let _join_guard = maybe_spawn_auto_confirmer(); diff --git a/wallet/src/signer/utils.rs b/wallet/src/signer/utils.rs index 40c25d32c0..d093e31f8a 100644 --- a/wallet/src/signer/utils.rs +++ b/wallet/src/signer/utils.rs @@ -14,19 +14,19 @@ // limitations under the License. use common::chain::{ + Destination, Transaction, TxOutput, htlc::HtlcSecret, signature::{ inputsig::{ + InputWitness, htlc::{ produce_uniparty_signature_for_htlc_refunding, produce_uniparty_signature_for_htlc_spending, }, standard_signature::StandardInputSignature, - InputWitness, }, sighash::{input_commitments::SighashInputCommitment, sighashtype::SigHashType}, }, - Destination, Transaction, TxOutput, }; use crypto::key::{PrivateKey, SigAuxDataProvider}; use utils::debug_assert_or_log; diff --git a/wallet/src/wallet/mod.rs b/wallet/src/wallet/mod.rs index 6187c1e18e..fc6b5af712 100644 --- a/wallet/src/wallet/mod.rs +++ b/wallet/src/wallet/mod.rs @@ -20,40 +20,40 @@ use std::{ }; use common::{ - address::{pubkeyhash::PublicKeyHash, Address, AddressError, RpcAddress}, + address::{Address, AddressError, RpcAddress, pubkeyhash::PublicKeyHash}, chain::{ + AccountCommand, AccountOutPoint, Block, ChainConfig, Currency, DelegationId, Destination, + GenBlock, IdCreationError, OrderAccountCommand, OrderId, OutPointSourceId, PoolId, + RpcOrderInfo, SignedTransaction, SignedTransactionIntent, Transaction, + TransactionCreationError, TxInput, TxOutput, TxOutputTag, UtxoOutPoint, block::timestamp::BlockTimestamp, classic_multisig::ClassicMultisigChallenge, htlc::{HashedTimelockContract, HtlcSecret, HtlcSecretHash}, make_delegation_id, make_order_id, make_token_id, output_value::OutputValue, signature::{ - inputsig::arbitrary_message::{ArbitraryMessageSignature, SignArbitraryMessageError}, DestinationSigError, + inputsig::arbitrary_message::{ArbitraryMessageSignature, SignArbitraryMessageError}, }, tokens::{IsTokenUnfreezable, Metadata, RPCFungibleTokenInfo, TokenId, TokenIssuance}, - AccountCommand, AccountOutPoint, Block, ChainConfig, Currency, DelegationId, Destination, - GenBlock, IdCreationError, OrderAccountCommand, OrderId, OutPointSourceId, PoolId, - RpcOrderInfo, SignedTransaction, SignedTransactionIntent, Transaction, - TransactionCreationError, TxInput, TxOutput, TxOutputTag, UtxoOutPoint, }, primitives::{ - id::{hash_encoded, WithId}, - Amount, BlockHeight, Id, H256, + Amount, BlockHeight, H256, Id, + id::{WithId, hash_encoded}, }, size_estimation::SizeEstimationError, }; use consensus::PoSGenerateBlockInputData; use crypto::{ key::{ + PrivateKey, PublicKey, extended::ExtendedPublicKey, hdkd::{child_number::ChildNumber, derivable::Derivable, u31::U31}, - PrivateKey, PublicKey, }, vrf::VRFPublicKey, }; use mempool::FeeRate; -use tx_verifier::{check_transaction, error::TokenIssuanceError, CheckTransactionError}; +use tx_verifier::{CheckTransactionError, check_transaction, error::TokenIssuanceError}; use utils::{debug_panic_or_log, ensure}; use wallet_storage::{ DefaultBackend, Store, StoreTxRo, StoreTxRw, StoreTxRwUnlocked, TransactionRoLocked, @@ -61,6 +61,7 @@ use wallet_storage::{ WalletStorageReadUnlocked, WalletStorageWriteLocked, WalletStorageWriteUnlocked, }; use wallet_types::{ + AccountId, AccountKeyPurposeId, BlockInfo, KeyPurpose, KeychainUsageState, SignedTxWithFees, account_info::{StandaloneAddressDetails, StandaloneAddresses}, chain_info::ChainInfo, hw_data::HardwareWalletFullInfo, @@ -74,28 +75,27 @@ use wallet_types::{ wallet_tx::{TxData, TxState}, wallet_type::{WalletControllerMode, WalletType}, with_locked::WithLocked, - AccountId, AccountKeyPurposeId, BlockInfo, KeyPurpose, KeychainUsageState, SignedTxWithFees, }; #[cfg(feature = "trezor")] use crate::signer::trezor_signer::{FoundDevice, TrezorError}; use crate::{ + Account, SendRequest, account::{ - transaction_list::TransactionList, CoinSelectionAlgo, CurrentFeeRate, DelegationData, - OrderData, OutputCacheInconsistencyError, PoolData, TxInfo, UnconfirmedTokenInfo, - UtxoSelectorError, + CoinSelectionAlgo, CurrentFeeRate, DelegationData, OrderData, + OutputCacheInconsistencyError, PoolData, TxInfo, UnconfirmedTokenInfo, UtxoSelectorError, + transaction_list::TransactionList, }, destination_getters::HtlcSpendingCondition, key_chain::{ - make_account_path, make_path_to_vrf_key, AccountKeyChainImplSoftware, KeyChainError, - MasterKeyChain, LOOKAHEAD_SIZE, VRF_INDEX, + AccountKeyChainImplSoftware, KeyChainError, LOOKAHEAD_SIZE, MasterKeyChain, VRF_INDEX, + make_account_path, make_path_to_vrf_key, }, send_request::{ - make_issue_token_outputs, IssueNftArguments, SelectedInputs, StakePoolCreationArguments, + IssueNftArguments, SelectedInputs, StakePoolCreationArguments, make_issue_token_outputs, }, signer::{Signer, SignerError, SignerProvider}, wallet_events::{WalletEvents, WalletEventsNoOp}, - Account, SendRequest, }; pub use bip39::{Language, Mnemonic}; @@ -122,7 +122,9 @@ pub enum WalletError { HardwareWalletOpenedAsSoftwareWallet(WalletType), #[error("The wallet belongs to a different chain than the one specified")] DifferentChainType, - #[error("Unsupported wallet version: {0}, max supported version of this software is {CURRENT_WALLET_VERSION}")] + #[error( + "Unsupported wallet version: {0}, max supported version of this software is {CURRENT_WALLET_VERSION}" + )] UnsupportedWalletVersion(u32), #[error("Wallet database error: {0}")] DatabaseError(#[from] wallet_storage::Error), @@ -242,11 +244,15 @@ pub enum WalletError { ReducedLookaheadSize(u32, u32), #[error("Wallet file {0} error: {1}")] WalletFileError(PathBuf, String), - #[error("Failed to completely sign the decommission transaction. \ + #[error( + "Failed to completely sign the decommission transaction. \ This wallet does not seem to have the decommission key. \ - Consider using a decommission-request, and passing it to the wallet that has the decommission key")] + Consider using a decommission-request, and passing it to the wallet that has the decommission key" + )] PartiallySignedTransactionInDecommissionCommand, - #[error("Failed to create decommission request as all the signatures are present. Use staking-decommission-pool command.")] + #[error( + "Failed to create decommission request as all the signatures are present. Use staking-decommission-pool command." + )] FullySignedTransactionInDecommissionReq, #[error("Destination does not belong to this wallet")] DestinationNotFromThisWallet, @@ -299,7 +305,9 @@ pub enum WalletError { #[error("HTLC secret provided for non-HTLC UTXO")] HtlcSecretProvidedForNonHtlcUtxo, - #[error("The provided HTLC secret doesn't match the hash (expected: {expected:x}, actual: {actual:x})")] + #[error( + "The provided HTLC secret doesn't match the hash (expected: {expected:x}, actual: {actual:x})" + )] HtlcSecretDoesntMatchHash { expected: HtlcSecretHash, actual: HtlcSecretHash, @@ -672,7 +680,7 @@ where } CURRENT_WALLET_VERSION => return Ok(signer_provider), unsupported_version => { - return Err(WalletError::UnsupportedWalletVersion(unsupported_version)) + return Err(WalletError::UnsupportedWalletVersion(unsupported_version)); } } } @@ -735,14 +743,14 @@ where return Err(WalletError::CannotChangeWalletType { from: current_wallet_type, to: wallet_type, - }) + }); } #[cfg(all(feature = "trezor", feature = "ledger"))] (WalletType::Ledger, WalletType::Trezor) | (WalletType::Trezor, WalletType::Ledger) => { return Err(WalletError::CannotChangeWalletType { from: current_wallet_type, to: wallet_type, - }) + }); } #[cfg(feature = "ledger")] (WalletType::Cold | WalletType::Hot, WalletType::Ledger) @@ -750,7 +758,7 @@ where return Err(WalletError::CannotChangeWalletType { from: current_wallet_type, to: wallet_type, - }) + }); } (WalletType::Cold, WalletType::Cold) => {} (WalletType::Hot, WalletType::Hot) => {} @@ -1183,13 +1191,13 @@ where account_index: U31, create_request: impl FnOnce(&mut Account, &mut StoreTxRwUnlocked) -> R, sign_request: impl AsyncFnOnce( - R, - &P::K, - &mut StoreTxRwUnlocked, - Arc, -

::S, - ) -> WalletResult - + Send, + R, + &P::K, + &mut StoreTxRwUnlocked, + Arc, +

::S, + ) -> WalletResult + + Send, ) -> WalletResult { let account = Self::get_account_mut(&mut self.accounts, account_index)?; let mut db_tx = self.db.transaction_rw_unlocked(None)?; @@ -1220,12 +1228,12 @@ where &mut self, account_index: U31, f: impl AsyncFnOnce( - &P::K, - &mut StoreTxRwUnlocked, - Arc, -

::S, - ) -> WalletResult - + Send, + &P::K, + &mut StoreTxRwUnlocked, + Arc, +

::S, + ) -> WalletResult + + Send, ) -> WalletResult { self.async_for_account_rw_unlocked( account_index, diff --git a/wallet/src/wallet/test_helpers.rs b/wallet/src/wallet/test_helpers.rs index dc3b90cf59..16aeb99db6 100644 --- a/wallet/src/wallet/test_helpers.rs +++ b/wallet/src/wallet/test_helpers.rs @@ -28,10 +28,10 @@ use wallet_storage::{DefaultBackend, Store}; use wallet_types::{seed_phrase::StoreSeedPhrase, wallet_type::WalletType}; use crate::{ - signer::{software_signer::SoftwareSignerProvider, SignerProvider}, + DefaultWallet, Wallet, + signer::{SignerProvider, software_signer::SoftwareSignerProvider}, wallet::create_wallet_in_memory, wallet_events::WalletEventsNoOp, - DefaultWallet, Wallet, }; pub async fn create_wallet_with_mnemonic( diff --git a/wallet/src/wallet/tests.rs b/wallet/src/wallet/tests.rs index 3bb902e9bd..fbb216aed6 100644 --- a/wallet/src/wallet/tests.rs +++ b/wallet/src/wallet/tests.rs @@ -24,36 +24,37 @@ use rstest::rstest; use common::{ address::pubkeyhash::PublicKeyHash, chain::{ - block::{consensus_data::PoSData, timestamp::BlockTimestamp, BlockReward, ConsensusData}, - config::{create_mainnet, create_regtest, create_unit_test_config, Builder, ChainType}, + AccountNonce, AccountSpending, ChainstateUpgradeBuilder, Currency, Destination, Genesis, + OutPointSourceId, TxInput, + block::{BlockReward, ConsensusData, consensus_data::PoSData, timestamp::BlockTimestamp}, + config::{Builder, ChainType, create_mainnet, create_regtest, create_unit_test_config}, output_value::{OutputValue, RpcOutputValue}, signature::inputsig::InputWitness, stakelock::StakePoolData, timelock::OutputTimeLock, tokens::{RPCIsTokenFrozen, TokenData, TokenIssuanceV0, TokenIssuanceV1}, - AccountNonce, AccountSpending, ChainstateUpgradeBuilder, Currency, Destination, Genesis, - OutPointSourceId, TxInput, }, - primitives::{per_thousand::PerThousand, Idable, H256}, + primitives::{H256, Idable, per_thousand::PerThousand}, }; use crypto::{ key::{ - hdkd::{child_number::ChildNumber, derivable::Derivable, derivation_path::DerivationPath}, KeyKind, + hdkd::{child_number::ChildNumber, derivable::Derivable, derivation_path::DerivationPath}, }, vrf::transcript::no_rng::VRFTranscript, }; use randomness::{CryptoRng, Rng, RngExt as _, SliceRandom}; -use serialization::{extras::non_empty_vec::DataOrNoVec, hex::HexEncode, Encode}; +use serialization::{Encode, extras::non_empty_vec::DataOrNoVec, hex::HexEncode}; use storage::raw::DbMapId; use test_utils::{ assert_matches, assert_matches_return_val, - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, random_ascii_alphanumeric_string, token_utils::random_token_issuance_v1_with_min_supply, }; -use wallet_storage::{schema, WalletStorageEncryptionRead}; +use wallet_storage::{WalletStorageEncryptionRead, schema}; use wallet_types::{ + AccountWalletTxId, WalletTx, account_info::DEFAULT_ACCOUNT_INDEX, partially_signed_transaction::{ OrderAdditionalInfo, PartiallySignedTransaction, PartiallySignedTransactionError, @@ -61,11 +62,11 @@ use wallet_types::{ }, seed_phrase::{PassPhrase, StoreSeedPhrase}, utxo_types::{UtxoState, UtxoType}, - AccountWalletTxId, WalletTx, }; use crate::{ - key_chain::{make_account_path, LOOKAHEAD_SIZE}, + DefaultWallet, + key_chain::{LOOKAHEAD_SIZE, make_account_path}, send_request::{make_address_output, make_create_delegation_output}, signer::software_signer::SoftwareSignerProvider, wallet::test_helpers::{ @@ -73,7 +74,6 @@ use crate::{ create_wallet_with_mnemonic_and_named_db, scan_wallet, }, wallet_events::WalletEventsNoOp, - DefaultWallet, }; use super::*; @@ -83,8 +83,7 @@ use super::*; const MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; -const MNEMONIC2: &str = - "disease woman cave illness sample crew swamp robust crumble infant news sign liquid rigid alter"; +const MNEMONIC2: &str = "disease woman cave illness sample crew swamp robust crumble infant news sign liquid rigid alter"; const NETWORK_FEE: u128 = 10000; @@ -1415,13 +1414,15 @@ async fn locked_wallet_cant_sign_transaction(#[case] seed: Seed) { ); // check that the kdf challenge has been deleted - assert!(wallet - .db - .transaction_ro() - .unwrap() - .get_encryption_key_kdf_challenge() - .unwrap() - .is_none()); + assert!( + wallet + .db + .transaction_ro() + .unwrap() + .get_encryption_key_kdf_challenge() + .unwrap() + .is_none() + ); wallet .create_transaction_to_addresses( @@ -1734,7 +1735,7 @@ async fn wallet_list_mainchain_transactions(#[case] seed: Seed) { #[case(Seed::from_entropy())] #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn wallet_transactions_with_fees(#[case] seed: Seed) { - use crate::destination_getters::{get_tx_output_destination, HtlcSpendingCondition}; + use crate::destination_getters::{HtlcSpendingCondition, get_tx_output_destination}; let mut rng = make_seedable_rng(seed); let chain_config = Arc::new(create_mainnet()); diff --git a/wallet/storage/src/internal/mod.rs b/wallet/storage/src/internal/mod.rs index ab1f7894fc..a232acabee 100644 --- a/wallet/storage/src/internal/mod.rs +++ b/wallet/storage/src/internal/mod.rs @@ -16,8 +16,8 @@ use storage::raw; use crate::{ - schema::Schema, TransactionRwUnlocked, Transactional, WalletStorageEncryptionRead, - WalletStorageEncryptionWrite, + TransactionRwUnlocked, Transactional, WalletStorageEncryptionRead, + WalletStorageEncryptionWrite, schema::Schema, }; mod password; diff --git a/wallet/storage/src/internal/password.rs b/wallet/storage/src/internal/password.rs index e990439361..f0a5360386 100644 --- a/wallet/storage/src/internal/password.rs +++ b/wallet/storage/src/internal/password.rs @@ -15,10 +15,10 @@ use crypto::{ kdf::{ - argon2::Argon2Config, hash_from_challenge, hash_password, KdfChallenge, KdfConfig, - KdfResult, + KdfChallenge, KdfConfig, KdfResult, argon2::Argon2Config, hash_from_challenge, + hash_password, }, - symkey::{key_size, SymmetricKey, SymmetricKeyKind}, + symkey::{SymmetricKey, SymmetricKeyKind, key_size}, }; use randomness::make_true_rng; use utils::const_nz_usize; @@ -105,7 +105,7 @@ pub fn challenge_to_sym_key( mod test { use randomness::RngExt; use rstest::rstest; - use test_utils::random::{make_seedable_rng, Seed}; + use test_utils::random::{Seed, make_seedable_rng}; use super::{challenge_to_sym_key, password_to_sym_key}; diff --git a/wallet/storage/src/internal/store_tx.rs b/wallet/storage/src/internal/store_tx.rs index 8665f3428e..9001193be5 100644 --- a/wallet/storage/src/internal/store_tx.rs +++ b/wallet/storage/src/internal/store_tx.rs @@ -16,26 +16,28 @@ use std::collections::BTreeMap; use crate::{ - schema::{self as db, Schema}, WalletStorageEncryptionRead, WalletStorageEncryptionWrite, WalletStorageReadLocked, WalletStorageReadUnlocked, WalletStorageWriteLocked, WalletStorageWriteUnlocked, + schema::{self as db, Schema}, }; use common::{ address::Address, - chain::{block::timestamp::BlockTimestamp, Destination, SignedTransaction}, + chain::{Destination, SignedTransaction, block::timestamp::BlockTimestamp}, }; use crypto::{ kdf::KdfChallenge, - key::{extended::ExtendedPublicKey, PrivateKey}, + key::{PrivateKey, extended::ExtendedPublicKey}, symkey::SymmetricKey, }; use serialization::{Codec, DecodeAll, Encode, EncodeLike}; -use storage::{schema, MakeMapRef}; +use storage::{MakeMapRef, schema}; use utils::{ ensure, maybe_encrypted::{MaybeEncrypted, MaybeEncryptedError}, }; use wallet_types::{ + AccountDerivationPathId, AccountId, AccountInfo, AccountKeyPurposeId, AccountWalletCreatedTxId, + AccountWalletTxId, KeychainUsageState, WalletTx, account_id::{AccountAddress, AccountPublicKey}, account_info::{ AccountVrfKeys, StandaloneMultisig, StandalonePrivateKey, StandaloneWatchOnlyKey, @@ -44,8 +46,6 @@ use wallet_types::{ keys::{RootKeyConstant, RootKeys}, seed_phrase::{SeedPhraseConstant, SerializableSeedPhrase}, wallet_type::WalletType, - AccountDerivationPathId, AccountId, AccountInfo, AccountKeyPurposeId, AccountWalletCreatedTxId, - AccountWalletTxId, KeychainUsageState, WalletTx, }; use wallet_types::hw_data; diff --git a/wallet/storage/src/internal/test.rs b/wallet/storage/src/internal/test.rs index af2ef5e01a..a1681028d1 100644 --- a/wallet/storage/src/internal/test.rs +++ b/wallet/storage/src/internal/test.rs @@ -23,7 +23,7 @@ use crypto::key::extended::{ExtendedKeyKind, ExtendedPrivateKey}; use crypto::vrf::ExtendedVRFPrivateKey; use randomness::{CryptoRng, RngExt as _}; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use wallet_types::keys::RootKeys; fn gen_random_password(rng: &mut impl CryptoRng) -> String { diff --git a/wallet/storage/src/lib.rs b/wallet/storage/src/lib.rs index d09745f7d1..a99ad38f24 100644 --- a/wallet/storage/src/lib.rs +++ b/wallet/storage/src/lib.rs @@ -21,17 +21,19 @@ pub mod schema; use common::{ address::{Address, AddressError}, - chain::{block::timestamp::BlockTimestamp, Destination, SignedTransaction}, + chain::{Destination, SignedTransaction, block::timestamp::BlockTimestamp}, }; use crypto::{ kdf::KdfChallenge, - key::{extended::ExtendedPublicKey, PrivateKey}, + key::{PrivateKey, extended::ExtendedPublicKey}, symkey::SymmetricKey, }; pub use internal::{Store, StoreTxRo, StoreTxRoUnlocked, StoreTxRw, StoreTxRwUnlocked}; use std::collections::BTreeMap; use wallet_types::{ + AccountDerivationPathId, AccountId, AccountInfo, AccountKeyPurposeId, AccountWalletCreatedTxId, + AccountWalletTxId, KeychainUsageState, WalletTx, account_id::{AccountAddress, AccountPublicKey}, account_info::{AccountVrfKeys, StandaloneMultisig, StandaloneWatchOnlyKey}, chain_info::ChainInfo, @@ -39,8 +41,6 @@ use wallet_types::{ keys::RootKeys, seed_phrase::SerializableSeedPhrase, wallet_type::WalletType, - AccountDerivationPathId, AccountId, AccountInfo, AccountKeyPurposeId, AccountWalletCreatedTxId, - AccountWalletTxId, KeychainUsageState, WalletTx, }; /// Wallet Errors @@ -83,7 +83,7 @@ pub trait WalletStorageReadLocked { fn get_user_transactions(&self) -> Result>; fn get_account_unconfirmed_tx_counter(&self, account_id: &AccountId) -> Result>; fn get_account_vrf_public_keys(&self, account_id: &AccountId) - -> Result>; + -> Result>; fn get_account_standalone_watch_only_keys( &self, account_id: &AccountId, diff --git a/wallet/storage/src/schema.rs b/wallet/storage/src/schema.rs index 4043c36d1b..f46bb369d1 100644 --- a/wallet/storage/src/schema.rs +++ b/wallet/storage/src/schema.rs @@ -19,14 +19,14 @@ use common::chain::SignedTransaction; use crypto::key::extended::ExtendedPublicKey; use utils::maybe_encrypted::MaybeEncrypted; use wallet_types::{ + AccountDerivationPathId, AccountId, AccountInfo, AccountKeyPurposeId, AccountWalletCreatedTxId, + AccountWalletTxId, KeychainUsageState, WalletTx, account_id::{AccountAddress, AccountPublicKey}, account_info::{ AccountVrfKeys, StandaloneMultisig, StandalonePrivateKey, StandaloneWatchOnlyKey, }, keys::{RootKeyConstant, RootKeys}, seed_phrase::{SeedPhraseConstant, SerializableSeedPhrase}, - AccountDerivationPathId, AccountId, AccountInfo, AccountKeyPurposeId, AccountWalletCreatedTxId, - AccountWalletTxId, KeychainUsageState, WalletTx, }; storage::decl_schema! { diff --git a/wallet/types/src/account_id.rs b/wallet/types/src/account_id.rs index 1414aba5ad..9b5e5470dd 100644 --- a/wallet/types/src/account_id.rs +++ b/wallet/types/src/account_id.rs @@ -20,7 +20,7 @@ use common::{ primitives::Id, }; use crypto::key::hdkd::derivation_path::DerivationPath; -use crypto::key::{extended::ExtendedPublicKey, PublicKey}; +use crypto::key::{PublicKey, extended::ExtendedPublicKey}; use serialization::{Decode, Encode}; use storage::HasPrefix; diff --git a/wallet/types/src/account_info.rs b/wallet/types/src/account_info.rs index da3440b3a8..bcaa678768 100644 --- a/wallet/types/src/account_info.rs +++ b/wallet/types/src/account_info.rs @@ -14,11 +14,11 @@ // limitations under the License. use common::{ - chain::{classic_multisig::ClassicMultisigChallenge, ChainConfig, Destination, GenBlock}, + chain::{ChainConfig, Destination, GenBlock, classic_multisig::ClassicMultisigChallenge}, primitives::{BlockHeight, Id}, }; use crypto::{ - key::{extended::ExtendedPublicKey, hdkd::u31::U31, PrivateKey, PublicKey}, + key::{PrivateKey, PublicKey, extended::ExtendedPublicKey, hdkd::u31::U31}, vrf::ExtendedVRFPublicKey, }; use serialization::{Decode, Encode}; diff --git a/wallet/types/src/chain_info.rs b/wallet/types/src/chain_info.rs index f0d769b2e9..25f3863ec0 100644 --- a/wallet/types/src/chain_info.rs +++ b/wallet/types/src/chain_info.rs @@ -14,7 +14,7 @@ // limitations under the License. use common::{ - chain::{config::MagicBytes, ChainConfig, GenBlock}, + chain::{ChainConfig, GenBlock, config::MagicBytes}, primitives::Id, }; use serialization::{Decode, Encode}; diff --git a/wallet/types/src/generic_transaction.rs b/wallet/types/src/generic_transaction.rs index 7d0cbb8a7e..013fb41473 100644 --- a/wallet/types/src/generic_transaction.rs +++ b/wallet/types/src/generic_transaction.rs @@ -14,7 +14,7 @@ // limitations under the License. use common::chain::{ - partially_signed_transaction::PartiallySignedTransaction, SignedTransaction, Transaction, + SignedTransaction, Transaction, partially_signed_transaction::PartiallySignedTransaction, }; use serialization::DecodeAll as _; @@ -58,17 +58,17 @@ mod tests { use common::{ chain::{ + OutPointSourceId, TxInput, TxOutput, UtxoOutPoint, output_value::OutputValue, partially_signed_transaction::{ PartiallySignedTransactionConsistencyCheck, TxAdditionalInfo, }, signature::inputsig::InputWitness, - OutPointSourceId, TxInput, TxOutput, UtxoOutPoint, }, primitives::{Amount, Id}, }; use serialization::Encode; - use test_utils::random::{gen_random_bytes, make_seedable_rng, RngExt as _, Seed}; + use test_utils::random::{RngExt as _, Seed, gen_random_bytes, make_seedable_rng}; use super::*; diff --git a/wallet/types/src/partially_signed_transaction.rs b/wallet/types/src/partially_signed_transaction.rs index 43962d2675..b355b6877d 100644 --- a/wallet/types/src/partially_signed_transaction.rs +++ b/wallet/types/src/partially_signed_transaction.rs @@ -16,15 +16,15 @@ use std::collections::BTreeMap; use common::chain::{ - htlc::HtlcSecret, partially_signed_transaction::PartiallySignedTransactionConsistencyCheck, - signature::inputsig::InputWitness, tokens::TokenId, Destination, OrderId, PoolId, Transaction, - TxOutput, + Destination, OrderId, PoolId, Transaction, TxOutput, htlc::HtlcSecret, + partially_signed_transaction::PartiallySignedTransactionConsistencyCheck, + signature::inputsig::InputWitness, tokens::TokenId, }; pub use common::chain::partially_signed_transaction::{ - make_sighash_input_commitments, OrderAdditionalInfo, PartiallySignedTransaction, - PartiallySignedTransactionError, PoolAdditionalInfo, SighashInputCommitmentCreationError, - TxAdditionalInfo as PtxAdditionalInfo, + OrderAdditionalInfo, PartiallySignedTransaction, PartiallySignedTransactionError, + PoolAdditionalInfo, SighashInputCommitmentCreationError, TxAdditionalInfo as PtxAdditionalInfo, + make_sighash_input_commitments, }; pub trait PartiallySignedTransactionWalletExt { diff --git a/wallet/types/src/wallet_tx.rs b/wallet/types/src/wallet_tx.rs index 8f068cfb3c..938ae74480 100644 --- a/wallet/types/src/wallet_tx.rs +++ b/wallet/types/src/wallet_tx.rs @@ -15,8 +15,8 @@ use std::fmt::Display; -use common::chain::block::timestamp::BlockTimestamp; use common::chain::block::ConsensusData; +use common::chain::block::timestamp::BlockTimestamp; use serialization::{Decode, Encode}; use common::chain::{ diff --git a/wallet/wallet-address-generator-lib/src/lib.rs b/wallet/wallet-address-generator-lib/src/lib.rs index 4d6262379b..0857a6f66f 100644 --- a/wallet/wallet-address-generator-lib/src/lib.rs +++ b/wallet/wallet-address-generator-lib/src/lib.rs @@ -15,19 +15,19 @@ use clap::{Parser, ValueEnum}; -use common::address::pubkeyhash::PublicKeyHash; use common::address::Address; +use common::address::pubkeyhash::PublicKeyHash; use common::chain::config::{Builder, ChainType}; use common::chain::{ChainConfig, Destination}; use crypto::key::extended::{ExtendedPrivateKey, ExtendedPublicKey}; use crypto::key::hdkd::u31::U31; use crypto::key::hdkd::{child_number::ChildNumber, derivable::Derivable}; use utils::{app_version_with_git_info, clap_utils, ensure}; -use wallet::key_chain::LOOKAHEAD_SIZE; use wallet::WalletError; +use wallet::key_chain::LOOKAHEAD_SIZE; use wallet::{ - key_chain::{make_account_path, KeyChainError, MasterKeyChain}, WalletResult, + key_chain::{KeyChainError, MasterKeyChain, make_account_path}, }; use wallet_types::KeyPurpose; diff --git a/wallet/wallet-cli-commands/src/command_handler/mod.rs b/wallet/wallet-cli-commands/src/command_handler/mod.rs index e70eabc915..2e1506e690 100644 --- a/wallet/wallet-cli-commands/src/command_handler/mod.rs +++ b/wallet/wallet-cli-commands/src/command_handler/mod.rs @@ -24,10 +24,11 @@ use chainstate::rpc::RpcOutputValueOut; use common::{ address::{Address, RpcAddress}, chain::{ + ChainConfig, Destination, RpcCurrency, SignedTransaction, config::checkpoints_data::print_block_heights_ids_as_checkpoints_data, htlc::HtlcSecret, - tokens::TokenId, ChainConfig, Destination, RpcCurrency, SignedTransaction, + tokens::TokenId, }, - primitives::{Idable as _, H256}, + primitives::{H256, Idable as _}, text_summary::TextSummary, }; use crypto::key::hdkd::u31::U31; @@ -57,21 +58,21 @@ use wallet_types::partially_signed_transaction::PartiallySignedTransaction; use crate::{CreateWalletDeviceSelectMenu, OpenWalletDeviceSelectMenu}; use crate::{ + ManageableWalletCommand, OpenWalletSubCommand, WalletManagementCommand, errors::WalletCliCommandError, helper_types::{ - active_order_infos_header, format_token_name, token_ticker_from_rpc_token_info, CliCurrency, + CliCurrency, active_order_infos_header, format_token_name, token_ticker_from_rpc_token_info, }, - ManageableWalletCommand, OpenWalletSubCommand, WalletManagementCommand, }; use self::local_state::WalletWithState; use super::{ + ColdWalletCommand, ConsoleCommand, WalletCommand, helper_types::{ - format_active_order_info, format_delegation_info, format_own_order_info, format_pool_info, - CliForceReduceLookaheadSize, CliUtxoState, + CliForceReduceLookaheadSize, CliUtxoState, format_active_order_info, + format_delegation_info, format_own_order_info, format_pool_info, }, - ColdWalletCommand, ConsoleCommand, WalletCommand, }; pub struct CommandHandler { @@ -477,7 +478,10 @@ where } else { String::new() }; - format!("The seed phrase has been deleted, you can store it if you haven't done so yet: \"{}\"{passphrase}", phrase.seed_phrase.join(" ")) + format!( + "The seed phrase has been deleted, you can store it if you haven't done so yet: \"{}\"{passphrase}", + phrase.seed_phrase.join(" ") + ) } else { "No stored seed phrase for this wallet.".into() }; @@ -743,7 +747,8 @@ where "The transaction has been fully signed and is ready to be broadcast to network. \ You can use the command `node-submit-transaction` in a wallet connected to the internet (this one or elsewhere). \ Pass the following data to the wallet to broadcast:\n\n{result_hex}\ - {qr_code_string}\n\n{summary}") + {qr_code_string}\n\n{summary}" + ) } PartialOrSignedTx::Partial(partially_signed_tx) => { let result_hex: HexEncoded = @@ -794,7 +799,9 @@ where String::new() } else { let qr_code = qrcode_or_error_string(&result); - format!("\n\nThe following qr code also contains the signature for easy transport:\n{qr_code}") + format!( + "\n\nThe following qr code also contains the signature for easy transport:\n{qr_code}" + ) }; Ok(ConsoleCommand::Print(format!( @@ -813,7 +820,9 @@ where String::new() } else { let qr_code = qrcode_or_error_string(&result); - format!("\n\nThe following qr code also contains the signature for easy transport:\n{qr_code}") + format!( + "\n\nThe following qr code also contains the signature for easy transport:\n{qr_code}" + ) }; Ok(ConsoleCommand::Print(format!( @@ -1066,9 +1075,13 @@ where .await?; let output = if no_rescan { - format!("Success. The following new multisig address has been added to the account\n{multisig_address}") + format!( + "Success. The following new multisig address has been added to the account\n{multisig_address}" + ) } else { - format!("Success. The following new multisig address has been added to the account\n{multisig_address}\nRescanning the blockchain to detect balance in added new addresses") + format!( + "Success. The following new multisig address has been added to the account\n{multisig_address}\nRescanning the blockchain to detect balance in added new addresses" + ) }; Ok(ConsoleCommand::SetStatus { @@ -2437,8 +2450,12 @@ fn format_signature_status((idx, status): (usize, &RpcSignatureStatus)) -> Strin RpcSignatureStatus::NotSigned => "NotSigned".to_owned(), RpcSignatureStatus::InvalidSignature => "InvalidSignature".to_owned(), RpcSignatureStatus::UnknownSignature => "UnknownSignature".to_owned(), - RpcSignatureStatus::PartialMultisig { required_signatures, num_signatures } => - format!("PartialMultisig having {num_signatures} out of {required_signatures} required signatures"), + RpcSignatureStatus::PartialMultisig { + required_signatures, + num_signatures, + } => format!( + "PartialMultisig having {num_signatures} out of {required_signatures} required signatures" + ), }; format!("Signature for input {idx}: {status}") diff --git a/wallet/wallet-cli-commands/src/helper_types.rs b/wallet/wallet-cli-commands/src/helper_types.rs index 0101f9b62f..a505633278 100644 --- a/wallet/wallet-cli-commands/src/helper_types.rs +++ b/wallet/wallet-cli-commands/src/helper_types.rs @@ -21,19 +21,19 @@ use itertools::Itertools; use chainstate::rpc::RpcOutputValueOut; use common::{ - address::{decode_address, Address, AddressError, RpcAddress}, + address::{Address, AddressError, RpcAddress, decode_address}, chain::{ + ChainConfig, Currency, Destination, OrderId, OutPointSourceId, TxOutput, UtxoOutPoint, block::timestamp::BlockTimestamp, timelock::OutputTimeLock, tokens::{RPCTokenInfo, TokenId}, - ChainConfig, Currency, Destination, OrderId, OutPointSourceId, TxOutput, UtxoOutPoint, }, primitives::{ + BlockHeight, DecimalAmount, H256, Id, amount::decimal::{ - subtract_decimal_amounts_of_same_currency, DecimalAmountWithIsSameComparison, + DecimalAmountWithIsSameComparison, subtract_decimal_amounts_of_same_currency, }, time::Time, - BlockHeight, DecimalAmount, Id, H256, }, }; use utils::ensure; @@ -121,8 +121,14 @@ pub fn format_pool_info(info: PoolInfo) -> String { "Pool Id: {}, Pledge: {}, Balance: {}, Creation Block Height: {}, Creation block timestamp: {}, ", "Staker: {}, Decommission Key: {}, VRF Public Key: {}" ), - info.pool_id, info.pledge.decimal(), info.balance.decimal(), info.height, info.block_timestamp, - info.staker, info.decommission_key, info.vrf_public_key + info.pool_id, + info.pledge.decimal(), + info.balance.decimal(), + info.height, + info.block_timestamp, + info.staker, + info.decommission_key, + info.vrf_public_key ) } @@ -826,12 +832,12 @@ mod tests { use common::{ address::pubkeyhash::PublicKeyHash, - chain::{self, tokens::TokenId, Destination}, + chain::{self, Destination, tokens::TokenId}, }; use randomness::RngExt; use test_utils::{ assert_matches, assert_matches_return_val, - random::{make_seedable_rng, Seed}, + random::{Seed, make_seedable_rng}, }; use wallet_rpc_lib::types::RpcAmountIn; diff --git a/wallet/wallet-cli-commands/src/lib.rs b/wallet/wallet-cli-commands/src/lib.rs index c625b4db6c..a4074822b9 100644 --- a/wallet/wallet-cli-commands/src/lib.rs +++ b/wallet/wallet-cli-commands/src/lib.rs @@ -29,15 +29,15 @@ use common::{ chain::{Block, SignedTransaction, Transaction}, primitives::{BlockHeight, DecimalAmount, Id}, }; -use crypto::key::{hdkd::u31::U31, PrivateKey, PublicKey}; -use p2p_types::{bannable_address::BannableAddress, PeerId}; +use crypto::key::{PrivateKey, PublicKey, hdkd::u31::U31}; +use p2p_types::{PeerId, bannable_address::BannableAddress}; use rpc::description::{Described, Module}; use serialization::hex_encoded::HexEncoded; use utils_networking::IpOrSocketAddress; use wallet_controller::types::WalletTypeArgs; #[cfg(feature = "trezor")] use wallet_rpc_lib::types::FoundDevice; -use wallet_rpc_lib::{types::NodeInterface, ColdWalletRpcDescription, WalletRpcDescription}; +use wallet_rpc_lib::{ColdWalletRpcDescription, WalletRpcDescription, types::NodeInterface}; use crate::helper_types::{ CliCurrency, CliOutputTimeLock, CliTokenTotalSupply, CliUnspecifiedCurrencyTransfer, diff --git a/wallet/wallet-cli-lib/src/cli_event_loop.rs b/wallet/wallet-cli-lib/src/cli_event_loop.rs index fce9bc437f..1f43101c6a 100644 --- a/wallet/wallet-cli-lib/src/cli_event_loop.rs +++ b/wallet/wallet-cli-lib/src/cli_event_loop.rs @@ -26,9 +26,9 @@ use wallet_rpc_client::{ wallet_rpc_traits::WalletInterface, }; use wallet_rpc_lib::{ + ColdWalletRpcServer, WalletEventsRpcServer, WalletRpc, WalletRpcServer, WalletService, config::WalletRpcConfig, types::{ControllerConfig, NodeInterface}, - ColdWalletRpcServer, WalletEventsRpcServer, WalletRpc, WalletRpcServer, WalletService, }; use crate::{errors::WalletCliError, version_check::parse_version_without_metadata}; diff --git a/wallet/wallet-cli-lib/src/config.rs b/wallet/wallet-cli-lib/src/config.rs index cb391e6874..dc984bfab3 100644 --- a/wallet/wallet-cli-lib/src/config.rs +++ b/wallet/wallet-cli-lib/src/config.rs @@ -17,7 +17,7 @@ use std::path::PathBuf; use clap::{Args, Parser, Subcommand}; -use common::chain::config::{regtest_options::ChainConfigOptions, ChainType}; +use common::chain::config::{ChainType, regtest_options::ChainConfigOptions}; use crypto::key::hdkd::u31::U31; use utils::{app_version_with_git_info, clap_utils}; use utils_networking::NetworkAddressWithPort; diff --git a/wallet/wallet-cli-lib/src/lib.rs b/wallet/wallet-cli-lib/src/lib.rs index 621d3842a5..2490e7b3ff 100644 --- a/wallet/wallet-cli-lib/src/lib.rs +++ b/wallet/wallet-cli-lib/src/lib.rs @@ -27,8 +27,8 @@ use std::{ use cli_event_loop::Event; use common::chain::{ - config::{regtest_options::regtest_chain_config, ChainType}, ChainConfig, + config::{ChainType, regtest_options::regtest_chain_config}, }; use config::{CliArgs, Network}; use console::{ConsoleInput, ConsoleOutput}; @@ -144,7 +144,7 @@ async fn start_hot_wallet( _ => { return Err(Box::new(WalletCliError::::InvalidConfig( "Invalid RPC cookie/username/password combination".to_owned(), - ))) + ))); } }; diff --git a/wallet/wallet-cli-lib/src/repl/interactive/mod.rs b/wallet/wallet-cli-lib/src/repl/interactive/mod.rs index 32a1ba5e27..4926efdb38 100644 --- a/wallet/wallet-cli-lib/src/repl/interactive/mod.rs +++ b/wallet/wallet-cli-lib/src/repl/interactive/mod.rs @@ -23,15 +23,15 @@ use std::path::PathBuf; use clap::Command; use itertools::Itertools; use reedline::{ - default_emacs_keybindings, default_vi_insert_keybindings, default_vi_normal_keybindings, ColumnarMenu, DefaultPrompt, DefaultValidator, EditMode, Emacs, FileBackedHistory, History, - ListMenu, MenuBuilder, Reedline, ReedlineMenu, Signal, Vi, + ListMenu, MenuBuilder, Reedline, ReedlineMenu, Signal, Vi, default_emacs_keybindings, + default_vi_insert_keybindings, default_vi_normal_keybindings, }; use tokio::sync::{mpsc, oneshot}; use utils::once_destructor::OnceDestructor; use wallet_cli_commands::{ - get_repl_command, parse_input, ChoiceMenu, ConsoleCommand, ManageableWalletCommand, + ChoiceMenu, ConsoleCommand, ManageableWalletCommand, get_repl_command, parse_input, }; use wallet_rpc_lib::types::NodeInterface; @@ -435,10 +435,10 @@ fn read_command( reedline::KeyCode::Char('j') | reedline::KeyCode::Down if end_batch < last_batch => { - return Ok(PagginationCommand::Next) + return Ok(PagginationCommand::Next); } reedline::KeyCode::Char('k') | reedline::KeyCode::Up if current_index > 0 => { - return Ok(PagginationCommand::Previous) + return Ok(PagginationCommand::Previous); } reedline::KeyCode::Char('q') | reedline::KeyCode::Esc => { return Ok(PagginationCommand::Exit); diff --git a/wallet/wallet-cli-lib/src/repl/non_interactive/mod.rs b/wallet/wallet-cli-lib/src/repl/non_interactive/mod.rs index 91ebb439ca..f10973776f 100644 --- a/wallet/wallet-cli-lib/src/repl/non_interactive/mod.rs +++ b/wallet/wallet-cli-lib/src/repl/non_interactive/mod.rs @@ -17,10 +17,10 @@ pub mod log; use clap::Command; use tokio::sync::{mpsc, oneshot}; -use wallet_cli_commands::{get_repl_command, parse_input, ConsoleCommand}; +use wallet_cli_commands::{ConsoleCommand, get_repl_command, parse_input}; use wallet_rpc_lib::types::NodeInterface; -use crate::{cli_event_loop::Event, console::ConsoleOutput, errors::WalletCliError, ConsoleInput}; +use crate::{ConsoleInput, cli_event_loop::Event, console::ConsoleOutput, errors::WalletCliError}; #[derive(Debug)] enum LineOutput { diff --git a/wallet/wallet-cli-lib/tests/basic.rs b/wallet/wallet-cli-lib/tests/basic.rs index e910e75cc6..ae3435098f 100644 --- a/wallet/wallet-cli-lib/tests/basic.rs +++ b/wallet/wallet-cli-lib/tests/basic.rs @@ -19,7 +19,7 @@ use rstest::rstest; use common::{address::Address, chain::PoolId, primitives::H256}; use randomness::RngExt; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use utils::app_version_with_git_info; use crate::cli_test_framework::CliTestFramework; @@ -57,11 +57,12 @@ async fn wallet_cli_file(#[case] seed: Seed) { .unwrap() .to_owned(); - assert!(test - .exec(&format!( + assert!( + test.exec(&format!( "wallet-create software \"{file_name}\" store-seed-phrase" )) - .starts_with("New wallet created successfully\n")); + .starts_with("New wallet created successfully\n") + ); assert_eq!(test.exec("wallet-close"), "Successfully closed the wallet."); assert_eq!( @@ -103,14 +104,15 @@ async fn produce_blocks_decommission_genesis_pool(#[case] seed: Seed) { // create a new pool let address = test.exec("address-new"); - assert!(test - .exec(&format!( + assert!( + test.exec(&format!( "staking-create-pool 40000 {} 0.{} {}", rng.random_range(0..100), rng.random_range(1..100), address, ),) - .contains("The transaction was submitted successfully with ID")); + .contains("The transaction was submitted successfully with ID") + ); // create some blocks assert_eq!(test.exec("node-generate-blocks 20"), "Success"); @@ -122,21 +124,23 @@ async fn produce_blocks_decommission_genesis_pool(#[case] seed: Seed) { assert_eq!(test.exec("account-select 1"), "Success"); let acc2_address = test.exec("address-new"); assert_eq!(test.exec("account-select 0"), "Success"); - assert!(test - .exec(&format!("address-send {} 50000", acc2_address)) - .contains("The transaction was submitted successfully with ID")); + assert!( + test.exec(&format!("address-send {} 50000", acc2_address)) + .contains("The transaction was submitted successfully with ID") + ); // create a block assert_eq!(test.exec("node-generate-blocks 1"), "Success"); assert_eq!(test.exec("account-select 1"), "Success"); - assert!(test - .exec(&format!( + assert!( + test.exec(&format!( "staking-create-pool 40000 {} 0.{} {}", rng.random_range(0..100), rng.random_range(1..100), address, ),) - .contains("The transaction was submitted successfully with ID")); + .contains("The transaction was submitted successfully with ID") + ); assert_eq!(test.exec("account-select 0"), "Success"); // create some blocks @@ -166,9 +170,10 @@ async fn produce_blocks_decommission_genesis_pool(#[case] seed: Seed) { // submit the tx test.create_genesis_wallet(); assert_eq!(test.exec("wallet-sync"), "Success"); - assert!(test - .exec(&format!("node-submit-transaction {signed_tx}")) - .contains("The transaction was submitted successfully with ID")); + assert!( + test.exec(&format!("node-submit-transaction {signed_tx}")) + .contains("The transaction was submitted successfully with ID") + ); // stake with the other acc assert_eq!(test.exec("account-select 1"), "Success"); diff --git a/wallet/wallet-cli-lib/tests/cli_test_framework.rs b/wallet/wallet-cli-lib/tests/cli_test_framework.rs index 417fd22f6a..abfac079db 100644 --- a/wallet/wallet-cli-lib/tests/cli_test_framework.rs +++ b/wallet/wallet-cli-lib/tests/cli_test_framework.rs @@ -14,7 +14,7 @@ // limitations under the License. use std::{ - sync::{mpsc, Arc}, + sync::{Arc, mpsc}, time::Duration, }; @@ -31,8 +31,8 @@ use wallet_cli_lib::{ }; use wallet_rpc_lib::types::NodeInterface; use wallet_test_node::{ - create_chain_config, default_chain_config_options, start_node, COLD_WALLET_MENEMONIC, - RPC_PASSWORD, RPC_USERNAME, + COLD_WALLET_MENEMONIC, RPC_PASSWORD, RPC_USERNAME, create_chain_config, + default_chain_config_options, start_node, }; pub use wallet_test_node::MNEMONIC; diff --git a/wallet/wallet-cli-lib/tests/staking.rs b/wallet/wallet-cli-lib/tests/staking.rs index 2c1933d7f6..9f6323001f 100644 --- a/wallet/wallet-cli-lib/tests/staking.rs +++ b/wallet/wallet-cli-lib/tests/staking.rs @@ -16,7 +16,7 @@ mod cli_test_framework; use rstest::rstest; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use crate::cli_test_framework::CliTestFramework; diff --git a/wallet/wallet-controller/src/helpers/mod.rs b/wallet/wallet-controller/src/helpers/mod.rs index 57bf710d5c..a36a8ed22f 100644 --- a/wallet/wallet-controller/src/helpers/mod.rs +++ b/wallet/wallet-controller/src/helpers/mod.rs @@ -18,33 +18,33 @@ use std::collections::{BTreeMap, BTreeSet}; use futures::{ - stream::{FuturesOrdered, FuturesUnordered}, TryStreamExt, + stream::{FuturesOrdered, FuturesUnordered}, }; use common::{ address::RpcAddress, chain::{ + AccountCommand, ChainConfig, Currency, Destination, OrderAccountCommand, OrderId, PoolId, + RpcOrderInfo, Transaction, TxInput, TxOutput, UtxoOutPoint, htlc::HtlcSecret, output_values_holder::collect_token_v1_ids_from_output_values_holder, tokens::{RPCTokenInfo, TokenId}, - AccountCommand, ChainConfig, Currency, Destination, OrderAccountCommand, OrderId, PoolId, - RpcOrderInfo, Transaction, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{amount::RpcAmountOut, Amount}, + primitives::{Amount, amount::RpcAmountOut}, }; use node_comm::node_traits::NodeInterface; use utils::ensure; use wallet::{ - destination_getters::{get_tx_output_destination, HtlcSpendingCondition}, WalletError, + destination_getters::{HtlcSpendingCondition, get_tx_output_destination}, }; use wallet_types::partially_signed_transaction::{ OrderAdditionalInfo, PartiallySignedTransaction, PartiallySignedTransactionWalletExt as _, PoolAdditionalInfo, PtxAdditionalInfo, TokenAdditionalInfo, TokensAdditionalInfo, }; -use crate::{runtime_wallet::RuntimeWallet, types::Balances, ControllerError}; +use crate::{ControllerError, runtime_wallet::RuntimeWallet, types::Balances}; pub async fn fetch_rpc_token_info( rpc_client: &T, diff --git a/wallet/wallet-controller/src/helpers/tests.rs b/wallet/wallet-controller/src/helpers/tests.rs index c5e011712a..c0f9555044 100644 --- a/wallet/wallet-controller/src/helpers/tests.rs +++ b/wallet/wallet-controller/src/helpers/tests.rs @@ -26,7 +26,10 @@ use chainstate::ChainInfo; use common::{ address::pubkeyhash::PublicKeyHash, chain::{ - block::{timestamp::BlockTimestamp, BlockReward, ConsensusData}, + AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, Block, ChainConfig, + DelegationId, Destination, OrderAccountCommand, OrderData, PoolId, RpcOrderInfo, + SignedTransaction, Transaction, TxInput, TxOutput, UtxoOutPoint, + block::{BlockReward, ConsensusData, timestamp::BlockTimestamp}, classic_multisig::ClassicMultisigChallenge, config::create_regtest, htlc::{HashedTimelockContract, HtlcSecret, HtlcSecretHash}, @@ -39,18 +42,15 @@ use common::{ IsTokenFreezable, RPCFungibleTokenInfo, RPCTokenInfo, TokenId, TokenIssuance, TokenIssuanceV1, TokenTotalSupply, }, - AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, Block, ChainConfig, - DelegationId, Destination, OrderAccountCommand, OrderData, PoolId, RpcOrderInfo, - SignedTransaction, Transaction, TxInput, TxOutput, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight, Id, Idable}, + primitives::{Amount, BlockHeight, Id, Idable, per_thousand::PerThousand}, }; use node_comm::node_traits::MockNodeInterface; use randomness::{Rng, RngExt as _, SliceRandom as _}; -use test_utils::random::{gen_random_alnum_string, gen_random_bytes, make_seedable_rng, Seed}; +use test_utils::random::{Seed, gen_random_alnum_string, gen_random_bytes, make_seedable_rng}; use wallet::{ - wallet::test_helpers::{create_wallet_with_mnemonic, scan_wallet}, DefaultWallet, + wallet::test_helpers::{create_wallet_with_mnemonic, scan_wallet}, }; use wallet_types::{ account_info::DEFAULT_ACCOUNT_INDEX, @@ -62,10 +62,10 @@ use wallet_types::{ use crate::{ tests::test_utils::{ - create_block_scan_wallet, random_is_token_unfreezable, random_nft_issuance, - random_order_currencies_with_token, random_pub_key, random_rpc_is_token_frozen, - random_token_data_with_id_and_authority, random_vrf_pub_key, tx_with_outputs, - wallet_new_dest, OrderCurrencies, TestOrderData, TestTokenData, MNEMONIC, + MNEMONIC, OrderCurrencies, TestOrderData, TestTokenData, create_block_scan_wallet, + random_is_token_unfreezable, random_nft_issuance, random_order_currencies_with_token, + random_pub_key, random_rpc_is_token_frozen, random_token_data_with_id_and_authority, + random_vrf_pub_key, tx_with_outputs, wallet_new_dest, }, { helpers::{ diff --git a/wallet/wallet-controller/src/lib.rs b/wallet/wallet-controller/src/lib.rs index 3539039fb2..02686772ed 100644 --- a/wallet/wallet-controller/src/lib.rs +++ b/wallet/wallet-controller/src/lib.rs @@ -33,7 +33,7 @@ use chainstate::tx_verifier::{ self, error::ScriptError, input_check::signature_only_check::SignatureOnlyVerifiable, }; use futures::StreamExt; -use futures::{never::Never, stream::FuturesOrdered, TryStreamExt}; +use futures::{TryStreamExt, never::Never, stream::FuturesOrdered}; use helpers::{ fetch_input_infos, fetch_rpc_token_info, fetch_utxo, fetch_utxo_extra_info, into_balances, }; @@ -62,19 +62,19 @@ use synced_controller::SyncedController; use common::{ address::AddressError, chain::{ + Block, ChainConfig, Currency, Destination, GenBlock, PoolId, SighashInputCommitmentVersion, + SignedTransaction, Transaction, TxInput, TxOutput, UtxoOutPoint, block::timestamp::BlockTimestamp, htlc::HtlcSecret, signature::{ - inputsig::InputWitness, sighash::input_commitments::SighashInputCommitment, - DestinationSigError, Transactable, + DestinationSigError, Transactable, inputsig::InputWitness, + sighash::input_commitments::SighashInputCommitment, }, tokens::{RPCTokenInfo, TokenId}, - Block, ChainConfig, Currency, Destination, GenBlock, PoolId, SighashInputCommitmentVersion, - SignedTransaction, Transaction, TxInput, TxOutput, UtxoOutPoint, }, primitives::{ - time::{get_time, Time}, Amount, BlockHeight, Id, Idable, + time::{Time, get_time}, }, }; use consensus::{GenerateBlockInputData, PoSTimestampSearchInputData}; @@ -88,24 +88,24 @@ pub use node_comm::{ handles_client::WalletHandlesClient, make_cold_wallet_rpc_client, make_rpc_client, rpc_client::NodeRpcClient, }; -use randomness::{make_pseudo_rng, make_true_rng, RngExt as _}; +use randomness::{RngExt as _, make_pseudo_rng, make_true_rng}; +#[cfg(feature = "trezor")] +use wallet::signer::SignerError; #[cfg(feature = "ledger")] use wallet::signer::ledger_signer::LedgerSignerProvider; #[cfg(feature = "trezor")] use wallet::signer::trezor_signer::{SelectedDevice, TrezorSignerProvider}; -#[cfg(feature = "trezor")] -use wallet::signer::SignerError; use wallet::{ + WalletError, WalletResult, account::{ - currency_grouper::{self}, TransactionToSign, + currency_grouper::{self}, }, - destination_getters::{get_tx_output_destination, HtlcSpendingCondition}, + destination_getters::{HtlcSpendingCondition, get_tx_output_destination}, signer::software_signer::SoftwareSignerProvider, wallet::{WalletCreation, WalletPoolsFilter}, wallet_events::WalletEvents, - WalletError, WalletResult, }; pub use wallet_types::{ @@ -117,9 +117,9 @@ pub use wallet_types::{ use wallet_types::hw_data::HardwareWalletFullInfo; use wallet_types::{ partially_signed_transaction::{ - make_sighash_input_commitments, PartiallySignedTransaction, - PartiallySignedTransactionError, PartiallySignedTransactionWalletExt as _, - PtxAdditionalInfo, SighashInputCommitmentCreationError, + PartiallySignedTransaction, PartiallySignedTransactionError, + PartiallySignedTransactionWalletExt as _, PtxAdditionalInfo, + SighashInputCommitmentCreationError, make_sighash_input_commitments, }, signature_status::SignatureStatus, wallet_type::{WalletControllerMode, WalletType}, diff --git a/wallet/wallet-controller/src/read.rs b/wallet/wallet-controller/src/read.rs index be3d3d939a..198f77ab6f 100644 --- a/wallet/wallet-controller/src/read.rs +++ b/wallet/wallet-controller/src/read.rs @@ -17,7 +17,7 @@ use std::collections::BTreeMap; -use futures::{stream::FuturesUnordered, FutureExt, TryStreamExt}; +use futures::{FutureExt, TryStreamExt, stream::FuturesUnordered}; use common::{ address::Address, @@ -25,7 +25,7 @@ use common::{ ChainConfig, Currency, DelegationId, Destination, OrderId, PoolId, Transaction, TxOutput, UtxoOutPoint, }, - primitives::{id::WithId, Amount, Id}, + primitives::{Amount, Id, id::WithId}, }; use crypto::{ key::{ @@ -37,21 +37,21 @@ use crypto::{ use node_comm::node_traits::NodeInterface; use utils::tap_log::TapLog; use wallet::{ - account::{transaction_list::TransactionList, DelegationData, PoolData, TxInfo}, + account::{DelegationData, PoolData, TxInfo, transaction_list::TransactionList}, wallet::WalletPoolsFilter, }; use wallet_types::{ + KeyPurpose, KeychainUsageState, account_info::StandaloneAddresses, utxo_types::{UtxoStates, UtxoTypes}, wallet_tx::TxData, with_locked::WithLocked, - KeyPurpose, KeychainUsageState, }; use crate::{ + ControllerError, runtime_wallet::RuntimeWallet, types::{AccountStandaloneKeyDetails, Balances, CreatedBlockInfo}, - ControllerError, }; pub struct ReadOnlyController<'a, T, B: storage::Backend + 'static> { diff --git a/wallet/wallet-controller/src/runtime_wallet.rs b/wallet/wallet-controller/src/runtime_wallet.rs index 25633d1e24..b693edfec7 100644 --- a/wallet/wallet-controller/src/runtime_wallet.rs +++ b/wallet/wallet-controller/src/runtime_wallet.rs @@ -16,41 +16,42 @@ use std::collections::{BTreeMap, BTreeSet}; use common::{ - address::{pubkeyhash::PublicKeyHash, Address}, + address::{Address, pubkeyhash::PublicKeyHash}, chain::{ + AccountCommand, AccountOutPoint, Currency, DelegationId, Destination, GenBlock, + OrderAccountCommand, OrderId, PoolId, RpcOrderInfo, SignedTransaction, + SignedTransactionIntent, Transaction, TxOutput, UtxoOutPoint, classic_multisig::ClassicMultisigChallenge, htlc::{HashedTimelockContract, HtlcSecret}, output_value::OutputValue, signature::inputsig::arbitrary_message::ArbitraryMessageSignature, tokens::{IsTokenUnfreezable, Metadata, RPCFungibleTokenInfo, TokenId, TokenIssuance}, - AccountCommand, AccountOutPoint, Currency, DelegationId, Destination, GenBlock, - OrderAccountCommand, OrderId, PoolId, RpcOrderInfo, SignedTransaction, - SignedTransactionIntent, Transaction, TxOutput, UtxoOutPoint, }, - primitives::{id::WithId, Amount, BlockHeight, Id, H256}, + primitives::{Amount, BlockHeight, H256, Id, id::WithId}, }; use crypto::{ key::{ + PrivateKey, PublicKey, extended::ExtendedPublicKey, hdkd::{child_number::ChildNumber, u31::U31}, - PrivateKey, PublicKey, }, vrf::VRFPublicKey, }; use mempool::FeeRate; use wallet::{ + Wallet, WalletError, WalletResult, account::{ - transaction_list::TransactionList, CoinSelectionAlgo, DelegationData, OrderData, PoolData, - TxInfo, UnconfirmedTokenInfo, + CoinSelectionAlgo, DelegationData, OrderData, PoolData, TxInfo, UnconfirmedTokenInfo, + transaction_list::TransactionList, }, destination_getters::HtlcSpendingCondition, send_request::{SelectedInputs, StakePoolCreationArguments}, signer::software_signer::SoftwareSignerProvider, wallet::WalletPoolsFilter, wallet_events::WalletEvents, - Wallet, WalletError, WalletResult, }; use wallet_types::{ + KeyPurpose, KeychainUsageState, SignedTxWithFees, account_info::{StandaloneAddressDetails, StandaloneAddresses}, hw_data::HardwareWalletFullInfo, partially_signed_transaction::{ @@ -61,7 +62,6 @@ use wallet_types::{ utxo_types::{UtxoState, UtxoStates, UtxoTypes}, wallet_tx::TxData, with_locked::WithLocked, - KeyPurpose, KeychainUsageState, SignedTxWithFees, }; #[cfg(feature = "ledger")] diff --git a/wallet/wallet-controller/src/sync/mod.rs b/wallet/wallet-controller/src/sync/mod.rs index af14a65568..83705d7a95 100644 --- a/wallet/wallet-controller/src/sync/mod.rs +++ b/wallet/wallet-controller/src/sync/mod.rs @@ -18,7 +18,7 @@ use std::{cmp::Reverse, collections::BTreeMap, iter}; use async_trait::async_trait; use common::{ - chain::{block::timestamp::BlockTimestamp, Block, ChainConfig, GenBlock}, + chain::{Block, ChainConfig, GenBlock, block::timestamp::BlockTimestamp}, primitives::{BlockHeight, Id}, }; use crypto::key::hdkd::u31::U31; @@ -26,8 +26,8 @@ use logging::log; use node_comm::node_traits::NodeInterface; use utils::{once_destructor::OnceDestructor, set_flag::SetFlag}; use wallet::{ - signer::SignerProvider, wallet::WalletSyncingState, wallet_events::WalletEvents, Wallet, - WalletResult, + Wallet, WalletResult, signer::SignerProvider, wallet::WalletSyncingState, + wallet_events::WalletEvents, }; use crate::ControllerError; diff --git a/wallet/wallet-controller/src/sync/tests/mod.rs b/wallet/wallet-controller/src/sync/tests/mod.rs index dce552b248..8bdc2d0c2b 100644 --- a/wallet/wallet-controller/src/sync/tests/mod.rs +++ b/wallet/wallet-controller/src/sync/tests/mod.rs @@ -29,24 +29,24 @@ use chainstate::ChainInfo; use chainstate_test_framework::TestFramework; use common::{ chain::{ - tokens::{RPCTokenInfo, TokenId}, Currency, DelegationId, Destination, OrderId, PoolId, RpcOrderInfo, SignedTransaction, Transaction, + tokens::{RPCTokenInfo, TokenId}, }, - primitives::{time::Time, Amount}, + primitives::{Amount, time::Time}, }; use consensus::GenerateBlockInputData; use crypto::ephemeral_e2e::EndToEndPublicKey; use logging::log; -use mempool::{tx_accumulator::PackingStrategy, FeeRate}; +use mempool::{FeeRate, tx_accumulator::PackingStrategy}; use mempool_types::tx_options::TxOptionsOverrides; use node_comm::{ node_traits::{ConnectedPeer, MempoolEvents, PeerId}, rpc_client::NodeRpcError, }; use p2p_types::{bannable_address::BannableAddress, socket_address::SocketAddress}; -use randomness::{seq::IteratorRandom, CryptoRng, RngExt as _}; -use test_utils::random::{make_seedable_rng, Seed}; +use randomness::{CryptoRng, RngExt as _, seq::IteratorRandom}; +use test_utils::random::{Seed, make_seedable_rng}; use utils_networking::IpOrSocketAddress; use wallet::wallet_events::WalletEventsNoOp; use wallet_types::{account_info::DEFAULT_ACCOUNT_INDEX, wallet_type::WalletControllerMode}; diff --git a/wallet/wallet-controller/src/synced_controller.rs b/wallet/wallet-controller/src/synced_controller.rs index 56dbc5543c..ab276672f3 100644 --- a/wallet/wallet-controller/src/synced_controller.rs +++ b/wallet/wallet-controller/src/synced_controller.rs @@ -16,30 +16,30 @@ use std::collections::{BTreeMap, BTreeSet}; use chainstate::rpc::RpcOutputValueIn; -use futures::{stream::FuturesUnordered, TryStreamExt}; +use futures::{TryStreamExt, stream::FuturesUnordered}; use common::{ - address::{pubkeyhash::PublicKeyHash, Address}, + address::{Address, pubkeyhash::PublicKeyHash}, chain::{ + ChainConfig, Currency, DelegationId, Destination, OrderId, PoolId, RpcOrderInfo, + SignedTransaction, SignedTransactionIntent, Transaction, TxOutput, UtxoOutPoint, classic_multisig::ClassicMultisigChallenge, htlc::{HashedTimelockContract, HtlcSecret}, output_value::OutputValue, output_values_holder::collect_token_v1_ids_from_output_values_holder, signature::inputsig::arbitrary_message::ArbitraryMessageSignature, tokens::{ - get_referenced_token_ids_ignore_issuance, IsTokenFreezable, IsTokenUnfreezable, - Metadata, RPCFungibleTokenInfo, RPCTokenInfo, TokenId, TokenIssuance, TokenIssuanceV1, - TokenTotalSupply, + IsTokenFreezable, IsTokenUnfreezable, Metadata, RPCFungibleTokenInfo, RPCTokenInfo, + TokenId, TokenIssuance, TokenIssuanceV1, TokenTotalSupply, + get_referenced_token_ids_ignore_issuance, }, - ChainConfig, Currency, DelegationId, Destination, OrderId, PoolId, RpcOrderInfo, - SignedTransaction, SignedTransactionIntent, Transaction, TxOutput, UtxoOutPoint, }, - primitives::{amount::RpcAmountIn, per_thousand::PerThousand, Amount, Id}, + primitives::{Amount, Id, amount::RpcAmountIn, per_thousand::PerThousand}, }; use crypto::{ key::{ - hdkd::{child_number::ChildNumber, u31::U31}, PrivateKey, PublicKey, + hdkd::{child_number::ChildNumber, u31::U31}, }, vrf::VRFPublicKey, }; @@ -48,17 +48,18 @@ use mempool::FeeRate; use node_comm::node_traits::NodeInterface; use utils::ensure; use wallet::{ + WalletError, WalletResult, account::{CoinSelectionAlgo, TransactionToSign, UnconfirmedTokenInfo}, - destination_getters::{get_tx_output_destination, HtlcSpendingCondition}, + destination_getters::{HtlcSpendingCondition, get_tx_output_destination}, send_request::{ - make_address_output, make_address_output_token, make_create_delegation_output, - make_data_deposit_output, SelectedInputs, StakePoolCreationArguments, + SelectedInputs, StakePoolCreationArguments, make_address_output, make_address_output_token, + make_create_delegation_output, make_data_deposit_output, }, wallet::WalletPoolsFilter, wallet_events::WalletEvents, - WalletError, WalletResult, }; use wallet_types::{ + SignedTxWithFees, partially_signed_transaction::{ OrderAdditionalInfo, PartiallySignedTransaction, PtxAdditionalInfo, TokenAdditionalInfo, TokensAdditionalInfo, TxAdditionalInfo, @@ -66,10 +67,10 @@ use wallet_types::{ signature_status::SignatureStatus, utxo_types::{UtxoState, UtxoType}, with_locked::WithLocked, - SignedTxWithFees, }; use crate::{ + ControllerConfig, ControllerError, helpers::{ fetch_order_info, fetch_rpc_token_info, fetch_token_infos, fetch_token_infos_into, fetch_utxo, get_referenced_token_ids_from_partially_signed_transaction, into_balances, @@ -79,7 +80,6 @@ use crate::{ types::{ Balances, GenericCurrencyTransfer, NewTransaction, PreparedTransaction, SweepFromAddresses, }, - ControllerConfig, ControllerError, }; pub struct SyncedController<'a, T, W, B: storage::Backend + 'static> { diff --git a/wallet/wallet-controller/src/tests/compose_transaction_tests.rs b/wallet/wallet-controller/src/tests/compose_transaction_tests.rs index 7e16786e14..9152b3ec32 100644 --- a/wallet/wallet-controller/src/tests/compose_transaction_tests.rs +++ b/wallet/wallet-controller/src/tests/compose_transaction_tests.rs @@ -25,13 +25,13 @@ use chainstate::ChainInfo; use common::{ address::pubkeyhash::PublicKeyHash, chain::{ + Destination, OrderData, Transaction, TxInput, TxOutput, UtxoOutPoint, block::timestamp::BlockTimestamp, config::create_regtest, htlc::{HashedTimelockContract, HtlcSecret, HtlcSecretHash}, output_value::OutputValue, timelock::OutputTimeLock, tokens::{RPCTokenInfo, TokenId}, - Destination, OrderData, Transaction, TxInput, TxOutput, UtxoOutPoint, }, primitives::{Amount, BlockHeight, Id, Idable}, }; @@ -39,7 +39,7 @@ use node_comm::{mock::ClonableMockNodeInterface, node_traits::MockNodeInterface} use randomness::RngExt as _; use test_utils::{ assert_matches_return_val, - random::{gen_random_alnum_string, make_seedable_rng, Seed}, + random::{Seed, gen_random_alnum_string, make_seedable_rng}, }; use wallet::{ account::TransactionToSign, wallet::test_helpers::create_wallet_with_mnemonic, @@ -48,13 +48,13 @@ use wallet::{ use wallet_types::partially_signed_transaction::PtxAdditionalInfo; use crate::{ + Controller, helpers::get_referenced_token_ids_from_partially_signed_transaction, runtime_wallet::RuntimeWallet, tests::test_utils::{ - assert_fees, create_block_scan_wallet, random_rpc_ft_info_with_id_ticker_decimals, - tx_with_outputs, wallet_new_dest, MNEMONIC, + MNEMONIC, assert_fees, create_block_scan_wallet, + random_rpc_ft_info_with_id_ticker_decimals, tx_with_outputs, wallet_new_dest, }, - Controller, }; #[rstest] diff --git a/wallet/wallet-controller/src/tests/test_utils.rs b/wallet/wallet-controller/src/tests/test_utils.rs index ea0196e478..e98eb7e30a 100644 --- a/wallet/wallet-controller/src/tests/test_utils.rs +++ b/wallet/wallet-controller/src/tests/test_utils.rs @@ -18,6 +18,8 @@ use std::collections::BTreeMap; use common::{ address::pubkeyhash::PublicKeyHash, chain::{ + Block, ChainConfig, Currency, Destination, OrderId, SignedTransaction, Transaction, + TxOutput, block::{BlockReward, ConsensusData}, output_value::OutputValue, tokens::{ @@ -25,10 +27,8 @@ use common::{ RPCFungibleTokenInfo, RPCIsTokenFrozen, RPCTokenTotalSupply, TokenCreator, TokenId, TokenTotalSupply, }, - Block, ChainConfig, Currency, Destination, OrderId, SignedTransaction, Transaction, - TxOutput, }, - primitives::{amount::RpcAmountOut, Amount, BlockHeight}, + primitives::{Amount, BlockHeight, amount::RpcAmountOut}, }; use crypto::{ key::{KeyKind, PrivateKey, PublicKey}, @@ -36,7 +36,7 @@ use crypto::{ }; use randomness::{CryptoRng, Rng, RngExt as _}; use test_utils::random::{gen_random_alnum_string, gen_random_bytes}; -use wallet::{signer::SignerProvider, wallet::test_helpers::scan_wallet, DefaultWallet, Wallet}; +use wallet::{DefaultWallet, Wallet, signer::SignerProvider, wallet::test_helpers::scan_wallet}; use wallet_types::account_info::DEFAULT_ACCOUNT_INDEX; use crate::types::Balances; diff --git a/wallet/wallet-controller/src/types/mod.rs b/wallet/wallet-controller/src/types/mod.rs index 86b141482e..413e8c7239 100644 --- a/wallet/wallet-controller/src/types/mod.rs +++ b/wallet/wallet-controller/src/types/mod.rs @@ -27,11 +27,11 @@ use bip39::{Language, Mnemonic}; use common::{ chain::{ + ChainConfig, Destination, TxOutput, output_value::OutputValue, tokens::{RPCTokenInfo, TokenId}, - ChainConfig, Destination, TxOutput, }, - primitives::{amount::decimal::DecimalAmountWithIsSameComparison, DecimalAmount, H256}, + primitives::{DecimalAmount, H256, amount::decimal::DecimalAmountWithIsSameComparison}, }; use utils::ensure; #[cfg(feature = "trezor")] diff --git a/wallet/wallet-node-client/src/handles_client/mod.rs b/wallet/wallet-node-client/src/handles_client/mod.rs index 5624b51d69..2d8eea6ff5 100644 --- a/wallet/wallet-node-client/src/handles_client/mod.rs +++ b/wallet/wallet-node-client/src/handles_client/mod.rs @@ -25,23 +25,23 @@ use blockprod::{BlockProductionError, BlockProductionHandle, TimestampSearchData use chainstate::{BlockSource, ChainInfo, ChainstateError, ChainstateHandle}; use common::{ chain::{ - tokens::{RPCTokenInfo, TokenId}, Block, Currency, DelegationId, Destination, GenBlock, OrderId, PoolId, RpcOrderInfo, SignedTransaction, Transaction, + tokens::{RPCTokenInfo, TokenId}, }, - primitives::{time::Time, Amount, BlockHeight, Id}, + primitives::{Amount, BlockHeight, Id, time::Time}, }; use consensus::GenerateBlockInputData; use crypto::ephemeral_e2e::EndToEndPublicKey; use mempool::{ - event::MempoolEvent, tx_accumulator::PackingStrategy, tx_options::TxOptionsOverrides, FeeRate, - MempoolHandle, + FeeRate, MempoolHandle, event::MempoolEvent, tx_accumulator::PackingStrategy, + tx_options::TxOptionsOverrides, }; use p2p::{ + P2pHandle, error::P2pError, interface::types::ConnectedPeer, types::{bannable_address::BannableAddress, peer_id::PeerId, socket_address::SocketAddress}, - P2pHandle, }; use serialization::hex::HexError; use utils::app_version_with_git_info; diff --git a/wallet/wallet-node-client/src/mock.rs b/wallet/wallet-node-client/src/mock.rs index cbe071e5cd..13fa44b6b8 100644 --- a/wallet/wallet-node-client/src/mock.rs +++ b/wallet/wallet-node-client/src/mock.rs @@ -25,18 +25,18 @@ use tokio::sync::{Mutex, MutexGuard}; use chainstate::ChainInfo; use common::{ chain::{ - tokens::{RPCTokenInfo, TokenId}, Block, Currency, DelegationId, Destination, GenBlock, OrderId, PoolId, RpcOrderInfo, SignedTransaction, Transaction, TxOutput, UtxoOutPoint, + tokens::{RPCTokenInfo, TokenId}, }, - primitives::{time::Time, Amount, BlockHeight, Id}, + primitives::{Amount, BlockHeight, Id, time::Time}, }; use consensus::GenerateBlockInputData; use crypto::ephemeral_e2e::EndToEndPublicKey; -use mempool::{tx_accumulator::PackingStrategy, tx_options::TxOptionsOverrides, FeeRate}; +use mempool::{FeeRate, tx_accumulator::PackingStrategy, tx_options::TxOptionsOverrides}; use p2p::{ interface::types::ConnectedPeer, - types::{bannable_address::BannableAddress, socket_address::SocketAddress, PeerId}, + types::{PeerId, bannable_address::BannableAddress, socket_address::SocketAddress}, }; use utils_networking::IpOrSocketAddress; use wallet_types::wallet_type::WalletControllerMode; diff --git a/wallet/wallet-node-client/src/node_traits.rs b/wallet/wallet-node-client/src/node_traits.rs index 87c1093e1d..b0e5502f80 100644 --- a/wallet/wallet-node-client/src/node_traits.rs +++ b/wallet/wallet-node-client/src/node_traits.rs @@ -24,15 +24,15 @@ use futures::stream::Stream; use chainstate::ChainInfo; use common::{ chain::{ - tokens::{RPCTokenInfo, TokenId}, Block, Currency, DelegationId, Destination, GenBlock, OrderId, PoolId, RpcOrderInfo, SignedTransaction, Transaction, TxOutput, UtxoOutPoint, + tokens::{RPCTokenInfo, TokenId}, }, - primitives::{time::Time, Amount, BlockHeight, Id}, + primitives::{Amount, BlockHeight, Id, time::Time}, }; use consensus::GenerateBlockInputData; use crypto::ephemeral_e2e::EndToEndPublicKey; -use mempool::{tx_accumulator::PackingStrategy, tx_options::TxOptionsOverrides, FeeRate}; +use mempool::{FeeRate, tx_accumulator::PackingStrategy, tx_options::TxOptionsOverrides}; use p2p::types::{bannable_address::BannableAddress, socket_address::SocketAddress}; use utils_networking::IpOrSocketAddress; use wallet_types::wallet_type::WalletControllerMode; @@ -144,7 +144,7 @@ pub trait NodeInterface { async fn p2p_get_reserved_nodes(&self) -> Result, Self::Error>; async fn p2p_add_reserved_node(&self, address: IpOrSocketAddress) -> Result<(), Self::Error>; async fn p2p_remove_reserved_node(&self, address: IpOrSocketAddress) - -> Result<(), Self::Error>; + -> Result<(), Self::Error>; async fn mempool_get_fee_rate(&self, in_top_x_mb: usize) -> Result; async fn mempool_get_fee_rate_points(&self) -> Result, Self::Error>; diff --git a/wallet/wallet-node-client/src/rpc_client/client_impl.rs b/wallet/wallet-node-client/src/rpc_client/client_impl.rs index d7be5f8803..34c814ab44 100644 --- a/wallet/wallet-node-client/src/rpc_client/client_impl.rs +++ b/wallet/wallet-node-client/src/rpc_client/client_impl.rs @@ -21,22 +21,22 @@ use std::{ use futures::StreamExt; -use blockprod::{rpc::BlockProductionRpcClient, TimestampSearchData}; -use chainstate::{rpc::ChainstateRpcClient, ChainInfo}; +use blockprod::{TimestampSearchData, rpc::BlockProductionRpcClient}; +use chainstate::{ChainInfo, rpc::ChainstateRpcClient}; use common::{ address::Address, chain::{ - tokens::{RPCTokenInfo, TokenId}, Block, Currency, DelegationId, Destination, GenBlock, OrderId, PoolId, RpcOrderInfo, SignedTransaction, Transaction, TxOutput, UtxoOutPoint, + tokens::{RPCTokenInfo, TokenId}, }, - primitives::{time::Time, Amount, BlockHeight, Id}, + primitives::{Amount, BlockHeight, Id, time::Time}, }; use consensus::GenerateBlockInputData; use crypto::ephemeral_e2e::EndToEndPublicKey; use mempool::{ - rpc::MempoolRpcClient, rpc_event::RpcEvent, tx_accumulator::PackingStrategy, - tx_options::TxOptionsOverrides, FeeRate, + FeeRate, rpc::MempoolRpcClient, rpc_event::RpcEvent, tx_accumulator::PackingStrategy, + tx_options::TxOptionsOverrides, }; use p2p::{ interface::types::ConnectedPeer, diff --git a/wallet/wallet-node-client/src/rpc_client/cold_wallet_client.rs b/wallet/wallet-node-client/src/rpc_client/cold_wallet_client.rs index 743bef161c..c516267875 100644 --- a/wallet/wallet-node-client/src/rpc_client/cold_wallet_client.rs +++ b/wallet/wallet-node-client/src/rpc_client/cold_wallet_client.rs @@ -23,18 +23,18 @@ use blockprod::TimestampSearchData; use chainstate::ChainInfo; use common::{ chain::{ - tokens::{RPCTokenInfo, TokenId}, Block, Currency, DelegationId, Destination, GenBlock, OrderId, PoolId, RpcOrderInfo, SignedTransaction, Transaction, + tokens::{RPCTokenInfo, TokenId}, }, - primitives::{time::Time, Amount, BlockHeight, Id}, + primitives::{Amount, BlockHeight, Id, time::Time}, }; use consensus::GenerateBlockInputData; use crypto::ephemeral_e2e::EndToEndPublicKey; -use mempool::{tx_accumulator::PackingStrategy, tx_options::TxOptionsOverrides, FeeRate}; +use mempool::{FeeRate, tx_accumulator::PackingStrategy, tx_options::TxOptionsOverrides}; use p2p::{ interface::types::ConnectedPeer, - types::{bannable_address::BannableAddress, socket_address::SocketAddress, PeerId}, + types::{PeerId, bannable_address::BannableAddress, socket_address::SocketAddress}, }; use utils_networking::IpOrSocketAddress; use wallet_types::wallet_type::WalletControllerMode; diff --git a/wallet/wallet-node-client/src/rpc_client/mod.rs b/wallet/wallet-node-client/src/rpc_client/mod.rs index 5fa61930da..cfd21e2070 100644 --- a/wallet/wallet-node-client/src/rpc_client/mod.rs +++ b/wallet/wallet-node-client/src/rpc_client/mod.rs @@ -21,10 +21,10 @@ use std::sync::Arc; use common::address::AddressError; use common::chain::ChainConfig; use common::primitives::per_thousand::PerThousandParseError; -use rpc::new_ws_client; use rpc::ClientError; use rpc::RpcAuthData; use rpc::RpcWsClient; +use rpc::new_ws_client; use crate::node_traits::NodeInterface; diff --git a/wallet/wallet-node-client/tests/call_tests.rs b/wallet/wallet-node-client/tests/call_tests.rs index 462bb6dbe2..b0e407ac2b 100644 --- a/wallet/wallet-node-client/tests/call_tests.rs +++ b/wallet/wallet-node-client/tests/call_tests.rs @@ -17,17 +17,17 @@ use std::{net::SocketAddr, str::FromStr, sync::Arc}; use tokio::task::JoinHandle; -use blockprod::{test_blockprod_config, BlockProductionHandle}; +use blockprod::{BlockProductionHandle, test_blockprod_config}; use chainstate::{ - make_chainstate, rpc::ChainstateRpcServer, ChainstateConfig, ChainstateHandle, - DefaultTransactionVerificationStrategy, + ChainstateConfig, ChainstateHandle, DefaultTransactionVerificationStrategy, make_chainstate, + rpc::ChainstateRpcServer, }; use common::{ chain::{ - block::{timestamp::BlockTimestamp, BlockReward, ConsensusData}, Block, ChainConfig, + block::{BlockReward, ConsensusData, timestamp::BlockTimestamp}, }, - primitives::{Idable, H256}, + primitives::{H256, Idable}, }; use mempool::{MempoolConfig, MempoolHandle, MempoolInit}; use node_comm::{make_handles_client, make_rpc_client, node_traits::NodeInterface}; diff --git a/wallet/wallet-rpc-client/src/handles_client/mod.rs b/wallet/wallet-rpc-client/src/handles_client/mod.rs index 9ed0829cf6..f2ffdbf873 100644 --- a/wallet/wallet-rpc-client/src/handles_client/mod.rs +++ b/wallet/wallet-rpc-client/src/handles_client/mod.rs @@ -15,34 +15,35 @@ use std::{collections::BTreeMap, fmt::Debug, num::NonZeroUsize, path::PathBuf, str::FromStr}; -use chainstate::{rpc::RpcOutputValueIn, ChainInfo}; +use chainstate::{ChainInfo, rpc::RpcOutputValueIn}; use common::{ address::dehexify::dehexify_all_addresses, chain::{ + Block, GenBlock, RpcCurrency, SignedTransaction, SignedTransactionIntent, Transaction, + TxOutput, UtxoOutPoint, block::timestamp::BlockTimestamp, output_values_holder::collect_token_v1_ids_from_output_values_holders, tokens::{IsTokenUnfreezable, RPCTokenInfo}, - Block, GenBlock, RpcCurrency, SignedTransaction, SignedTransactionIntent, Transaction, - TxOutput, UtxoOutPoint, }, - primitives::{BlockHeight, DecimalAmount, Id, Idable, H256}, + primitives::{BlockHeight, DecimalAmount, H256, Id, Idable}, }; -use crypto::key::{hdkd::u31::U31, PrivateKey}; +use crypto::key::{PrivateKey, hdkd::u31::U31}; use node_comm::node_traits::NodeInterface; -use p2p_types::{bannable_address::BannableAddress, socket_address::SocketAddress, PeerId}; +use p2p_types::{PeerId, bannable_address::BannableAddress, socket_address::SocketAddress}; use rpc::types::RpcHexString; use serialization::{hex::HexEncode, hex_encoded::HexEncoded, json_encoded::JsonEncoded}; use utils::app_version_with_git_info; use utils_networking::IpOrSocketAddress; use wallet::account::TxInfo; use wallet_controller::{ + ConnectedPeer, ControllerConfig, UtxoState, UtxoType, types::{ CreatedBlockInfo, GenericTokenTransfer, SeedWithPassPhrase, WalletCreationOptions, WalletInfo, WalletTypeArgs, }, - ConnectedPeer, ControllerConfig, UtxoState, UtxoType, }; use wallet_rpc_lib::{ + RpcError, WalletRpc, types::{ AccountExtendedPublicKey, ActiveOrderInfo, AddressInfo, AddressWithUsageInfo, Balances, BlockInfo, ComposedTransaction, CreatedWallet, DelegationInfo, HardwareWalletType, @@ -54,7 +55,6 @@ use wallet_rpc_lib::{ StandaloneAddressWithDetails, TokenMetadata, TxOptionsOverrides, UtxoInfo, VrfPublicKeyInfo, }, - RpcError, WalletRpc, }; use wallet_types::{ partially_signed_transaction::PartiallySignedTransaction, scan_blockchain::ScanBlockchain, diff --git a/wallet/wallet-rpc-client/src/rpc_client/client_impl.rs b/wallet/wallet-rpc-client/src/rpc_client/client_impl.rs index 2ca842d22f..ff5d75c7af 100644 --- a/wallet/wallet-rpc-client/src/rpc_client/client_impl.rs +++ b/wallet/wallet-rpc-client/src/rpc_client/client_impl.rs @@ -21,29 +21,30 @@ use crate::wallet_rpc_traits::{ use super::{ClientWalletRpc, WalletRpcError}; -use chainstate::{rpc::RpcOutputValueIn, ChainInfo}; +use chainstate::{ChainInfo, rpc::RpcOutputValueIn}; use common::{ chain::{ - block::timestamp::BlockTimestamp, tokens::RPCTokenInfo, Block, GenBlock, RpcCurrency, - SignedTransaction, SignedTransactionIntent, Transaction, TxOutput, UtxoOutPoint, + Block, GenBlock, RpcCurrency, SignedTransaction, SignedTransactionIntent, Transaction, + TxOutput, UtxoOutPoint, block::timestamp::BlockTimestamp, tokens::RPCTokenInfo, }, primitives::{BlockHeight, DecimalAmount, Id}, }; -use crypto::key::{hdkd::u31::U31, PrivateKey}; -use p2p_types::{bannable_address::BannableAddress, socket_address::SocketAddress, PeerId}; +use crypto::key::{PrivateKey, hdkd::u31::U31}; +use p2p_types::{PeerId, bannable_address::BannableAddress, socket_address::SocketAddress}; use rpc::types::RpcHexString; -use serialization::hex_encoded::HexEncoded; use serialization::DecodeAll; +use serialization::hex_encoded::HexEncoded; use utils_networking::IpOrSocketAddress; use wallet::account::TxInfo; use wallet_controller::{ + ConnectedPeer, ControllerConfig, UtxoState, UtxoType, types::{ Balances, CreatedBlockInfo, GenericTokenTransfer, SeedWithPassPhrase, WalletInfo, WalletTypeArgs, }, - ConnectedPeer, ControllerConfig, UtxoState, UtxoType, }; use wallet_rpc_lib::{ + ColdWalletRpcClient, WalletRpcClient, types::{ AccountExtendedPublicKey, ActiveOrderInfo, AddressInfo, AddressWithUsageInfo, BlockInfo, ComposedTransaction, CreatedWallet, DelegationInfo, HardwareWalletType, @@ -55,7 +56,6 @@ use wallet_rpc_lib::{ StandaloneAddressWithDetails, TokenMetadata, TransactionOptions, TransactionRequestOptions, TxOptionsOverrides, UtxoInfo, VrfPublicKeyInfo, }, - ColdWalletRpcClient, WalletRpcClient, }; use wallet_types::{ partially_signed_transaction::PartiallySignedTransaction, with_locked::WithLocked, diff --git a/wallet/wallet-rpc-client/src/rpc_client/mod.rs b/wallet/wallet-rpc-client/src/rpc_client/mod.rs index 47ad432c78..fdad2d7d52 100644 --- a/wallet/wallet-rpc-client/src/rpc_client/mod.rs +++ b/wallet/wallet-rpc-client/src/rpc_client/mod.rs @@ -15,10 +15,10 @@ pub mod client_impl; -use rpc::new_http_client; use rpc::ClientError; use rpc::RpcAuthData; use rpc::RpcHttpClient; +use rpc::new_http_client; use crate::wallet_rpc_traits::WalletInterface; diff --git a/wallet/wallet-rpc-client/src/wallet_rpc_traits.rs b/wallet/wallet-rpc-client/src/wallet_rpc_traits.rs index 540deb5eb3..f1fdf02f61 100644 --- a/wallet/wallet-rpc-client/src/wallet_rpc_traits.rs +++ b/wallet/wallet-rpc-client/src/wallet_rpc_traits.rs @@ -15,24 +15,24 @@ use std::{collections::BTreeMap, num::NonZeroUsize, path::PathBuf}; -use chainstate::{rpc::RpcOutputValueIn, ChainInfo}; +use chainstate::{ChainInfo, rpc::RpcOutputValueIn}; use common::{ chain::{ - block::timestamp::BlockTimestamp, tokens::RPCTokenInfo, Block, GenBlock, RpcCurrency, - SignedTransaction, SignedTransactionIntent, Transaction, TxOutput, UtxoOutPoint, + Block, GenBlock, RpcCurrency, SignedTransaction, SignedTransactionIntent, Transaction, + TxOutput, UtxoOutPoint, block::timestamp::BlockTimestamp, tokens::RPCTokenInfo, }, primitives::{BlockHeight, DecimalAmount, Id}, }; -use crypto::key::{hdkd::u31::U31, PrivateKey}; -use p2p_types::{bannable_address::BannableAddress, socket_address::SocketAddress, PeerId}; +use crypto::key::{PrivateKey, hdkd::u31::U31}; +use p2p_types::{PeerId, bannable_address::BannableAddress, socket_address::SocketAddress}; use serialization::hex_encoded::HexEncoded; use utils_networking::IpOrSocketAddress; use wallet::account::TxInfo; use wallet_controller::{ + ConnectedPeer, ControllerConfig, UtxoState, UtxoType, types::{ CreatedBlockInfo, GenericTokenTransfer, SeedWithPassPhrase, WalletInfo, WalletTypeArgs, }, - ConnectedPeer, ControllerConfig, UtxoState, UtxoType, }; use wallet_rpc_lib::types::{ AccountExtendedPublicKey, ActiveOrderInfo, AddressInfo, AddressWithUsageInfo, Balances, @@ -377,7 +377,7 @@ pub trait WalletInterface { ) -> Result, Self::Error>; async fn new_vrf_public_key(&self, account_index: U31) - -> Result; + -> Result; async fn get_vrf_public_key( &self, diff --git a/wallet/wallet-rpc-lib/src/cmdline.rs b/wallet/wallet-rpc-lib/src/cmdline.rs index d8df44e9b9..3762d10d6e 100644 --- a/wallet/wallet-rpc-lib/src/cmdline.rs +++ b/wallet/wallet-rpc-lib/src/cmdline.rs @@ -16,11 +16,11 @@ use std::path::PathBuf; use clap::ValueEnum; -use common::chain::config::{regtest_options::ChainConfigOptions, ChainType}; +use common::chain::config::{ChainType, regtest_options::ChainConfigOptions}; use crypto::key::hdkd::u31::U31; use rpc::{ - rpc_creds::{RpcCreds, RpcCredsError}, RpcAuthData, + rpc_creds::{RpcCreds, RpcCredsError}, }; use utils::{ app_version_with_git_info, clap_utils, cookie::COOKIE_FILENAME, diff --git a/wallet/wallet-rpc-lib/src/config.rs b/wallet/wallet-rpc-lib/src/config.rs index 6bf0e55d07..9724a39b11 100644 --- a/wallet/wallet-rpc-lib/src/config.rs +++ b/wallet/wallet-rpc-lib/src/config.rs @@ -16,11 +16,11 @@ use std::{net::SocketAddr, path::PathBuf, sync::Arc}; use common::chain::config::{ - regtest_options::{regtest_chain_config, ChainConfigOptions}, ChainConfig, ChainType, + regtest_options::{ChainConfigOptions, regtest_chain_config}, }; use crypto::key::hdkd::u31::U31; -use rpc::{rpc_creds::RpcCreds, RpcAuthData}; +use rpc::{RpcAuthData, rpc_creds::RpcCreds}; use crate::types::HardwareWalletType; diff --git a/wallet/wallet-rpc-lib/src/lib.rs b/wallet/wallet-rpc-lib/src/lib.rs index 54ef2bff95..2fb4b740f7 100644 --- a/wallet/wallet-rpc-lib/src/lib.rs +++ b/wallet/wallet-rpc-lib/src/lib.rs @@ -21,8 +21,9 @@ mod service; #[cfg(any(feature = "trezor", feature = "ledger"))] use rpc::types::HardwareWalletType; pub use rpc::{ - types, ColdWalletRpcClient, ColdWalletRpcDescription, ColdWalletRpcServer, RpcCreds, RpcError, + ColdWalletRpcClient, ColdWalletRpcDescription, ColdWalletRpcServer, RpcCreds, RpcError, WalletEventsRpcServer, WalletRpc, WalletRpcClient, WalletRpcDescription, WalletRpcServer, + types, }; pub use service::{Event, EventStream, TxState, WalletHandle, /* WalletResult, */ WalletService,}; use wallet_controller::{NodeInterface, NodeRpcClient}; diff --git a/wallet/wallet-rpc-lib/src/rpc/interface.rs b/wallet/wallet-rpc-lib/src/rpc/interface.rs index 5279d4214b..b7dd005a3b 100644 --- a/wallet/wallet-rpc-lib/src/rpc/interface.rs +++ b/wallet/wallet-rpc-lib/src/rpc/interface.rs @@ -23,10 +23,10 @@ use chainstate::rpc::RpcOutputValueIn; use common::{ address::RpcAddress, chain::{ - block::timestamp::BlockTimestamp, - tokens::{RPCTokenInfo, TokenId}, Block, DelegationId, Destination, GenBlock, OrderId, PoolId, RpcCurrency, SignedTransaction, SignedTransactionIntent, Transaction, TxOutput, + block::timestamp::BlockTimestamp, + tokens::{RPCTokenInfo, TokenId}, }, primitives::{BlockHeight, Id}, }; @@ -35,8 +35,8 @@ use p2p_types::{bannable_address::BannableAddress, socket_address::SocketAddress use rpc::types::RpcHexString; use wallet::account::TxInfo; use wallet_controller::{ - types::{BlockInfo, CreatedBlockInfo, GenericTokenTransfer, SeedWithPassPhrase, WalletInfo}, ConnectedPeer, + types::{BlockInfo, CreatedBlockInfo, GenericTokenTransfer, SeedWithPassPhrase, WalletInfo}, }; use wallet_types::{ partially_signed_transaction::PartiallySignedTransaction, with_locked::WithLocked, @@ -622,7 +622,7 @@ trait WalletRpc { /// List delegation ids controlled by the selected account in this wallet, with their balances #[method(name = "delegation_list_ids")] async fn list_delegation_ids(&self, account: AccountArg) - -> rpc::RpcResult>; + -> rpc::RpcResult>; /// List the blocks created by the selected account in this wallet through staking/mining/etc #[method(name = "staking_list_created_block_ids")] diff --git a/wallet/wallet-rpc-lib/src/rpc/mod.rs b/wallet/wallet-rpc-lib/src/rpc/mod.rs index da50c09587..3f28c91f20 100644 --- a/wallet/wallet-rpc-lib/src/rpc/mod.rs +++ b/wallet/wallet-rpc-lib/src/rpc/mod.rs @@ -26,45 +26,45 @@ use std::{ time::Duration, }; -use futures::{stream::FuturesUnordered, TryStreamExt as _}; +use futures::{TryStreamExt as _, stream::FuturesUnordered}; use itertools::Itertools as _; use chainstate::{ + ChainInfo, TokenIssuanceError, rpc::{RpcOutputValueIn, RpcOutputValueOut}, tx_verifier::check_transaction, - ChainInfo, TokenIssuanceError, }; use common::{ + TokenDecimals, address::Address, chain::{ + Block, ChainConfig, Currency, DelegationId, Destination, GenBlock, OrderId, PoolId, + RpcCurrency, SignedTransaction, SignedTransactionIntent, Transaction, TxOutput, + UtxoOutPoint, block::timestamp::BlockTimestamp, classic_multisig::ClassicMultisigChallenge, htlc::{HashedTimelockContract, HtlcSecret, HtlcSecretHash}, output_value::OutputValue, output_values_holder::collect_token_v1_ids_from_rpc_output_values_holders, signature::inputsig::arbitrary_message::{ - produce_message_challenge, ArbitraryMessageSignature, + ArbitraryMessageSignature, produce_message_challenge, }, tokens::{ IsTokenFreezable, IsTokenUnfreezable, Metadata, RPCTokenInfo, TokenId, TokenTotalSupply, }, - Block, ChainConfig, Currency, DelegationId, Destination, GenBlock, OrderId, PoolId, - RpcCurrency, SignedTransaction, SignedTransactionIntent, Transaction, TxOutput, - UtxoOutPoint, }, primitives::{ - id::WithId, per_thousand::PerThousand, time::Time, Amount, BlockHeight, Id, Idable, + Amount, BlockHeight, Id, Idable, id::WithId, per_thousand::PerThousand, time::Time, }, - TokenDecimals, }; use crypto::{ - key::{hdkd::u31::U31, PrivateKey, PublicKey}, + key::{PrivateKey, PublicKey, hdkd::u31::U31}, vrf::VRFPublicKey, }; use mempool::tx_accumulator::PackingStrategy; use mempool_types::tx_options::TxOptionsOverrides; -use p2p_types::{bannable_address::BannableAddress, socket_address::SocketAddress, PeerId}; -use serialization::{hex_encoded::HexEncoded, DecodeAll}; +use p2p_types::{PeerId, bannable_address::BannableAddress, socket_address::SocketAddress}; +use serialization::{DecodeAll, hex_encoded::HexEncoded}; use types::{ AccountExtendedPublicKey, NewOrderTransaction, NewSubmittedTransaction, NewTokenTransaction, RpcHashedTimelockContract, RpcNewTransaction, RpcPreparedTransaction, @@ -72,29 +72,29 @@ use types::{ use utils::{ensure, shallow_clone::ShallowClone, sorted::Sorted as _}; use utils_networking::IpOrSocketAddress; use wallet::{ - account::{transaction_list::TransactionList, PoolData, TransactionToSign, TxInfo}, WalletError, + account::{PoolData, TransactionToSign, TxInfo, transaction_list::TransactionList}, }; use wallet_controller::{ + ConnectedPeer, ControllerConfig, ControllerError, DEFAULT_ACCOUNT_INDEX, NodeInterface, + UtxoState, UtxoStates, UtxoType, UtxoTypes, types::{ Balances, BlockInfo, CreatedBlockInfo, CreatedWallet, GenericTokenTransfer, InspectTransaction, NewTransaction, OpenedWallet, RpcAmountOut, SeedWithPassPhrase, SweepFromAddresses, TransactionToInspect, WalletCreationOptions, WalletInfo, WalletTypeArgs, }, - ConnectedPeer, ControllerConfig, ControllerError, NodeInterface, UtxoState, UtxoStates, - UtxoType, UtxoTypes, DEFAULT_ACCOUNT_INDEX, }; use wallet_types::{ - account_info::StandaloneAddressDetails, generic_transaction::GenericTransaction, + SignedTxWithFees, account_info::StandaloneAddressDetails, + generic_transaction::GenericTransaction, partially_signed_transaction::PartiallySignedTransaction, scan_blockchain::ScanBlockchain, signature_status::SignatureStatus, wallet_tx::TxData, with_locked::WithLocked, - SignedTxWithFees, }; use crate::{ - types::{ActiveOrderInfo, ExistingOwnOrderData}, WalletHandle, WalletRpcConfig, + types::{ActiveOrderInfo, ExistingOwnOrderData}, }; #[cfg(any(feature = "trezor", feature = "ledger"))] @@ -112,7 +112,7 @@ pub use interface::{ ColdWalletRpcClient, ColdWalletRpcDescription, ColdWalletRpcServer, WalletEventsRpcServer, WalletRpcClient, WalletRpcDescription, WalletRpcServer, }; -pub use rpc::{rpc_creds::RpcCreds, Rpc}; +pub use rpc::{Rpc, rpc_creds::RpcCreds}; pub use self::types::RpcError; @@ -916,7 +916,7 @@ where GenericTransaction::Tx(tx) => TransactionToSign::Tx(tx), GenericTransaction::Partial(tx) => TransactionToSign::Partial(tx), GenericTransaction::Signed(_) => { - return Err(RpcError::UnexpectedFullySignedTransaction) + return Err(RpcError::UnexpectedFullySignedTransaction); } }; diff --git a/wallet/wallet-rpc-lib/src/rpc/server_impl.rs b/wallet/wallet-rpc-lib/src/rpc/server_impl.rs index 3fafbdb295..f75c0d4e68 100644 --- a/wallet/wallet-rpc-lib/src/rpc/server_impl.rs +++ b/wallet/wallet-rpc-lib/src/rpc/server_impl.rs @@ -19,33 +19,34 @@ use chainstate::rpc::RpcOutputValueIn; use common::{ address::dehexify::dehexify_all_addresses, chain::{ + Block, DelegationId, Destination, GenBlock, OrderId, PoolId, RpcCurrency, + SignedTransaction, SignedTransactionIntent, Transaction, TxOutput, block::timestamp::BlockTimestamp, output_values_holder::collect_token_v1_ids_from_output_values_holders, tokens::{IsTokenUnfreezable, RPCTokenInfo, TokenId}, - Block, DelegationId, Destination, GenBlock, OrderId, PoolId, RpcCurrency, - SignedTransaction, SignedTransactionIntent, Transaction, TxOutput, }, - primitives::{time::Time, BlockHeight, Id, Idable}, + primitives::{BlockHeight, Id, Idable, time::Time}, }; use crypto::{key::PrivateKey, vrf::VRFPublicKey}; -use p2p_types::{bannable_address::BannableAddress, socket_address::SocketAddress, PeerId}; +use p2p_types::{PeerId, bannable_address::BannableAddress, socket_address::SocketAddress}; use serialization::{hex::HexEncode, json_encoded::JsonEncoded}; use utils::app_version_with_git_info; use utils_networking::IpOrSocketAddress; use wallet::account::TxInfo; use wallet_controller::{ + ConnectedPeer, NodeInterface, UtxoState, UtxoStates, UtxoType, UtxoTypes, types::{ BlockInfo, CreatedBlockInfo, GenericTokenTransfer, SeedWithPassPhrase, WalletCreationOptions, WalletInfo, }, - ConnectedPeer, NodeInterface, UtxoState, UtxoStates, UtxoType, UtxoTypes, }; use wallet_types::{ - partially_signed_transaction::PartiallySignedTransaction, scan_blockchain::ScanBlockchain, - signature_status::SignatureStatus, with_locked::WithLocked, ImportOrCreate, + ImportOrCreate, partially_signed_transaction::PartiallySignedTransaction, + scan_blockchain::ScanBlockchain, signature_status::SignatureStatus, with_locked::WithLocked, }; use crate::{ + RpcError, rpc::{ColdWalletRpcServer, WalletEventsRpcServer, WalletRpc, WalletRpcServer}, types::{ AccountArg, ActiveOrderInfo, AddressInfo, AddressWithUsageInfo, Balances, ChainInfo, @@ -58,7 +59,6 @@ use crate::{ StandaloneAddressWithDetails, TokenMetadata, TransactionOptions, TransactionRequestOptions, TxOptionsOverrides, UtxoInfo, VrfPublicKeyInfo, }, - RpcError, }; use super::types::{ diff --git a/wallet/wallet-rpc-lib/src/rpc/types.rs b/wallet/wallet-rpc-lib/src/rpc/types.rs index bf26f7bd01..380f0a5cc0 100644 --- a/wallet/wallet-rpc-lib/src/rpc/types.rs +++ b/wallet/wallet-rpc-lib/src/rpc/types.rs @@ -17,24 +17,24 @@ use chainstate::rpc::RpcTypeError; use common::{ - address::{pubkeyhash::PublicKeyHash, Address, AddressError}, + TokenDecimalsProvider, TokenDecimalsUnavailableError, + address::{Address, AddressError, pubkeyhash::PublicKeyHash}, chain::{ + ChainConfig, DelegationId, Destination, OrderId, PoolId, SignedTransaction, Transaction, + TxOutput, UtxoOutPoint, block::timestamp::BlockTimestamp, classic_multisig::ClassicMultisigChallengeError, signature::DestinationSigError, timelock::OutputTimeLock, tokens::{self, IsTokenFreezable, Metadata, TokenCreator, TokenId}, - ChainConfig, DelegationId, Destination, OrderId, PoolId, SignedTransaction, Transaction, - TxOutput, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight, Id, Idable}, - TokenDecimalsProvider, TokenDecimalsUnavailableError, + primitives::{Amount, BlockHeight, Id, Idable, per_thousand::PerThousand}, }; use crypto::{ key::{ + PublicKey, extended::ExtendedPublicKey, hdkd::{chain_code::ChainCode, child_number::ChildNumber, u31::U31}, - PublicKey, }, vrf::VRFPublicKey, }; @@ -43,10 +43,10 @@ use utils::ensure; use wallet::account::PoolData; pub use chainstate::{ + ChainInfo, rpc::{ RpcOutputValueIn, RpcOutputValueOut, RpcSignedTransaction, RpcTxOutput, RpcUtxoOutpoint, }, - ChainInfo, }; pub use common::{ address::RpcAddress, @@ -59,11 +59,11 @@ pub use serialization::hex_encoded::HexEncoded; pub use wallet_controller::types::{ Balances, BlockInfo, InspectTransaction, SignatureStats, ValidatedSignatures, }; -use wallet_controller::{types::WalletTypeArgs, UtxoState, UtxoType}; pub use wallet_controller::{ControllerConfig, NodeInterface}; +use wallet_controller::{UtxoState, UtxoType, types::WalletTypeArgs}; use wallet_types::{ - partially_signed_transaction::PartiallySignedTransaction, seed_phrase::StoreSeedPhrase, - signature_status::SignatureStatus, ImportOrCreate, KeyPurpose, + ImportOrCreate, KeyPurpose, partially_signed_transaction::PartiallySignedTransaction, + seed_phrase::StoreSeedPhrase, signature_status::SignatureStatus, }; use crate::service::SubmitError; @@ -83,7 +83,9 @@ pub enum RpcError { #[error("Invalid address: {0}")] InvalidAddressWithAddr(String), - #[error("Failed to parse margin_ratio_per_thousand. The decimal must be in the range [0.001,1.000] or [0.1%,100%]")] + #[error( + "Failed to parse margin_ratio_per_thousand. The decimal must be in the range [0.001,1.000] or [0.1%,100%]" + )] InvalidMarginRatio, #[error("Invalid pool ID")] @@ -139,7 +141,9 @@ pub enum RpcError { #[error("Can't compose a transaction without any inputs")] ComposeTransactionEmptyInputs, - #[error("Provided address to create a Multisig address at index {0} is not a valid public key. Only public keys can be used.")] + #[error( + "Provided address to create a Multisig address at index {0} is not a valid public key. Only public keys can be used." + )] MultisigNotPublicKey(usize), #[error("Invalid multisig: {0}")] @@ -154,9 +158,7 @@ pub enum RpcError { #[error("The specified address {0} is not a multisig address")] NotMultisigAddress(String), - #[error( - "There are no UTXOs corresponding to the specified multisig address for tokens: {0:?}" - )] + #[error("There are no UTXOs corresponding to the specified multisig address for tokens: {0:?}")] NoUtxosForMultisigAddressForTokens(Vec), #[error("No outputs specified")] @@ -919,7 +921,7 @@ impl From for CreatedWallet { multiple_devices_available: Some(MultipleDevicesAvailable::Trezor { devices: devices.into_iter().map(Into::into).collect(), }), - } + }; } }; Self { diff --git a/wallet/wallet-rpc-lib/src/service/events.rs b/wallet/wallet-rpc-lib/src/service/events.rs index a44d1284c2..eb40f9b181 100644 --- a/wallet/wallet-rpc-lib/src/service/events.rs +++ b/wallet/wallet-rpc-lib/src/service/events.rs @@ -14,7 +14,7 @@ // limitations under the License. use common::{ - chain::{block::timestamp::BlockTimestamp, GenBlock, OutPointSourceId, Transaction}, + chain::{GenBlock, OutPointSourceId, Transaction, block::timestamp::BlockTimestamp}, primitives::{BlockHeight, Id, Idable}, }; use crypto::key::hdkd::u31::U31; diff --git a/wallet/wallet-rpc-lib/src/service/worker.rs b/wallet/wallet-rpc-lib/src/service/worker.rs index f46081374b..5fd26b0e85 100644 --- a/wallet/wallet-rpc-lib/src/service/worker.rs +++ b/wallet/wallet-rpc-lib/src/service/worker.rs @@ -28,7 +28,7 @@ use wallet_controller::types::{ use wallet_controller::{ControllerError, NodeInterface}; use wallet_types::{scan_blockchain::ScanBlockchain, wallet_type::WalletType}; -use crate::{types::RpcError, Event}; +use crate::{Event, types::RpcError}; use super::WalletServiceEvents; diff --git a/wallet/wallet-rpc-lib/tests/basic.rs b/wallet/wallet-rpc-lib/tests/basic.rs index 137f0973ea..c70a71820e 100644 --- a/wallet/wallet-rpc-lib/tests/basic.rs +++ b/wallet/wallet-rpc-lib/tests/basic.rs @@ -21,19 +21,19 @@ use common::{ }; use logging::log; use utils::{ - make_seedable_rng, ClientT, JsonValue, Seed, Subscription, SubscriptionClientT, ACCOUNT0_ARG, - ACCOUNT1_ARG, + ACCOUNT0_ARG, ACCOUNT1_ARG, ClientT, JsonValue, Seed, Subscription, SubscriptionClientT, + make_seedable_rng, }; use wallet_rpc_lib::{ + TxState, types::{ AddressInfo, Balances, BlockInfo, NewAccountInfo, NewSubmittedTransaction, RpcAmountIn, RpcUtxoState, TransactionOptions, }, - TxState, }; use rstest::*; -use tokio::time::{timeout, Duration}; +use tokio::time::{Duration, timeout}; #[rstest] #[trace] diff --git a/wallet/wallet-rpc-lib/tests/utils.rs b/wallet/wallet-rpc-lib/tests/utils.rs index 38a8d2a8ba..fc23e83d57 100644 --- a/wallet/wallet-rpc-lib/tests/utils.rs +++ b/wallet/wallet-rpc-lib/tests/utils.rs @@ -19,7 +19,7 @@ use std::{sync::Arc, time::Duration}; use common::{ chain::config::{ - regtest::GenesisStakingSettings, regtest_options::ChainConfigOptions, ChainConfig, + ChainConfig, regtest::GenesisStakingSettings, regtest_options::ChainConfigOptions, }, primitives::BlockHeight, }; @@ -28,13 +28,13 @@ use rpc::RpcAuthData; use test_utils::{test_dir::TestRoot, test_root}; use wallet::signer::software_signer::SoftwareSignerProvider; use wallet_controller::NodeRpcClient; -use wallet_rpc_lib::{config::WalletServiceConfig, types::AccountArg, WalletHandle, WalletService}; +use wallet_rpc_lib::{WalletHandle, WalletService, config::WalletServiceConfig, types::AccountArg}; use wallet_test_node::{RPC_PASSWORD, RPC_USERNAME}; use wallet_types::{seed_phrase::StoreSeedPhrase, wallet_type::WalletType}; pub use rpc::test_support::{ClientT, Subscription, SubscriptionClientT}; pub use serde_json::Value as JsonValue; -pub use test_utils::random::{make_seedable_rng, Seed}; +pub use test_utils::random::{Seed, make_seedable_rng}; pub const ACCOUNT0_ARG: AccountArg = AccountArg(0); pub const ACCOUNT1_ARG: AccountArg = AccountArg(1); diff --git a/wallet/wallet-test-node/src/lib.rs b/wallet/wallet-test-node/src/lib.rs index a9f348c6ad..6277b2c19d 100644 --- a/wallet/wallet-test-node/src/lib.rs +++ b/wallet/wallet-test-node/src/lib.rs @@ -25,24 +25,24 @@ use randomness::{Rng, RngExt as _}; use blockprod::{rpc::BlockProductionRpcServer, test_blockprod_config}; use chainstate::{ - make_chainstate, rpc::ChainstateRpcServer, ChainstateConfig, - DefaultTransactionVerificationStrategy, + ChainstateConfig, DefaultTransactionVerificationStrategy, make_chainstate, + rpc::ChainstateRpcServer, }; use common::{ chain::{ + ChainConfig, ConsensusUpgrade, Destination, Genesis, NetUpgrades, PoSChainConfigBuilder, + TxOutput, block::timestamp::BlockTimestamp, config::{ - self, regtest::GenesisStakingSettings, regtest_options::ChainConfigOptions, ChainType, + self, ChainType, regtest::GenesisStakingSettings, regtest_options::ChainConfigOptions, }, output_value::OutputValue, pos_initial_difficulty, stakelock::StakePoolData, - ChainConfig, ConsensusUpgrade, Destination, Genesis, NetUpgrades, PoSChainConfigBuilder, - TxOutput, }, - primitives::{per_thousand::PerThousand, Amount, BlockHeight, H256}, + primitives::{Amount, BlockHeight, H256, per_thousand::PerThousand}, }; -use mempool::{rpc::MempoolRpcServer, MempoolConfig, MempoolInit}; +use mempool::{MempoolConfig, MempoolInit, rpc::MempoolRpcServer}; use p2p::rpc::P2pRpcServer; use rpc::rpc_creds::RpcCreds; diff --git a/wasm-wrappers/src/encode_input.rs b/wasm-wrappers/src/encode_input.rs index 9c817235f9..35743c9b96 100644 --- a/wasm-wrappers/src/encode_input.rs +++ b/wasm-wrappers/src/encode_input.rs @@ -17,8 +17,8 @@ use wasm_bindgen::prelude::*; use common::{ chain::{ - config::Builder, AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, - OrderAccountCommand, OrdersVersion, OutPointSourceId, TxInput, UtxoOutPoint, + AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, OrderAccountCommand, + OrdersVersion, OutPointSourceId, TxInput, UtxoOutPoint, config::Builder, }, primitives::BlockHeight, }; diff --git a/wasm-wrappers/src/encode_output.rs b/wasm-wrappers/src/encode_output.rs index 23319b0a3e..49a9160341 100644 --- a/wasm-wrappers/src/encode_output.rs +++ b/wasm-wrappers/src/encode_output.rs @@ -18,6 +18,7 @@ use std::str::FromStr as _; use wasm_bindgen::prelude::*; use common::chain::{ + ChainConfig, OrderData, TxOutput, config::Builder, htlc::{HashedTimelockContract, HtlcSecretHash}, output_value::OutputValue::{self, Coin, TokenV1}, @@ -27,7 +28,6 @@ use common::chain::{ Metadata, NftIssuance, NftIssuanceV0, TokenCreator, TokenIssuance, TokenIssuanceV1, TokenTotalSupply, }, - ChainConfig, OrderData, TxOutput, }; use crypto::key::PublicKey; use serialization::{DecodeAll, Encode}; diff --git a/wasm-wrappers/src/error.rs b/wasm-wrappers/src/error.rs index 3878931c6b..3b90c2dcc0 100644 --- a/wasm-wrappers/src/error.rs +++ b/wasm-wrappers/src/error.rs @@ -18,20 +18,19 @@ use wasm_bindgen::JsValue; use common::{ address::AddressError, chain::{ + IdCreationError, SignedTransactionIntentError, TransactionCreationError, classic_multisig::ClassicMultisigChallengeError, partially_signed_transaction::{ PartiallySignedTransactionError, SighashInputCommitmentCreationError, }, signature::{ + DestinationSigError, inputsig::{ - arbitrary_message::SignArbitraryMessageError, + InputWitnessTag, arbitrary_message::SignArbitraryMessageError, authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpendTag, classical_multisig::authorize_classical_multisig::ClassicalMultisigSigningError, - InputWitnessTag, }, - DestinationSigError, }, - IdCreationError, SignedTransactionIntentError, TransactionCreationError, }, size_estimation::SizeEstimationError, }; diff --git a/wasm-wrappers/src/internal.rs b/wasm-wrappers/src/internal.rs index 3821e4a2d7..60d2a97abf 100644 --- a/wasm-wrappers/src/internal.rs +++ b/wasm-wrappers/src/internal.rs @@ -19,16 +19,17 @@ use wasm_bindgen::prelude::*; use common::{ chain::{ + Transaction, TxOutput, config::Builder, partially_signed_transaction::make_sighash_input_commitments_at_height, signature::{ inputsig::{ + InputWitness, authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, - standard_signature::StandardInputSignature, InputWitness, + standard_signature::StandardInputSignature, }, sighash::signature_hash, }, - Transaction, TxOutput, }, primitives::BlockHeight, }; diff --git a/wasm-wrappers/src/lib.rs b/wasm-wrappers/src/lib.rs index 5e1f45de5f..86503acb85 100644 --- a/wasm-wrappers/src/lib.rs +++ b/wasm-wrappers/src/lib.rs @@ -33,55 +33,55 @@ use std::{num::NonZeroU8, str::FromStr}; use bip39::Language; use itertools::Itertools as _; -use wasm_bindgen::{prelude::*, JsValue}; +use wasm_bindgen::{JsValue, prelude::*}; use common::{ - address::{dehexify::dehexify_all_addresses, pubkeyhash::PublicKeyHash, Address}, + address::{Address, dehexify::dehexify_all_addresses, pubkeyhash::PublicKeyHash}, chain::{ + Destination, OutPointSourceId, SignedTransaction, SignedTransactionIntent, Transaction, + TxInput, TxOutput, UtxoOutPoint, block::timestamp::BlockTimestamp, classic_multisig::ClassicMultisigChallenge, - config::{Builder, BIP44_PATH}, + config::{BIP44_PATH, Builder}, htlc::HtlcSecret, make_delegation_id, make_order_id, make_pool_id, make_token_id, partially_signed_transaction::{ - make_sighash_input_commitments_at_height, PartiallySignedTransaction, - PartiallySignedTransactionConsistencyCheck, + PartiallySignedTransaction, PartiallySignedTransactionConsistencyCheck, + make_sighash_input_commitments_at_height, }, signature::{ inputsig::{ - arbitrary_message::{produce_message_challenge, ArbitraryMessageSignature}, + InputWitness, + arbitrary_message::{ArbitraryMessageSignature, produce_message_challenge}, authorize_hashed_timelock_contract_spend::{ AuthorizedHashedTimelockContractSpend, AuthorizedHashedTimelockContractSpendTag, }, classical_multisig::authorize_classical_multisig::{ - sign_classical_multisig_spending, AuthorizedClassicalMultisigSpend, + AuthorizedClassicalMultisigSpend, sign_classical_multisig_spending, }, htlc::{ produce_uniparty_signature_for_htlc_refunding, produce_uniparty_signature_for_htlc_spending, }, standard_signature::StandardInputSignature, - InputWitness, }, sighash::signature_hash, }, stakelock::StakePoolData, timelock::OutputTimeLock, - Destination, OutPointSourceId, SignedTransaction, SignedTransactionIntent, Transaction, - TxInput, TxOutput, UtxoOutPoint, }, - primitives::{per_thousand::PerThousand, BlockHeight, Id, Idable, H256}, + primitives::{BlockHeight, H256, Id, Idable, per_thousand::PerThousand}, size_estimation::{ input_signature_size_from_destination, outputs_encoded_size, tx_size_with_num_inputs_and_outputs, }, }; use crypto::key::{ + KeyKind, PrivateKey, PublicKey, Signature, extended::{ExtendedKeyKind, ExtendedPrivateKey, ExtendedPublicKey}, hdkd::{child_number::ChildNumber, derivable::Derivable, u31::U31}, - KeyKind, PrivateKey, PublicKey, Signature, }; -use serialization::{json_encoded::JsonEncoded, Decode, DecodeAll, Encode}; +use serialization::{Decode, DecodeAll, Encode, json_encoded::JsonEncoded}; use crate::{ error::Error, diff --git a/wasm-wrappers/src/tests.rs b/wasm-wrappers/src/tests.rs index 61be8140df..40dba76848 100644 --- a/wasm-wrappers/src/tests.rs +++ b/wasm-wrappers/src/tests.rs @@ -16,7 +16,7 @@ use rstest::rstest; use randomness::RngExt; -use test_utils::random::{make_seedable_rng, Seed}; +use test_utils::random::{Seed, make_seedable_rng}; use super::*; diff --git a/wasm-wrappers/src/utils.rs b/wasm-wrappers/src/utils.rs index e1ccce6eb9..91ec3b1677 100644 --- a/wasm-wrappers/src/utils.rs +++ b/wasm-wrappers/src/utils.rs @@ -16,8 +16,9 @@ use std::str::FromStr as _; use common::{ - address::{traits::Addressable, Address}, + address::{Address, traits::Addressable}, chain::{ + ChainConfig, OrderId, PoolId, output_value::OutputValue, partially_signed_transaction::{ OrderAdditionalInfo as PtxOrderAdditionalInfo, @@ -25,13 +26,12 @@ use common::{ }, signature::{ inputsig::{ - authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, InputWitness, InputWitnessTag, + authorize_hashed_timelock_contract_spend::AuthorizedHashedTimelockContractSpend, }, sighash::sighashtype::SigHashType, }, tokens::TokenId, - ChainConfig, OrderId, PoolId, }, primitives::{self}, }; diff --git a/wasm-wrappers/wasm-doc-gen/src/main.rs b/wasm-wrappers/wasm-doc-gen/src/main.rs index a3c0281c42..2e645a635e 100644 --- a/wasm-wrappers/wasm-doc-gen/src/main.rs +++ b/wasm-wrappers/wasm-doc-gen/src/main.rs @@ -307,7 +307,7 @@ fn main() -> anyhow::Result<()> { "Failed to open file {} to check docs: {e}\n Does it really exist?", file_path.display() - )) + )); } };