diff --git a/substrate/bin/node/bench/src/import.rs b/substrate/bin/node/bench/src/import.rs index a4056b49f7..5bbf1ddf3b 100644 --- a/substrate/bin/node/bench/src/import.rs +++ b/substrate/bin/node/bench/src/import.rs @@ -138,7 +138,8 @@ impl core::Benchmark for ImportBenchmark { // should be 5 per signed extrinsic + 1 per unsigned // we have 1 unsigned and the rest are signed in the block // those 5 events per signed are: - // - new account (RawEvent::NewAccount) as we always transfer fund to non-existant account + // - new account (RawEvent::NewAccount) as we always transfer fund to + // non-existant account // - endowed (RawEvent::Endowed) for this new account // - successful transfer (RawEvent::Transfer) for this transfer operation // - deposit event for charging transaction fee diff --git a/substrate/bin/node/cli/src/chain_spec.rs b/substrate/bin/node/cli/src/chain_spec.rs index 5d9e049cc3..bbb2904bea 100644 --- a/substrate/bin/node/cli/src/chain_spec.rs +++ b/substrate/bin/node/cli/src/chain_spec.rs @@ -78,10 +78,13 @@ fn session_keys( } fn staging_testnet_config_genesis() -> GenesisConfig { + #[rustfmt::skip] // stash, controller, session-key // generated with secret: // for i in 1 2 3 4 ; do for j in stash controller; do subkey inspect "$secret"/fir/$j/$i; done; done + // // and + // // for i in 1 2 3 4 ; do for j in session; do subkey --ed25519 inspect "$secret"//fir//$j//$i; done; done let initial_authorities: Vec<( diff --git a/substrate/bin/node/executor/tests/basic.rs b/substrate/bin/node/executor/tests/basic.rs index 062e9f7b5a..e9e21e541e 100644 --- a/substrate/bin/node/executor/tests/basic.rs +++ b/substrate/bin/node/executor/tests/basic.rs @@ -50,7 +50,8 @@ pub fn bloaty_code_unwrap() -> &'static [u8] { ) } -/// Default transfer fee. This will use the same logic that is implemented in transaction-payment module. +/// Default transfer fee. This will use the same logic that is implemented in transaction-payment +/// module. /// /// Note that reads the multiplier from storage directly, hence to get the fee of `extrinsic` /// at block `n`, it must be called prior to executing block `n` to do the calculation with the @@ -721,7 +722,8 @@ fn native_big_block_import_succeeds() { fn native_big_block_import_fails_on_fallback() { let mut t = new_test_ext(compact_code_unwrap(), false); - // We set the heap pages to 8 because we know that should give an OOM in WASM with the given block. + // We set the heap pages to 8 because we know that should give an OOM in WASM with the given + // block. set_heap_pages(&mut t.ext(), 8); assert!(executor_call:: _>( diff --git a/substrate/bin/node/testing/src/bench.rs b/substrate/bin/node/testing/src/bench.rs index 9b49f82c6a..f6ed241841 100644 --- a/substrate/bin/node/testing/src/bench.rs +++ b/substrate/bin/node/testing/src/bench.rs @@ -306,8 +306,8 @@ impl<'a> Iterator for BlockContentIterator<'a> { BlockType::RandomTransfersReaping => { Call::Balances(BalancesCall::transfer( sp_runtime::MultiAddress::Id(receiver), - // Transfer so that ending balance would be 1 less than existential deposit - // so that we kill the sender account. + // Transfer so that ending balance would be 1 less than existential + // deposit so that we kill the sender account. 100 * DOLLARS - (node_runtime::ExistentialDeposit::get() - 1), )) }, diff --git a/substrate/client/allocator/src/freeing_bump.rs b/substrate/client/allocator/src/freeing_bump.rs index ef401deed6..741f4012cd 100644 --- a/substrate/client/allocator/src/freeing_bump.rs +++ b/substrate/client/allocator/src/freeing_bump.rs @@ -217,7 +217,7 @@ impl Link { /// | 0 | next element link | /// +--------------+-------------------+ /// ``` -/// +/// /// ## Occupied header /// ```ignore /// 64 32 0 diff --git a/substrate/client/api/src/backend.rs b/substrate/client/api/src/backend.rs index 0fcd85120c..8b5bd50ffa 100644 --- a/substrate/client/api/src/backend.rs +++ b/substrate/client/api/src/backend.rs @@ -365,14 +365,16 @@ pub trait StorageProvider> { key: &StorageKey, ) -> sp_blockchain::Result>; - /// Given a `BlockId` and a key prefix, return the matching child storage keys and values in that block. + /// Given a `BlockId` and a key prefix, return the matching child storage keys and values in + /// that block. fn storage_pairs( &self, id: &BlockId, key_prefix: &StorageKey, ) -> sp_blockchain::Result>; - /// Given a `BlockId` and a key prefix, return a `KeyIterator` iterates matching storage keys in that block. + /// Given a `BlockId` and a key prefix, return a `KeyIterator` iterates matching storage keys in + /// that block. fn storage_keys_iter<'a>( &self, id: &BlockId, @@ -380,7 +382,8 @@ pub trait StorageProvider> { start_key: Option<&StorageKey>, ) -> sp_blockchain::Result>; - /// Given a `BlockId`, a key and a child storage key, return the value under the key in that block. + /// Given a `BlockId`, a key and a child storage key, return the value under the key in that + /// block. fn child_storage( &self, id: &BlockId, @@ -388,7 +391,8 @@ pub trait StorageProvider> { key: &StorageKey, ) -> sp_blockchain::Result>; - /// Given a `BlockId`, a key prefix, and a child storage key, return the matching child storage keys. + /// Given a `BlockId`, a key prefix, and a child storage key, return the matching child storage + /// keys. fn child_storage_keys( &self, id: &BlockId, @@ -406,7 +410,8 @@ pub trait StorageProvider> { start_key: Option<&StorageKey>, ) -> sp_blockchain::Result>; - /// Given a `BlockId`, a key and a child storage key, return the hash under the key in that block. + /// Given a `BlockId`, a key and a child storage key, return the hash under the key in that + /// block. fn child_storage_hash( &self, id: &BlockId, @@ -569,7 +574,8 @@ pub trait PrunableStateChangesTrieStorage: ) -> sp_blockchain::Result, Block::Hash>>; /// Get end block (inclusive) of oldest pruned max-level (or skewed) digest trie blocks range. /// It is guaranteed that we have no any changes tries before (and including) this block. - /// It is guaranteed that all existing changes tries after this block are not yet pruned (if created). + /// It is guaranteed that all existing changes tries after this block are not yet pruned (if + /// created). fn oldest_pruned_digest_range_end(&self) -> NumberFor; } @@ -616,7 +622,8 @@ pub trait ProvideChtRoots { block: NumberFor, ) -> sp_blockchain::Result>; - /// Get changes trie CHT root for given block. Returns None if the block is not a part of any CHT. + /// Get changes trie CHT root for given block. Returns None if the block is not a part of any + /// CHT. fn changes_trie_cht_root( &self, cht_size: NumberFor, diff --git a/substrate/client/api/src/cht.rs b/substrate/client/api/src/cht.rs index 50b54a17f8..83bc84c6ec 100644 --- a/substrate/client/api/src/cht.rs +++ b/substrate/client/api/src/cht.rs @@ -47,7 +47,8 @@ pub fn size>() -> N { SIZE.into() } -/// Returns Some(cht_number) if CHT is need to be built when the block with given number is canonized. +/// Returns Some(cht_number) if CHT is need to be built when the block with given number is +/// canonized. pub fn is_build_required(cht_size: N, block_num: N) -> Option where N: Clone + AtLeast32Bit, diff --git a/substrate/client/api/src/leaves.rs b/substrate/client/api/src/leaves.rs index db5a25b451..80216bc466 100644 --- a/substrate/client/api/src/leaves.rs +++ b/substrate/client/api/src/leaves.rs @@ -125,7 +125,8 @@ where displaced } - /// Note a block height finalized, displacing all leaves with number less than the finalized block's. + /// Note a block height finalized, displacing all leaves with number less than the finalized + /// block's. /// /// Although it would be more technically correct to also prune out leaves at the /// same number as the finalized block, but with different hashes, the current behavior diff --git a/substrate/client/api/src/proof_provider.rs b/substrate/client/api/src/proof_provider.rs index ad0989c743..79444f0069 100644 --- a/substrate/client/api/src/proof_provider.rs +++ b/substrate/client/api/src/proof_provider.rs @@ -55,11 +55,11 @@ pub trait ProofProvider { id: &BlockId, ) -> sp_blockchain::Result<(Block::Header, StorageProof)>; - /// Get proof for computation of (block, extrinsic) pairs where key has been changed at given blocks range. - /// `min` is the hash of the first block, which changes trie root is known to the requester - when we're using - /// changes tries from ascendants of this block, we should provide proofs for changes tries roots - /// `max` is the hash of the last block known to the requester - we can't use changes tries from descendants - /// of this block. + /// Get proof for computation of (block, extrinsic) pairs where key has been changed at given + /// blocks range. `min` is the hash of the first block, which changes trie root is known to the + /// requester - when we're using changes tries from ascendants of this block, we should provide + /// proofs for changes tries roots `max` is the hash of the last block known to the requester - + /// we can't use changes tries from descendants of this block. /// Works only for runtimes that are supporting changes tries. fn key_changes_proof( &self, @@ -72,7 +72,8 @@ pub trait ProofProvider { ) -> sp_blockchain::Result>; /// Given a `BlockId` iterate over all storage values starting at `start_key` exclusively, - /// building proofs until size limit is reached. Returns combined proof and the number of collected keys. + /// building proofs until size limit is reached. Returns combined proof and the number of + /// collected keys. fn read_proof_collection( &self, id: &BlockId, diff --git a/substrate/client/authority-discovery/src/lib.rs b/substrate/client/authority-discovery/src/lib.rs index 4929ce6991..800f683aa0 100644 --- a/substrate/client/authority-discovery/src/lib.rs +++ b/substrate/client/authority-discovery/src/lib.rs @@ -87,8 +87,8 @@ impl Default for WorkerConfig { max_publish_interval: Duration::from_secs(1 * 60 * 60), keystore_refresh_interval: Duration::from_secs(60), // External addresses of remote authorities can change at any given point in time. The - // interval on which to trigger new queries for the current and next authorities is a trade - // off between efficiency and performance. + // interval on which to trigger new queries for the current and next authorities is a + // trade off between efficiency and performance. // // Querying 700 [`AuthorityId`]s takes ~8m on the Kusama DHT (16th Nov 2020) when // comparing `authority_discovery_authority_addresses_requested_total` and diff --git a/substrate/client/authority-discovery/src/worker.rs b/substrate/client/authority-discovery/src/worker.rs index dccaf10d06..5974bb7afb 100644 --- a/substrate/client/authority-discovery/src/worker.rs +++ b/substrate/client/authority-discovery/src/worker.rs @@ -91,7 +91,8 @@ pub enum Role { /// /// 4. Put addresses and signature as a record with the authority id as a key on a Kademlia DHT. /// -/// When constructed with either [`Role::PublishAndDiscover`] or [`Role::Discover`] a [`Worker`] will +/// When constructed with either [`Role::PublishAndDiscover`] or [`Role::Discover`] a [`Worker`] +/// will /// /// 1. Retrieve the current and next set of authorities. /// diff --git a/substrate/client/basic-authorship/src/basic_authorship.rs b/substrate/client/basic-authorship/src/basic_authorship.rs index b606062948..b9703041ff 100644 --- a/substrate/client/basic-authorship/src/basic_authorship.rs +++ b/substrate/client/basic-authorship/src/basic_authorship.rs @@ -68,8 +68,8 @@ pub struct ProposerFactory { metrics: PrometheusMetrics, /// The default block size limit. /// - /// If no `block_size_limit` is passed to [`sp_consensus::Proposer::propose`], this block size limit will be - /// used. + /// If no `block_size_limit` is passed to [`sp_consensus::Proposer::propose`], this block size + /// limit will be used. default_block_size_limit: usize, telemetry: Option, /// When estimating the block size, should the proof be included? @@ -81,7 +81,8 @@ pub struct ProposerFactory { impl ProposerFactory { /// Create a new proposer factory. /// - /// Proof recording will be disabled when using proposers built by this instance to build blocks. + /// Proof recording will be disabled when using proposers built by this instance to build + /// blocks. pub fn new( spawn_handle: impl SpawnNamed + 'static, client: Arc, @@ -140,7 +141,8 @@ impl ProposerFactory { /// The default value for the block size limit is: /// [`DEFAULT_BLOCK_SIZE_LIMIT`]. /// - /// If there is no block size limit passed to [`sp_consensus::Proposer::propose`], this value will be used. + /// If there is no block size limit passed to [`sp_consensus::Proposer::propose`], this value + /// will be used. pub fn set_default_block_size_limit(&mut self, limit: usize) { self.default_block_size_limit = limit; } diff --git a/substrate/client/cli/src/commands/utils.rs b/substrate/client/cli/src/commands/utils.rs index fa783f7a95..6148f17e7f 100644 --- a/substrate/client/cli/src/commands/utils.rs +++ b/substrate/client/cli/src/commands/utils.rs @@ -55,7 +55,8 @@ pub fn read_uri(uri: Option<&String>) -> error::Result { /// /// 1. Try to construct the `Pair` while using `uri` as input for [`sp_core::Pair::from_phrase`]. /// -/// 2. Try to construct the `Pair` while using `uri` as input for [`sp_core::Pair::from_string_with_seed`]. +/// 2. Try to construct the `Pair` while using `uri` as input for +/// [`sp_core::Pair::from_string_with_seed`]. /// /// 3. Try to construct the `Pair::Public` while using `uri` as input for /// [`sp_core::crypto::Ss58Codec::from_string_with_version`]. diff --git a/substrate/client/cli/src/lib.rs b/substrate/client/cli/src/lib.rs index 0d5051bc11..b560594f77 100644 --- a/substrate/client/cli/src/lib.rs +++ b/substrate/client/cli/src/lib.rs @@ -92,8 +92,9 @@ pub trait SubstrateCli: Sized { fn load_spec(&self, id: &str) -> std::result::Result, String>; /// Helper function used to parse the command line arguments. This is the equivalent of - /// `structopt`'s `from_iter()` except that it takes a `VersionInfo` argument to provide the name of - /// the application, author, "about" and version. It will also set `AppSettings::GlobalVersion`. + /// `structopt`'s `from_iter()` except that it takes a `VersionInfo` argument to provide the + /// name of the application, author, "about" and version. It will also set + /// `AppSettings::GlobalVersion`. /// /// To allow running the node without subcommand, tt also sets a few more settings: /// `AppSettings::ArgsNegateSubcommands` and `AppSettings::SubcommandsNegateReqs`. @@ -108,8 +109,9 @@ pub trait SubstrateCli: Sized { } /// Helper function used to parse the command line arguments. This is the equivalent of - /// `structopt`'s `from_iter()` except that it takes a `VersionInfo` argument to provide the name of - /// the application, author, "about" and version. It will also set `AppSettings::GlobalVersion`. + /// `structopt`'s `from_iter()` except that it takes a `VersionInfo` argument to provide the + /// name of the application, author, "about" and version. It will also set + /// `AppSettings::GlobalVersion`. /// /// To allow running the node without subcommand, it also sets a few more settings: /// `AppSettings::ArgsNegateSubcommands` and `AppSettings::SubcommandsNegateReqs`. @@ -166,8 +168,9 @@ pub trait SubstrateCli: Sized { } /// Helper function used to parse the command line arguments. This is the equivalent of - /// `structopt`'s `from_iter()` except that it takes a `VersionInfo` argument to provide the name of - /// the application, author, "about" and version. It will also set `AppSettings::GlobalVersion`. + /// `structopt`'s `from_iter()` except that it takes a `VersionInfo` argument to provide the + /// name of the application, author, "about" and version. It will also set + /// `AppSettings::GlobalVersion`. /// /// To allow running the node without subcommand, it also sets a few more settings: /// `AppSettings::ArgsNegateSubcommands` and `AppSettings::SubcommandsNegateReqs`. diff --git a/substrate/client/cli/src/params/import_params.rs b/substrate/client/cli/src/params/import_params.rs index 9248e210eb..3c87e91c22 100644 --- a/substrate/client/cli/src/params/import_params.rs +++ b/substrate/client/cli/src/params/import_params.rs @@ -167,7 +167,8 @@ pub struct ExecutionStrategiesParams { )] pub execution_offchain_worker: Option, - /// The means of execution used when calling into the runtime while not syncing, importing or constructing blocks. + /// The means of execution used when calling into the runtime while not syncing, importing or + /// constructing blocks. #[structopt( long = "execution-other", value_name = "STRATEGY", diff --git a/substrate/client/cli/src/params/mod.rs b/substrate/client/cli/src/params/mod.rs index 6e55f607ae..dac832a1f8 100644 --- a/substrate/client/cli/src/params/mod.rs +++ b/substrate/client/cli/src/params/mod.rs @@ -40,7 +40,8 @@ pub use crate::params::{ transaction_pool_params::*, }; -/// Wrapper type of `String` that holds an unsigned integer of arbitrary size, formatted as a decimal. +/// Wrapper type of `String` that holds an unsigned integer of arbitrary size, formatted as a +/// decimal. #[derive(Debug, Clone)] pub struct GenericNumber(String); diff --git a/substrate/client/cli/src/params/network_params.rs b/substrate/client/cli/src/params/network_params.rs index dd2e09e4a8..676873cfab 100644 --- a/substrate/client/cli/src/params/network_params.rs +++ b/substrate/client/cli/src/params/network_params.rs @@ -110,13 +110,13 @@ pub struct NetworkParams { /// Enable peer discovery on local networks. /// - /// By default this option is `true` for `--dev` or when the chain type is `Local`/`Development` - /// and false otherwise. + /// By default this option is `true` for `--dev` or when the chain type is + /// `Local`/`Development` and false otherwise. #[structopt(long)] pub discover_local: bool, - /// Require iterative Kademlia DHT queries to use disjoint paths for increased resiliency in the - /// presence of potentially adversarial nodes. + /// Require iterative Kademlia DHT queries to use disjoint paths for increased resiliency in + /// the presence of potentially adversarial nodes. /// /// See the S/Kademlia paper for more information on the high level design as well as its /// security improvements. diff --git a/substrate/client/cli/src/params/node_key_params.rs b/substrate/client/cli/src/params/node_key_params.rs index bc5606752a..41f9033d28 100644 --- a/substrate/client/cli/src/params/node_key_params.rs +++ b/substrate/client/cli/src/params/node_key_params.rs @@ -53,17 +53,16 @@ pub struct NodeKeyParams { /// /// The secret key of the node is obtained as follows: /// - /// * If the `--node-key` option is given, the value is parsed as a secret key - /// according to the type. See the documentation for `--node-key`. + /// * If the `--node-key` option is given, the value is parsed as a secret key according to + /// the type. See the documentation for `--node-key`. /// - /// * If the `--node-key-file` option is given, the secret key is read from the - /// specified file. See the documentation for `--node-key-file`. + /// * If the `--node-key-file` option is given, the secret key is read from the specified + /// file. See the documentation for `--node-key-file`. /// - /// * Otherwise, the secret key is read from a file with a predetermined, - /// type-specific name from the chain-specific network config directory - /// inside the base directory specified by `--base-dir`. If this file does - /// not exist, it is created with a newly generated secret key of the - /// chosen type. + /// * Otherwise, the secret key is read from a file with a predetermined, type-specific name + /// from the chain-specific network config directory inside the base directory specified by + /// `--base-dir`. If this file does not exist, it is created with a newly generated secret + /// key of the chosen type. /// /// The node's secret key determines the corresponding public key and hence the /// node's peer ID in the context of libp2p. diff --git a/substrate/client/cli/src/params/shared_params.rs b/substrate/client/cli/src/params/shared_params.rs index 5ded5846e3..41472387d2 100644 --- a/substrate/client/cli/src/params/shared_params.rs +++ b/substrate/client/cli/src/params/shared_params.rs @@ -26,8 +26,8 @@ use structopt::StructOpt; pub struct SharedParams { /// Specify the chain specification. /// - /// It can be one of the predefined ones (dev, local, or staging) or it can be a path to a file with - /// the chainspec (such as one exported by the `build-spec` subcommand). + /// It can be one of the predefined ones (dev, local, or staging) or it can be a path to a file + /// with the chainspec (such as one exported by the `build-spec` subcommand). #[structopt(long, value_name = "CHAIN_SPEC")] pub chain: Option, diff --git a/substrate/client/consensus/aura/src/lib.rs b/substrate/client/consensus/aura/src/lib.rs index d9c089b956..d038db97cb 100644 --- a/substrate/client/consensus/aura/src/lib.rs +++ b/substrate/client/consensus/aura/src/lib.rs @@ -143,8 +143,8 @@ pub struct StartAuraParams { /// The proportion of the slot dedicated to proposing. /// /// The block proposing will be limited to this proportion of the slot from the starting of the - /// slot. However, the proposing can still take longer when there is some lenience factor applied, - /// because there were no blocks produced for some slots. + /// slot. However, the proposing can still take longer when there is some lenience factor + /// applied, because there were no blocks produced for some slots. pub block_proposal_slot_portion: SlotProportion, /// The maximum proportion of the slot dedicated to proposing with any lenience factor applied /// due to no blocks being produced. @@ -237,8 +237,8 @@ pub struct BuildAuraWorkerParams { /// The proportion of the slot dedicated to proposing. /// /// The block proposing will be limited to this proportion of the slot from the starting of the - /// slot. However, the proposing can still take longer when there is some lenience factor applied, - /// because there were no blocks produced for some slots. + /// slot. However, the proposing can still take longer when there is some lenience factor + /// applied, because there were no blocks produced for some slots. pub block_proposal_slot_portion: SlotProportion, /// The maximum proportion of the slot dedicated to proposing with any lenience factor applied /// due to no blocks being produced. diff --git a/substrate/client/consensus/babe/src/lib.rs b/substrate/client/consensus/babe/src/lib.rs index d5caf36542..21fba61866 100644 --- a/substrate/client/consensus/babe/src/lib.rs +++ b/substrate/client/consensus/babe/src/lib.rs @@ -430,8 +430,8 @@ pub struct BabeParams { /// The proportion of the slot dedicated to proposing. /// /// The block proposing will be limited to this proportion of the slot from the starting of the - /// slot. However, the proposing can still take longer when there is some lenience factor applied, - /// because there were no blocks produced for some slots. + /// slot. However, the proposing can still take longer when there is some lenience factor + /// applied, because there were no blocks produced for some slots. pub block_proposal_slot_portion: SlotProportion, /// The maximum proportion of the slot dedicated to proposing with any lenience factor applied diff --git a/substrate/client/consensus/common/src/block_import.rs b/substrate/client/consensus/common/src/block_import.rs index 83fb11834d..d16d71aec9 100644 --- a/substrate/client/consensus/common/src/block_import.rs +++ b/substrate/client/consensus/common/src/block_import.rs @@ -250,8 +250,8 @@ impl BlockImportParams { /// Auxiliary function for "converting" the transaction type. /// - /// Actually this just sets `StorageChanges::Changes` to `None` and makes rustc think that `Self` now - /// uses a different transaction type. + /// Actually this just sets `StorageChanges::Changes` to `None` and makes rustc think that + /// `Self` now uses a different transaction type. pub fn clear_storage_changes_and_mutate( self, ) -> BlockImportParams { diff --git a/substrate/client/consensus/common/src/shared_data.rs b/substrate/client/consensus/common/src/shared_data.rs index e1797bc6f5..7a25660e08 100644 --- a/substrate/client/consensus/common/src/shared_data.rs +++ b/substrate/client/consensus/common/src/shared_data.rs @@ -54,10 +54,11 @@ impl Drop for SharedDataLockedUpgradable { /// Created by [`SharedData::shared_data_locked`]. /// /// As long as this object isn't dropped, the shared data is held in a mutex guard and the shared -/// data is tagged as locked. Access to the shared data is provided through [`Deref`](std::ops::Deref) and -/// [`DerefMut`](std::ops::DerefMut). The trick is to use [`Self::release_mutex`] to release the mutex, but still keep -/// the shared data locked. This means every other thread trying to access the shared data in this -/// time will need to wait until this lock is freed. +/// data is tagged as locked. Access to the shared data is provided through +/// [`Deref`](std::ops::Deref) and [`DerefMut`](std::ops::DerefMut). The trick is to use +/// [`Self::release_mutex`] to release the mutex, but still keep the shared data locked. This means +/// every other thread trying to access the shared data in this time will need to wait until this +/// lock is freed. /// /// If this object is dropped without calling [`Self::release_mutex`], the lock will be dropped /// immediately. @@ -210,8 +211,8 @@ impl SharedData { /// /// This will give mutable access to the shared data. The returned [`SharedDataLocked`] /// provides the function [`SharedDataLocked::release_mutex`] to release the mutex, but - /// keeping the data locked. This is useful in async contexts for example where the data needs to - /// be locked, but a mutex guard can not be held. + /// keeping the data locked. This is useful in async contexts for example where the data needs + /// to be locked, but a mutex guard can not be held. /// /// For an example see [`SharedData`]. pub fn shared_data_locked(&self) -> SharedDataLocked { diff --git a/substrate/client/consensus/epochs/src/lib.rs b/substrate/client/consensus/epochs/src/lib.rs index 52327dbbf6..685a5c26d0 100644 --- a/substrate/client/consensus/epochs/src/lib.rs +++ b/substrate/client/consensus/epochs/src/lib.rs @@ -615,7 +615,8 @@ where &self.inner } - /// Reset to a specified pair of epochs, as if they were announced at blocks `parent_hash` and `hash`. + /// Reset to a specified pair of epochs, as if they were announced at blocks `parent_hash` and + /// `hash`. pub fn reset(&mut self, parent_hash: Hash, hash: Hash, number: Number, current: E, next: E) { self.inner = ForkTree::new(); self.epochs.clear(); diff --git a/substrate/client/consensus/manual-seal/src/consensus/babe.rs b/substrate/client/consensus/manual-seal/src/consensus/babe.rs index d18170e9a0..1d3afe392d 100644 --- a/substrate/client/consensus/manual-seal/src/consensus/babe.rs +++ b/substrate/client/consensus/manual-seal/src/consensus/babe.rs @@ -209,8 +209,9 @@ where { vec![ as CompatibleDigestItem>::babe_pre_digest(predigest)] } else { - // well we couldn't claim a slot because this is an existing chain and we're not in the authorities. - // we need to tell BabeBlockImport that the epoch has changed, and we put ourselves in the authorities. + // well we couldn't claim a slot because this is an existing chain and we're not in the + // authorities. we need to tell BabeBlockImport that the epoch has changed, and we put + // ourselves in the authorities. let predigest = PreDigest::SecondaryPlain(SecondaryPlainPreDigest { slot, authority_index: 0_u32 }); diff --git a/substrate/client/consensus/manual-seal/src/lib.rs b/substrate/client/consensus/manual-seal/src/lib.rs index 4f23bdcf65..f6994e4520 100644 --- a/substrate/client/consensus/manual-seal/src/lib.rs +++ b/substrate/client/consensus/manual-seal/src/lib.rs @@ -94,8 +94,8 @@ pub struct ManualSealParams, TP, SC, C /// Shared reference to the transaction pool. pub pool: Arc, - /// Stream, Basically the receiving end of a channel for sending commands to - /// the authorship task. + /// Stream, Basically the receiving end of a channel for sending + /// commands to the authorship task. pub commands_stream: CS, /// SelectChain strategy. @@ -281,7 +281,8 @@ mod tests { 0, )); let env = ProposerFactory::new(spawner.clone(), client.clone(), pool.clone(), None, None); - // this test checks that blocks are created as soon as transactions are imported into the pool. + // this test checks that blocks are created as soon as transactions are imported into the + // pool. let (sender, receiver) = futures::channel::oneshot::channel(); let mut sender = Arc::new(Some(sender)); let commands_stream = @@ -350,7 +351,8 @@ mod tests { 0, )); let env = ProposerFactory::new(spawner.clone(), client.clone(), pool.clone(), None, None); - // this test checks that blocks are created as soon as an engine command is sent over the stream. + // this test checks that blocks are created as soon as an engine command is sent over the + // stream. let (mut sink, commands_stream) = futures::channel::mpsc::channel(1024); let future = run_manual_seal(ManualSealParams { block_import: client.clone(), @@ -427,7 +429,8 @@ mod tests { 0, )); let env = ProposerFactory::new(spawner.clone(), client.clone(), pool.clone(), None, None); - // this test checks that blocks are created as soon as an engine command is sent over the stream. + // this test checks that blocks are created as soon as an engine command is sent over the + // stream. let (mut sink, commands_stream) = futures::channel::mpsc::channel(1024); let future = run_manual_seal(ManualSealParams { block_import: client.clone(), diff --git a/substrate/client/consensus/pow/src/lib.rs b/substrate/client/consensus/pow/src/lib.rs index c2305180ca..1b8a622566 100644 --- a/substrate/client/consensus/pow/src/lib.rs +++ b/substrate/client/consensus/pow/src/lib.rs @@ -591,8 +591,8 @@ where return } - // The worker is locked for the duration of the whole proposing period. Within this period, - // the mining target is outdated and useless anyway. + // The worker is locked for the duration of the whole proposing period. Within this + // period, the mining target is outdated and useless anyway. let difficulty = match algorithm.difficulty(best_hash) { Ok(x) => x, diff --git a/substrate/client/consensus/slots/src/lib.rs b/substrate/client/consensus/slots/src/lib.rs index 1aa8d984d3..da04b98cce 100644 --- a/substrate/client/consensus/slots/src/lib.rs +++ b/substrate/client/consensus/slots/src/lib.rs @@ -428,7 +428,8 @@ impl + Send> SlotWorker Timestamp; /// The current slot that will be found in the [`InherentData`](`sp_inherents::InherentData`). @@ -1059,7 +1060,8 @@ mod test { }) .collect(); - // Should always be true after a short while, since the chain is advancing but finality is stalled + // Should always be true after a short while, since the chain is advancing but finality is + // stalled let expected: Vec = (slot_now..300).map(|s| s > 8).collect(); assert_eq!(should_backoff, expected); } diff --git a/substrate/client/db/src/cache/list_cache.rs b/substrate/client/db/src/cache/list_cache.rs index 1808d431dd..795cb8f901 100644 --- a/substrate/client/db/src/cache/list_cache.rs +++ b/substrate/client/db/src/cache/list_cache.rs @@ -178,8 +178,8 @@ impl> ListCache } else { // there are unfinalized entries // => find the fork containing given block and read from this fork - // IF there's no matching fork, ensure that this isn't a block from a fork that has forked - // behind the best finalized block and search at finalized fork + // IF there's no matching fork, ensure that this isn't a block from a fork that has + // forked behind the best finalized block and search at finalized fork match self.find_unfinalized_fork(&at)? { Some(fork) => Some(&fork.head), @@ -316,7 +316,8 @@ impl> ListCache return Ok(None) } - // if the block is not final, it is possibly appended to/forking from existing unfinalized fork + // if the block is not final, it is possibly appended to/forking from existing unfinalized + // fork let is_final = entry_type == EntryType::Final || entry_type == EntryType::Genesis; if !is_final { let mut fork_and_action = None; @@ -392,9 +393,10 @@ impl> ListCache } // if we're here, then one of following is true: - // - either we're inserting final block => all ancestors are already finalized AND the only thing we can do - // is to try to update last finalized entry - // - either we're inserting non-final blocks that has no ancestors in any known unfinalized forks + // - either we're inserting final block => all ancestors are already finalized AND the only + // thing we can do is to try to update last finalized entry + // - either we're inserting non-final blocks that has no ancestors in any known unfinalized + // forks let new_storage_entry = match self.best_finalized_entry.as_ref() { Some(best_finalized_entry) => best_finalized_entry.try_update(value), @@ -1015,8 +1017,8 @@ mod tests { .value_at_block(&ComplexBlockId::new(H256::from_low_u64_be(2), 100)) .is_err()); - // when block is later than last finalized block AND there are no forks AND finalized value is Some - // ---> [100] --- 200 + // when block is later than last finalized block AND there are no forks AND finalized value + // is Some ---> [100] --- 200 assert_eq!( ListCache::new( DummyStorage::new() @@ -1088,8 +1090,8 @@ mod tests { None ); - // when block is later than last finalized block AND it appends to unfinalized fork from the end - // AND unfinalized value is Some + // when block is later than last finalized block AND it appends to unfinalized fork from the + // end AND unfinalized value is Some // ---> [2] ---> [4] ---> 5 assert_eq!( ListCache::new( @@ -1170,8 +1172,8 @@ mod tests { .unwrap() .is_none()); - // when trying to insert non-final block AND it appends to the best block of unfinalized fork - // AND new value is the same as in the fork' best block + // when trying to insert non-final block AND it appends to the best block of unfinalized + // fork AND new value is the same as in the fork' best block let mut cache = ListCache::new( DummyStorage::new() .with_meta(None, vec![test_id(4)]) @@ -1198,8 +1200,8 @@ mod tests { assert!(tx.inserted_entries().is_empty()); assert!(tx.removed_entries().is_empty()); assert!(tx.updated_meta().is_none()); - // when trying to insert non-final block AND it appends to the best block of unfinalized fork - // AND new value is the same as in the fork' best block + // when trying to insert non-final block AND it appends to the best block of unfinalized + // fork AND new value is the same as in the fork' best block let mut tx = DummyTransaction::new(); assert_eq!( cache @@ -1221,8 +1223,8 @@ mod tests { Some(Metadata { finalized: None, unfinalized: vec![test_id(5)] }) ); - // when trying to insert non-final block AND it is the first block that appends to the best block of unfinalized fork - // AND new value is the same as in the fork' best block + // when trying to insert non-final block AND it is the first block that appends to the best + // block of unfinalized fork AND new value is the same as in the fork' best block let cache = ListCache::new( DummyStorage::new() .with_meta(None, vec![correct_id(4)]) @@ -1249,8 +1251,8 @@ mod tests { assert!(tx.inserted_entries().is_empty()); assert!(tx.removed_entries().is_empty()); assert!(tx.updated_meta().is_none()); - // when trying to insert non-final block AND it is the first block that appends to the best block of unfinalized fork - // AND new value is the same as in the fork' best block + // when trying to insert non-final block AND it is the first block that appends to the best + // block of unfinalized fork AND new value is the same as in the fork' best block let mut tx = DummyTransaction::new(); assert_eq!( cache @@ -2204,7 +2206,8 @@ mod tests { cache.prune_finalized_entries(&mut tx, &test_id(20)); assert!(tx.removed_entries().is_empty()); assert!(tx.inserted_entries().is_empty()); - // when finalizing entry #30: entry 10 pruned + entry 20 is truncated (if pruning is enabled) + // when finalizing entry #30: entry 10 pruned + entry 20 is truncated (if pruning is + // enabled) cache.prune_finalized_entries(&mut tx, &test_id(30)); match strategy { PruningStrategy::NeverPrune => { diff --git a/substrate/client/db/src/changes_tries_storage.rs b/substrate/client/db/src/changes_tries_storage.rs index c064985316..3a3c591853 100644 --- a/substrate/client/db/src/changes_tries_storage.rs +++ b/substrate/client/db/src/changes_tries_storage.rs @@ -59,8 +59,8 @@ pub fn extract_new_configuration( .and_then(ChangesTrieSignal::as_new_configuration) } -/// Opaque configuration cache transaction. During its lifetime, no-one should modify cache. This is currently -/// guaranteed because import lock is held during block import/finalization. +/// Opaque configuration cache transaction. During its lifetime, no-one should modify cache. This is +/// currently guaranteed because import lock is held during block import/finalization. pub struct DbChangesTrieStorageTransaction { /// Cache operations that must be performed after db transaction is committed. cache_ops: DbCacheTransactionOps, @@ -110,12 +110,13 @@ struct ChangesTriesMeta { /// The range is inclusive from both sides. /// Is None only if: /// 1) we haven't yet finalized any blocks (except genesis) - /// 2) if best_finalized_block - min_blocks_to_keep points to the range where changes tries are disabled - /// 3) changes tries pruning is disabled + /// 2) if best_finalized_block - min_blocks_to_keep points to the range where changes tries are + /// disabled 3) changes tries pruning is disabled pub oldest_digest_range: Option<(NumberFor, NumberFor)>, /// End block (inclusive) of oldest pruned max-level (or skewed) digest trie blocks range. /// It is guaranteed that we have no any changes tries before (and including) this block. - /// It is guaranteed that all existing changes tries after this block are not yet pruned (if created). + /// It is guaranteed that all existing changes tries after this block are not yet pruned (if + /// created). pub oldest_pruned_digest_range_end: NumberFor, } @@ -1131,8 +1132,8 @@ mod tests { vec![3, 3], ); - // after truncating block2_1 && block2_2 - there are still two unfinalized forks (cache impl specifics), - // the 1st one points to the block #3 because it isn't truncated + // after truncating block2_1 && block2_2 - there are still two unfinalized forks (cache impl + // specifics), the 1st one points to the block #3 because it isn't truncated backend.revert(1, false).unwrap(); assert_eq!( backend diff --git a/substrate/client/db/src/lib.rs b/substrate/client/db/src/lib.rs index b909b52610..9f1dd4c0ec 100644 --- a/substrate/client/db/src/lib.rs +++ b/substrate/client/db/src/lib.rs @@ -1067,8 +1067,8 @@ impl FrozenForDuration { /// Disk backend. /// -/// Disk backend keeps data in a key-value store. In archive mode, trie nodes are kept from all blocks. -/// Otherwise, trie nodes are kept only from some recent blocks. +/// Disk backend keeps data in a key-value store. In archive mode, trie nodes are kept from all +/// blocks. Otherwise, trie nodes are kept only from some recent blocks. pub struct Backend { storage: Arc>, offchain_storage: offchain::LocalStorage, @@ -1459,8 +1459,9 @@ impl Backend { if operation.commit_state { transaction.set_from_vec(columns::META, meta_keys::FINALIZED_STATE, lookup_key); } else { - // When we don't want to commit the genesis state, we still preserve it in memory - // to bootstrap consensus. It is queried for an initial list of authorities, etc. + // When we don't want to commit the genesis state, we still preserve it in + // memory to bootstrap consensus. It is queried for an initial list of + // authorities, etc. *self.genesis_state.write() = Some(Arc::new(DbGenesisStorage::new( pending_block.header.state_root().clone(), operation.db_updates.clone(), @@ -3403,7 +3404,8 @@ pub(crate) mod tests { let block5 = insert_header(&backend, 5, block4, None, Default::default()); assert_eq!(backend.blockchain().info().best_hash, block5); - // Insert 1 as best again. This should fail because canonicalization_delay == 3 and best == 5 + // Insert 1 as best again. This should fail because canonicalization_delay == 3 and best == + // 5 let header = Header { number: 1, parent_hash: block0, diff --git a/substrate/client/db/src/light.rs b/substrate/client/db/src/light.rs index 0ad8224f02..d56188b70f 100644 --- a/substrate/client/db/src/light.rs +++ b/substrate/client/db/src/light.rs @@ -829,8 +829,8 @@ pub(crate) mod tests { assert_eq!(raw_db.count(columns::HEADER), 1 + ucht_size + ucht_size); assert_eq!(raw_db.count(columns::CHT), 0); - // insert block #{2 * cht::size() + 1} && check that new CHT is created + headers of this CHT are pruned - // nothing is yet finalized, so nothing is pruned. + // insert block #{2 * cht::size() + 1} && check that new CHT is created + headers of + // this CHT are pruned nothing is yet finalized, so nothing is pruned. prev_hash = insert_block(&db, HashMap::new(), || { header_producer(&prev_hash, 1 + cht_size + cht_size) }); diff --git a/substrate/client/db/src/storage_cache.rs b/substrate/client/db/src/storage_cache.rs index d5aa43e8ba..3193d34796 100644 --- a/substrate/client/db/src/storage_cache.rs +++ b/substrate/client/db/src/storage_cache.rs @@ -366,8 +366,8 @@ impl CacheChanges { } cache.sync(&enacted, &retracted); // Propagate cache only if committing on top of the latest canonical state - // blocks are ordered by number and only one block with a given number is marked as canonical - // (contributed to canonical state cache) + // blocks are ordered by number and only one block with a given number is marked as + // canonical (contributed to canonical state cache) if let Some(_) = self.parent_hash { let mut local_cache = self.local_cache.write(); if is_best { @@ -463,8 +463,8 @@ impl>, B: BlockT> CachingState { } } - /// Check if the key can be returned from cache by matching current block parent hash against canonical - /// state and filtering out entries modified in later blocks. + /// Check if the key can be returned from cache by matching current block parent hash against + /// canonical state and filtering out entries modified in later blocks. fn is_allowed( key: Option<&[u8]>, child_key: Option<&ChildStorageKey>, diff --git a/substrate/client/db/src/utils.rs b/substrate/client/db/src/utils.rs index 95cf698c24..48aaf66948 100644 --- a/substrate/client/db/src/utils.rs +++ b/substrate/client/db/src/utils.rs @@ -306,7 +306,8 @@ fn open_kvdb_rocksdb( ) -> OpenDbResult { // first upgrade database to required version match crate::upgrade::upgrade_db::(&path, db_type) { - // in case of missing version file, assume that database simply does not exist at given location + // in case of missing version file, assume that database simply does not exist at given + // location Ok(_) | Err(crate::upgrade::UpgradeError::MissingDatabaseVersionFile) => (), Err(err) => return Err(io::Error::new(io::ErrorKind::Other, err.to_string()).into()), } diff --git a/substrate/client/executor/common/src/runtime_blob/mod.rs b/substrate/client/executor/common/src/runtime_blob/mod.rs index 43d6e5e7a0..1af2708d3e 100644 --- a/substrate/client/executor/common/src/runtime_blob/mod.rs +++ b/substrate/client/executor/common/src/runtime_blob/mod.rs @@ -26,27 +26,28 @@ //! //! To give you some examples: //! -//! - wasmi allows reaching to non-exported mutable globals so that we could reset them. -//! Wasmtime doesn’t support that. +//! - wasmi allows reaching to non-exported mutable globals so that we could reset them. Wasmtime +//! doesn’t support that. //! //! We need to reset the globals because when we //! execute the Substrate Runtime, we do not drop and create the instance anew, instead //! we restore some selected parts of the state. //! -//! - stack depth metering can be performed via instrumentation or deferred to the engine and say -//! be added directly in machine code. Implementing this in machine code is rather cumbersome so +//! - stack depth metering can be performed via instrumentation or deferred to the engine and say be +//! added directly in machine code. Implementing this in machine code is rather cumbersome so //! instrumentation looks like a good solution. //! //! Stack depth metering is needed to make a wasm blob -//! execution deterministic, which in turn is needed by the Parachain Validation Function in Polkadot. +//! execution deterministic, which in turn is needed by the Parachain Validation Function in +//! Polkadot. //! //! ## Inspection //! //! Inspection of a wasm module may be needed to extract some useful information, such as to extract //! data segment snapshot, which is helpful for quickly restoring the initial state of instances. //! Inspection can be also useful to prove that a wasm module possesses some properties, such as, -//! is free of any floating point operations, which is a useful step towards making instances produced -//! from such a module deterministic. +//! is free of any floating point operations, which is a useful step towards making instances +//! produced from such a module deterministic. mod data_segments_snapshot; mod globals_snapshot; diff --git a/substrate/client/executor/common/src/runtime_blob/runtime_blob.rs b/substrate/client/executor/common/src/runtime_blob/runtime_blob.rs index b7f7119344..6fb9303e07 100644 --- a/substrate/client/executor/common/src/runtime_blob/runtime_blob.rs +++ b/substrate/client/executor/common/src/runtime_blob/runtime_blob.rs @@ -72,11 +72,13 @@ impl RuntimeBlob { export_mutable_globals(&mut self.raw_module, "exported_internal_global"); } - /// Run a pass that instrument this module so as to introduce a deterministic stack height limit. + /// Run a pass that instrument this module so as to introduce a deterministic stack height + /// limit. /// /// It will introduce a global mutable counter. The instrumentation will increase the counter /// according to the "cost" of the callee. If the cost exceeds the `stack_depth_limit` constant, - /// the instrumentation will trap. The counter will be decreased as soon as the the callee returns. + /// the instrumentation will trap. The counter will be decreased as soon as the the callee + /// returns. /// /// The stack cost of a function is computed based on how much locals there are and the maximum /// depth of the wasm operand stack. @@ -89,7 +91,8 @@ impl RuntimeBlob { Ok(Self { raw_module: injected_module }) } - /// Perform an instrumentation that makes sure that a specific function `entry_point` is exported + /// Perform an instrumentation that makes sure that a specific function `entry_point` is + /// exported pub fn entry_point_exists(&self, entry_point: &str) -> bool { self.raw_module .export_section() diff --git a/substrate/client/executor/common/src/wasm_runtime.rs b/substrate/client/executor/common/src/wasm_runtime.rs index 12ff92a2c6..eb73909d92 100644 --- a/substrate/client/executor/common/src/wasm_runtime.rs +++ b/substrate/client/executor/common/src/wasm_runtime.rs @@ -98,7 +98,8 @@ pub trait WasmInstance: Send { /// /// This is meant to be the starting address of the memory mapped area for the linear memory. /// - /// This function is intended only for a specific test that measures physical memory consumption. + /// This function is intended only for a specific test that measures physical memory + /// consumption. fn linear_memory_base_ptr(&self) -> Option<*const u8> { None } diff --git a/substrate/client/executor/src/native_executor.rs b/substrate/client/executor/src/native_executor.rs index 51b9a404bb..9faa645218 100644 --- a/substrate/client/executor/src/native_executor.rs +++ b/substrate/client/executor/src/native_executor.rs @@ -197,8 +197,8 @@ impl WasmExecutor { /// The runtime is passed as a [`RuntimeBlob`]. The runtime will be isntantiated with the /// parameters this `WasmExecutor` was initialized with. /// - /// In case of problems with during creation of the runtime or instantation, a `Err` is returned. - /// that describes the message. + /// In case of problems with during creation of the runtime or instantation, a `Err` is + /// returned. that describes the message. #[doc(hidden)] // We use this function for tests across multiple crates. pub fn uncached_call( &self, @@ -456,8 +456,8 @@ impl RuntimeSpawn for RuntimeInstanceSpawn { let _ = sender.send(output); }, Err(error) => { - // If execution is panicked, the `join` in the original runtime code will panic as well, - // since the sender is dropped without sending anything. + // If execution is panicked, the `join` in the original runtime code will + // panic as well, since the sender is dropped without sending anything. log::error!("Call error in spawned task: {:?}", error); }, } diff --git a/substrate/client/executor/src/wasm_runtime.rs b/substrate/client/executor/src/wasm_runtime.rs index c55af60b70..892c3681c7 100644 --- a/substrate/client/executor/src/wasm_runtime.rs +++ b/substrate/client/executor/src/wasm_runtime.rs @@ -304,8 +304,8 @@ pub fn create_wasm_runtime_with_code( WasmExecutionMethod::Interpreted => { // Wasmi doesn't have any need in a cache directory. // - // We drop the cache_path here to silence warnings that cache_path is not used if compiling - // without the `wasmtime` flag. + // We drop the cache_path here to silence warnings that cache_path is not used if + // compiling without the `wasmtime` flag. drop(cache_path); sc_executor_wasmi::create_runtime( @@ -361,8 +361,8 @@ fn decode_runtime_apis(apis: &[u8]) -> Result, WasmError> { apis.chunks(RUNTIME_API_INFO_SIZE) .map(|chunk| { - // `chunk` can be less than `RUNTIME_API_INFO_SIZE` if the total length of `apis` doesn't - // completely divide by `RUNTIME_API_INFO_SIZE`. + // `chunk` can be less than `RUNTIME_API_INFO_SIZE` if the total length of `apis` + // doesn't completely divide by `RUNTIME_API_INFO_SIZE`. <[u8; RUNTIME_API_INFO_SIZE]>::try_from(chunk) .map(sp_api::deserialize_runtime_api_info) .map_err(|_| WasmError::Other("a clipped runtime api info declaration".to_owned())) @@ -370,8 +370,8 @@ fn decode_runtime_apis(apis: &[u8]) -> Result, WasmError> { .collect::, WasmError>>() } -/// Take the runtime blob and scan it for the custom wasm sections containing the version information -/// and construct the `RuntimeVersion` from them. +/// Take the runtime blob and scan it for the custom wasm sections containing the version +/// information and construct the `RuntimeVersion` from them. /// /// If there are no such sections, it returns `None`. If there is an error during decoding those /// sections, `Err` will be returned. @@ -380,8 +380,8 @@ pub fn read_embedded_version(blob: &RuntimeBlob) -> Result = read_embedded_version(&blob)?; let runtime = create_wasm_runtime_with_code( @@ -429,7 +430,8 @@ fn create_versioned_wasm_runtime( if version.is_none() { // Call to determine runtime version. let version_result = { - // `ext` is already implicitly handled as unwind safe, as we store it in a global variable. + // `ext` is already implicitly handled as unwind safe, as we store it in a global + // variable. let mut ext = AssertUnwindSafe(ext); // The following unwind safety assertion is OK because if the method call panics, the diff --git a/substrate/client/executor/wasmi/src/lib.rs b/substrate/client/executor/wasmi/src/lib.rs index d11d867e9a..cc6a05fccf 100644 --- a/substrate/client/executor/wasmi/src/lib.rs +++ b/substrate/client/executor/wasmi/src/lib.rs @@ -687,7 +687,8 @@ pub struct WasmiInstance { missing_functions: Vec, } -// This is safe because `WasmiInstance` does not leak any references to `self.memory` and `self.instance` +// This is safe because `WasmiInstance` does not leak any references to `self.memory` and +// `self.instance` unsafe impl Send for WasmiInstance {} impl WasmInstance for WasmiInstance { diff --git a/substrate/client/executor/wasmtime/src/instance_wrapper.rs b/substrate/client/executor/wasmtime/src/instance_wrapper.rs index 797fe30690..23a9122045 100644 --- a/substrate/client/executor/wasmtime/src/instance_wrapper.rs +++ b/substrate/client/executor/wasmtime/src/instance_wrapper.rs @@ -98,8 +98,8 @@ pub struct InstanceWrapper { instance: Instance, // The memory instance of the `instance`. // - // It is important to make sure that we don't make any copies of this to make it easier to proof - // See `memory_as_slice` and `memory_as_slice_mut`. + // It is important to make sure that we don't make any copies of this to make it easier to + // proof See `memory_as_slice` and `memory_as_slice_mut`. memory: Memory, table: Option, // Make this struct explicitly !Send & !Sync. @@ -399,9 +399,9 @@ impl InstanceWrapper { self.memory.data_ptr() } - /// Removes physical backing from the allocated linear memory. This leads to returning the memory - /// back to the system. While the memory is zeroed this is considered as a side-effect and is not - /// relied upon. Thus this function acts as a hint. + /// Removes physical backing from the allocated linear memory. This leads to returning the + /// memory back to the system. While the memory is zeroed this is considered as a side-effect + /// and is not relied upon. Thus this function acts as a hint. pub fn decommit(&self) { if self.memory.data_size() == 0 { return diff --git a/substrate/client/executor/wasmtime/src/runtime.rs b/substrate/client/executor/wasmtime/src/runtime.rs index d4a2a28394..f80d8c8e5b 100644 --- a/substrate/client/executor/wasmtime/src/runtime.rs +++ b/substrate/client/executor/wasmtime/src/runtime.rs @@ -100,8 +100,8 @@ impl WasmModule for WasmtimeRuntime { // and results. // // NOTE: Attentive reader may notice that this could've been moved in `WasmModule` creation. - // However, I am not sure if that's a good idea since it would be pushing our luck further - // by assuming that `Store` not only `Send` but also `Sync`. + // However, I am not sure if that's a good idea since it would be pushing our luck + // further by assuming that `Store` not only `Send` but also `Sync`. let imports = resolve_imports( &store, &self.module, @@ -115,10 +115,10 @@ impl WasmModule for WasmtimeRuntime { InstanceWrapper::new(&store, &self.module, &imports, self.config.heap_pages)?; let heap_base = instance_wrapper.extract_heap_base()?; - // This function panics if the instance was created from a runtime blob different from which - // the mutable globals were collected. Here, it is easy to see that there is only a single - // runtime blob and thus it's the same that was used for both creating the instance and - // collecting the mutable globals. + // This function panics if the instance was created from a runtime blob different from + // which the mutable globals were collected. Here, it is easy to see that there is only + // a single runtime blob and thus it's the same that was used for both creating the + // instance and collecting the mutable globals. let globals_snapshot = GlobalsSnapshot::take(&snapshot_data.mutable_globals, &instance_wrapper); @@ -291,10 +291,10 @@ fn common_config(semantics: &Semantics) -> std::result::Result { // some instrumentations for both anticipated paths: substrate execution and PVF execution. // // Should there raise a need in performing no instrumentation and the client doesn't need - // to do any checks, then we can provide a `Cow` like semantics here: if we need the blob and - // the user got `RuntimeBlob` then extract it, or otherwise create it from the given + // to do any checks, then we can provide a `Cow` like semantics here: if we need the blob + // and the user got `RuntimeBlob` then extract it, or otherwise create it from the given // bytecode. blob: RuntimeBlob, }, /// The code is supplied in a form of a compiled artifact. /// - /// This assumes that the code is already prepared for execution and the same `Config` was used. + /// This assumes that the code is already prepared for execution and the same `Config` was + /// used. Artifact { compiled_artifact: &'a [u8] }, } @@ -430,11 +431,12 @@ pub fn create_runtime( /// /// # Safety /// -/// The caller must ensure that the compiled artifact passed here was produced by [`prepare_runtime_artifact`]. -/// Otherwise, there is a risk of arbitrary code execution with all implications. +/// The caller must ensure that the compiled artifact passed here was produced by +/// [`prepare_runtime_artifact`]. Otherwise, there is a risk of arbitrary code execution with all +/// implications. /// -/// It is ok though if the `compiled_artifact` was created by code of another version or with different -/// configuration flags. In such case the caller will receive an `Err` deterministically. +/// It is ok though if the `compiled_artifact` was created by code of another version or with +/// different configuration flags. In such case the caller will receive an `Err` deterministically. pub unsafe fn create_runtime_from_artifact( compiled_artifact: &[u8], config: Config, @@ -445,8 +447,8 @@ pub unsafe fn create_runtime_from_artifact( /// # Safety /// -/// This is only unsafe if called with [`CodeSupplyMode::Artifact`]. See [`create_runtime_from_artifact`] -/// to get more details. +/// This is only unsafe if called with [`CodeSupplyMode::Artifact`]. See +/// [`create_runtime_from_artifact`] to get more details. unsafe fn do_create_runtime( code_supply_mode: CodeSupplyMode<'_>, config: Config, diff --git a/substrate/client/executor/wasmtime/src/util.rs b/substrate/client/executor/wasmtime/src/util.rs index c294f66b50..3109a76a9a 100644 --- a/substrate/client/executor/wasmtime/src/util.rs +++ b/substrate/client/executor/wasmtime/src/util.rs @@ -44,7 +44,8 @@ pub fn from_wasmtime_val(val: wasmtime::Val) -> Value { } } -/// Converts a sp_wasm_interface's [`Value`] into the corresponding variant in wasmtime's [`wasmtime::Val`]. +/// Converts a sp_wasm_interface's [`Value`] into the corresponding variant in wasmtime's +/// [`wasmtime::Val`]. pub fn into_wasmtime_val(value: Value) -> wasmtime::Val { match value { Value::I32(v) => wasmtime::Val::I32(v), diff --git a/substrate/client/finality-grandpa/src/authorities.rs b/substrate/client/finality-grandpa/src/authorities.rs index 6f958bef0a..6e5dfdd05e 100644 --- a/substrate/client/finality-grandpa/src/authorities.rs +++ b/substrate/client/finality-grandpa/src/authorities.rs @@ -165,8 +165,8 @@ pub struct AuthoritySet { /// is lower than the last finalized block (as signaled in the forced /// change) must be applied beforehand. pending_forced_changes: Vec>, - /// Track at which blocks the set id changed. This is useful when we need to prove finality for a - /// given block since we can figure out what set the block belongs to and when the set + /// Track at which blocks the set id changed. This is useful when we need to prove finality for + /// a given block since we can figure out what set the block belongs to and when the set /// started/ended. authority_set_changes: AuthoritySetChanges, } @@ -657,16 +657,16 @@ impl + Clone> PendingChange { pub struct AuthoritySetChanges(Vec<(u64, N)>); /// The response when querying for a set id for a specific block. Either we get a set id -/// together with a block number for the last block in the set, or that the requested block is in the -/// latest set, or that we don't know what set id the given block belongs to. +/// together with a block number for the last block in the set, or that the requested block is in +/// the latest set, or that we don't know what set id the given block belongs to. #[derive(Debug, PartialEq)] pub enum AuthoritySetChangeId { /// The requested block is in the latest set. Latest, /// Tuple containing the set id and the last block number of that set. Set(SetId, N), - /// We don't know which set id the request block belongs to (this can only happen due to missing - /// data). + /// We don't know which set id the request block belongs to (this can only happen due to + /// missing data). Unknown, } @@ -912,7 +912,8 @@ mod tests { assert_eq!(authorities.pending_changes().collect::>(), vec![&change_a, &change_b]); - // finalizing "hash_c" won't enact the change signaled at "hash_a" but it will prune out "hash_b" + // finalizing "hash_c" won't enact the change signaled at "hash_a" but it will prune out + // "hash_b" let status = authorities .apply_standard_changes( "hash_c", diff --git a/substrate/client/finality-grandpa/src/communication/gossip.rs b/substrate/client/finality-grandpa/src/communication/gossip.rs index c3b385209b..90f40a93cb 100644 --- a/substrate/client/finality-grandpa/src/communication/gossip.rs +++ b/substrate/client/finality-grandpa/src/communication/gossip.rs @@ -483,8 +483,8 @@ struct Peers { /// gossiping. first_stage_peers: HashSet, /// The randomly picked set of peers we'll gossip to in the second stage of gossiping if the - /// first stage didn't allow us to spread the voting data enough to conclude the round. This set - /// should have size `sqrt(connected_peers)`. + /// first stage didn't allow us to spread the voting data enough to conclude the round. This + /// set should have size `sqrt(connected_peers)`. second_stage_peers: HashSet, /// The randomly picked set of `LUCKY_PEERS` light clients we'll gossip commit messages to. lucky_light_peers: HashSet, @@ -583,9 +583,11 @@ impl Peers { fn reshuffle(&mut self) { // we want to randomly select peers into three sets according to the following logic: - // - first set: LUCKY_PEERS random peers where at least LUCKY_PEERS/2 are authorities (unless + // - first set: LUCKY_PEERS random peers where at least LUCKY_PEERS/2 are authorities + // (unless // we're not connected to that many authorities) - // - second set: max(LUCKY_PEERS, sqrt(peers)) peers where at least LUCKY_PEERS are authorities. + // - second set: max(LUCKY_PEERS, sqrt(peers)) peers where at least LUCKY_PEERS are + // authorities. // - third set: LUCKY_PEERS random light client peers let shuffled_peers = { @@ -1220,8 +1222,10 @@ impl Inner { /// The initial logic for filtering round messages follows the given state /// transitions: /// - /// - State 1: allowed to LUCKY_PEERS random peers (where at least LUCKY_PEERS/2 are authorities) - /// - State 2: allowed to max(LUCKY_PEERS, sqrt(random peers)) (where at least LUCKY_PEERS are authorities) + /// - State 1: allowed to LUCKY_PEERS random peers (where at least LUCKY_PEERS/2 are + /// authorities) + /// - State 2: allowed to max(LUCKY_PEERS, sqrt(random peers)) (where at least LUCKY_PEERS are + /// authorities) /// - State 3: allowed to all peers /// /// Transitions will be triggered on repropagation attempts by the underlying gossip layer. @@ -1249,7 +1253,8 @@ impl Inner { /// The initial logic for filtering global messages follows the given state /// transitions: /// - /// - State 1: allowed to max(LUCKY_PEERS, sqrt(peers)) (where at least LUCKY_PEERS are authorities) + /// - State 1: allowed to max(LUCKY_PEERS, sqrt(peers)) (where at least LUCKY_PEERS are + /// authorities) /// - State 2: allowed to all peers /// /// We are more lenient with global messages since there should be a lot @@ -1625,7 +1630,8 @@ impl sc_network_gossip::Validator for GossipValidator return true, - Some((Some(_), _)) => return false, /* round messages don't require further checking. */ + // round messages don't require further checking. + Some((Some(_), _)) => return false, Some((None, _)) => {}, }; diff --git a/substrate/client/finality-grandpa/src/communication/mod.rs b/substrate/client/finality-grandpa/src/communication/mod.rs index 077dc6a3f9..0c1fb79c55 100644 --- a/substrate/client/finality-grandpa/src/communication/mod.rs +++ b/substrate/client/finality-grandpa/src/communication/mod.rs @@ -191,16 +191,16 @@ pub(crate) struct NetworkBridge> { neighbor_sender: periodic::NeighborPacketSender, /// `NeighborPacketWorker` processing packets sent through the `NeighborPacketSender`. - // `NetworkBridge` is required to be cloneable, thus one needs to be able to clone its children, - // thus one has to wrap `neighbor_packet_worker` with an `Arc` `Mutex`. + // `NetworkBridge` is required to be cloneable, thus one needs to be able to clone its + // children, thus one has to wrap `neighbor_packet_worker` with an `Arc` `Mutex`. neighbor_packet_worker: Arc>>, /// Receiver side of the peer report stream populated by the gossip validator, forwarded to the /// gossip engine. - // `NetworkBridge` is required to be cloneable, thus one needs to be able to clone its children, - // thus one has to wrap gossip_validator_report_stream with an `Arc` `Mutex`. Given that it is - // just an `UnboundedReceiver`, one could also switch to a multi-producer-*multi*-consumer - // channel implementation. + // `NetworkBridge` is required to be cloneable, thus one needs to be able to clone its + // children, thus one has to wrap gossip_validator_report_stream with an `Arc` `Mutex`. Given + // that it is just an `UnboundedReceiver`, one could also switch to a + // multi-producer-*multi*-consumer channel implementation. gossip_validator_report_stream: Arc>>, telemetry: Option, @@ -291,8 +291,8 @@ impl> NetworkBridge { .note_round(round, |to, neighbor| self.neighbor_sender.send(to, neighbor)); } - /// Get a stream of signature-checked round messages from the network as well as a sink for round messages to the - /// network all within the current set. + /// Get a stream of signature-checked round messages from the network as well as a sink for + /// round messages to the network all within the current set. pub(crate) fn round_communication( &self, keystore: Option, diff --git a/substrate/client/finality-grandpa/src/import.rs b/substrate/client/finality-grandpa/src/import.rs index a86421b4a0..c6bdbc0032 100644 --- a/substrate/client/finality-grandpa/src/import.rs +++ b/substrate/client/finality-grandpa/src/import.rs @@ -100,7 +100,8 @@ where let mut out = Vec::new(); let chain_info = self.inner.info(); - // request justifications for all pending changes for which change blocks have already been imported + // request justifications for all pending changes for which change blocks have already been + // imported let pending_changes: Vec<_> = self.authority_set.inner().pending_changes().cloned().collect(); diff --git a/substrate/client/finality-grandpa/src/justification.rs b/substrate/client/finality-grandpa/src/justification.rs index d051d0c44e..a852c74d9d 100644 --- a/substrate/client/finality-grandpa/src/justification.rs +++ b/substrate/client/finality-grandpa/src/justification.rs @@ -171,7 +171,8 @@ impl GrandpaJustification { match ancestry_chain.ancestry(self.commit.target_hash, signed.precommit.target_hash) { Ok(route) => { - // ancestry starts from parent hash but the precommit target hash has been visited + // ancestry starts from parent hash but the precommit target hash has been + // visited visited_hashes.insert(signed.precommit.target_hash); for hash in route { visited_hashes.insert(hash); diff --git a/substrate/client/finality-grandpa/src/observer.rs b/substrate/client/finality-grandpa/src/observer.rs index dd120fdd14..91779daf39 100644 --- a/substrate/client/finality-grandpa/src/observer.rs +++ b/substrate/client/finality-grandpa/src/observer.rs @@ -361,7 +361,8 @@ where match Future::poll(Pin::new(&mut self.observer), cx) { Poll::Pending => {}, Poll::Ready(Ok(())) => { - // observer commit stream doesn't conclude naturally; this could reasonably be an error. + // observer commit stream doesn't conclude naturally; this could reasonably be an + // error. return Poll::Ready(Ok(())) }, Poll::Ready(Err(CommandOrError::Error(e))) => { diff --git a/substrate/client/finality-grandpa/src/warp_proof.rs b/substrate/client/finality-grandpa/src/warp_proof.rs index 86b57c78a4..34eaa49cdf 100644 --- a/substrate/client/finality-grandpa/src/warp_proof.rs +++ b/substrate/client/finality-grandpa/src/warp_proof.rs @@ -188,8 +188,8 @@ impl WarpSyncProof { } /// Verifies the warp sync proof starting at the given set id and with the given authorities. - /// Verification stops when either the proof is exhausted or finality for the target header can be proven. - /// If the proof is valid the new set id and authorities is returned. + /// Verification stops when either the proof is exhausted or finality for the target header can + /// be proven. If the proof is valid the new set id and authorities is returned. fn verify( &self, set_id: SetId, diff --git a/substrate/client/informant/src/display.rs b/substrate/client/informant/src/display.rs index 76e21215c2..a41cf8e255 100644 --- a/substrate/client/informant/src/display.rs +++ b/substrate/client/informant/src/display.rs @@ -40,7 +40,6 @@ use wasm_timer::Instant; /// /// Call `InformantDisplay::new` to initialize the state, then regularly call `display` with the /// information to display. -/// pub struct InformantDisplay { /// Head of chain block number from the last time `display` has been called. /// `None` if `display` has never been called. diff --git a/substrate/client/informant/src/lib.rs b/substrate/client/informant/src/lib.rs index c7c90a626a..4f6aa2b7a3 100644 --- a/substrate/client/informant/src/lib.rs +++ b/substrate/client/informant/src/lib.rs @@ -52,11 +52,13 @@ impl Default for OutputFormat { } } -/// Marker trait for a type that implements `TransactionPool` and `MallocSizeOf` on `not(target_os = "unknown")`. +/// Marker trait for a type that implements `TransactionPool` and `MallocSizeOf` on `not(target_os = +/// "unknown")`. #[cfg(target_os = "unknown")] pub trait TransactionPoolAndMaybeMallogSizeOf: TransactionPool {} -/// Marker trait for a type that implements `TransactionPool` and `MallocSizeOf` on `not(target_os = "unknown")`. +/// Marker trait for a type that implements `TransactionPool` and `MallocSizeOf` on `not(target_os = +/// "unknown")`. #[cfg(not(target_os = "unknown"))] pub trait TransactionPoolAndMaybeMallogSizeOf: TransactionPool + MallocSizeOf {} diff --git a/substrate/client/keystore/src/local.rs b/substrate/client/keystore/src/local.rs index a86812a9f9..e5c8ff14af 100644 --- a/substrate/client/keystore/src/local.rs +++ b/substrate/client/keystore/src/local.rs @@ -521,8 +521,8 @@ impl KeystoreInner { /// Get a key pair for the given public key. /// - /// Returns `Ok(None)` if the key doesn't exist, `Ok(Some(_))` if the key exists or `Err(_)` when - /// something failed. + /// Returns `Ok(None)` if the key doesn't exist, `Ok(Some(_))` if the key exists or `Err(_)` + /// when something failed. pub fn key_pair( &self, public: &::Public, diff --git a/substrate/client/network-gossip/src/bridge.rs b/substrate/client/network-gossip/src/bridge.rs index 9ef5e0caee..6fa16cad77 100644 --- a/substrate/client/network-gossip/src/bridge.rs +++ b/substrate/client/network-gossip/src/bridge.rs @@ -64,8 +64,8 @@ enum ForwardingState { /// more messages to forward. Idle, /// The gossip engine is in the progress of forwarding messages and thus will not poll the - /// network for more messages until it has send all current messages into the subscribed message - /// sinks. + /// network for more messages until it has send all current messages into the subscribed + /// message sinks. Busy(VecDeque<(B::Hash, TopicNotification)>), } diff --git a/substrate/client/network-gossip/src/lib.rs b/substrate/client/network-gossip/src/lib.rs index 45fc19d6ef..55c2fc8206 100644 --- a/substrate/client/network-gossip/src/lib.rs +++ b/substrate/client/network-gossip/src/lib.rs @@ -32,8 +32,8 @@ //! //! # Usage //! -//! - Implement the `Network` trait, representing the low-level networking primitives. It is -//! already implemented on `sc_network::NetworkService`. +//! - Implement the `Network` trait, representing the low-level networking primitives. It is already +//! implemented on `sc_network::NetworkService`. //! - Implement the `Validator` trait. See the section below. //! - Decide on a protocol name. Each gossiping protocol should have a different one. //! - Build a `GossipEngine` using these three elements. diff --git a/substrate/client/network/src/behaviour.rs b/substrate/client/network/src/behaviour.rs index c181ee4e63..cb3b19d96c 100644 --- a/substrate/client/network/src/behaviour.rs +++ b/substrate/client/network/src/behaviour.rs @@ -302,12 +302,14 @@ impl Behaviour { &mut self.substrate } - /// Start querying a record from the DHT. Will later produce either a `ValueFound` or a `ValueNotFound` event. + /// Start querying a record from the DHT. Will later produce either a `ValueFound` or a + /// `ValueNotFound` event. pub fn get_value(&mut self, key: &record::Key) { self.discovery.get_value(key); } - /// Starts putting a record into DHT. Will later produce either a `ValuePut` or a `ValuePutFailed` event. + /// Starts putting a record into DHT. Will later produce either a `ValuePut` or a + /// `ValuePutFailed` event. pub fn put_value(&mut self, key: record::Key, value: Vec) { self.discovery.put_value(key, value); } diff --git a/substrate/client/network/src/block_request_handler.rs b/substrate/client/network/src/block_request_handler.rs index e546ae7661..67a83af897 100644 --- a/substrate/client/network/src/block_request_handler.rs +++ b/substrate/client/network/src/block_request_handler.rs @@ -294,12 +294,12 @@ impl BlockRequestHandler { }; (justifications, Vec::new(), false) } else { - // For now we keep compatibility by selecting precisely the GRANDPA one, and not just - // the first one. When sending we could have just taken the first one, since we don't - // expect there to be any other kind currently, but when receiving we need to add the - // engine ID tag. - // The ID tag is hardcoded here to avoid depending on the GRANDPA crate, and will be - // removed once we remove the backwards compatibility. + // For now we keep compatibility by selecting precisely the GRANDPA one, and not + // just the first one. When sending we could have just taken the first one, + // since we don't expect there to be any other kind currently, but when + // receiving we need to add the engine ID tag. + // The ID tag is hardcoded here to avoid depending on the GRANDPA crate, and + // will be removed once we remove the backwards compatibility. // See: https://github.com/paritytech/substrate/issues/8172 let justification = justifications.and_then(|just| just.into_justification(*b"FRNK")); diff --git a/substrate/client/network/src/config.rs b/substrate/client/network/src/config.rs index dd60f32912..306a4cfd29 100644 --- a/substrate/client/network/src/config.rs +++ b/substrate/client/network/src/config.rs @@ -112,8 +112,8 @@ pub struct Params { /// Request response configuration for the block request protocol. /// /// [`RequestResponseConfig::name`] is used to tag outgoing block requests with the correct - /// protocol name. In addition all of [`RequestResponseConfig`] is used to handle incoming block - /// requests, if enabled. + /// protocol name. In addition all of [`RequestResponseConfig`] is used to handle incoming + /// block requests, if enabled. /// /// Can be constructed either via [`crate::block_request_handler::generate_protocol_config`] /// allowing outgoing but not incoming requests, or constructed via @@ -272,7 +272,6 @@ impl fmt::Debug for ProtocolId { /// assert_eq!(peer_id, "QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV".parse::().unwrap()); /// assert_eq!(addr, "/ip4/198.51.100.19/tcp/30333".parse::().unwrap()); /// ``` -/// pub fn parse_str_addr(addr_str: &str) -> Result<(PeerId, Multiaddr), ParseErr> { let addr: Multiaddr = addr_str.parse()?; parse_addr(addr) @@ -506,7 +505,8 @@ impl NetworkConfiguration { } } - /// Create new default configuration for localhost-only connection with random port (useful for testing) + /// Create new default configuration for localhost-only connection with random port (useful for + /// testing) pub fn new_local() -> NetworkConfiguration { let mut config = NetworkConfiguration::new("test-node", "test-client", Default::default(), None); @@ -520,7 +520,8 @@ impl NetworkConfiguration { config } - /// Create new default configuration for localhost-only connection with random port (useful for testing) + /// Create new default configuration for localhost-only connection with random port (useful for + /// testing) pub fn new_memory() -> NetworkConfiguration { let mut config = NetworkConfiguration::new("test-node", "test-client", Default::default(), None); @@ -629,8 +630,8 @@ pub enum TransportConfig { allow_private_ipv4: bool, /// Optional external implementation of a libp2p transport. Used in WASM contexts where we - /// need some binding between the networking provided by the operating system or environment - /// and libp2p. + /// need some binding between the networking provided by the operating system or + /// environment and libp2p. /// /// This parameter exists whatever the target platform is, but it is expected to be set to /// `Some` only when compiling for WASM. @@ -710,12 +711,12 @@ impl NodeKeyConfig { /// /// * If the secret is configured as input, the corresponding keypair is returned. /// - /// * If the secret is configured as a file, it is read from that file, if it exists. - /// Otherwise a new secret is generated and stored. In either case, the - /// keypair obtained from the secret is returned. + /// * If the secret is configured as a file, it is read from that file, if it exists. Otherwise + /// a new secret is generated and stored. In either case, the keypair obtained from the + /// secret is returned. /// - /// * If the secret is configured to be new, it is generated and the corresponding - /// keypair is returned. + /// * If the secret is configured to be new, it is generated and the corresponding keypair is + /// returned. pub fn into_keypair(self) -> io::Result { use NodeKeyConfig::*; match self { diff --git a/substrate/client/network/src/discovery.rs b/substrate/client/network/src/discovery.rs index 6ca01cd892..d4367b2ada 100644 --- a/substrate/client/network/src/discovery.rs +++ b/substrate/client/network/src/discovery.rs @@ -1002,7 +1002,8 @@ mod tests { match e { DiscoveryOut::UnroutablePeer(other) | DiscoveryOut::Discovered(other) => { - // Call `add_self_reported_address` to simulate identify happening. + // Call `add_self_reported_address` to simulate identify + // happening. let addr = swarms .iter() .find_map(|(s, a)| { diff --git a/substrate/client/network/src/lib.rs b/substrate/client/network/src/lib.rs index 633baaca47..51bc370265 100644 --- a/substrate/client/network/src/lib.rs +++ b/substrate/client/network/src/lib.rs @@ -121,10 +121,10 @@ //! //! - **`/substrate//`** (where `` must be replaced with the //! protocol ID of the targeted chain, and `` is a number between 2 and 6). For each -//! connection we optionally keep an additional substream for all Substrate-based communications alive. -//! This protocol is considered legacy, and is progressively being replaced with alternatives. -//! This is designated as "The legacy Substrate substream" in this documentation. See below for -//! more details. +//! connection we optionally keep an additional substream for all Substrate-based communications +//! alive. This protocol is considered legacy, and is progressively being replaced with +//! alternatives. This is designated as "The legacy Substrate substream" in this documentation. See +//! below for more details. //! - **`//sync/2`** is a request-response protocol (see below) that lets one perform //! requests for information about blocks. Each request is the encoding of a `BlockRequest` and //! each response is the encoding of a `BlockResponse`, as defined in the `api.v1.proto` file in @@ -243,7 +243,6 @@ //! - Calling `trigger_repropagate` when a transaction is added to the pool. //! //! More precise usage details are still being worked on and will likely change in the future. -//! mod behaviour; mod chain; diff --git a/substrate/client/network/src/light_client_requests.rs b/substrate/client/network/src/light_client_requests.rs index 8489585e28..e18b783f21 100644 --- a/substrate/client/network/src/light_client_requests.rs +++ b/substrate/client/network/src/light_client_requests.rs @@ -36,7 +36,8 @@ fn generate_protocol_name(protocol_id: &ProtocolId) -> String { s } -/// Generates a [`ProtocolConfig`] for the light client request protocol, refusing incoming requests. +/// Generates a [`ProtocolConfig`] for the light client request protocol, refusing incoming +/// requests. pub fn generate_protocol_config(protocol_id: &ProtocolId) -> ProtocolConfig { ProtocolConfig { name: generate_protocol_name(protocol_id).into(), diff --git a/substrate/client/network/src/light_client_requests/sender.rs b/substrate/client/network/src/light_client_requests/sender.rs index 0c12c9a3f8..1560e7afbf 100644 --- a/substrate/client/network/src/light_client_requests/sender.rs +++ b/substrate/client/network/src/light_client_requests/sender.rs @@ -26,8 +26,9 @@ //! 2. Forward the request to [`crate::request_responses::RequestResponsesBehaviour`] via //! [`OutEvent::SendRequest`](sender::OutEvent::SendRequest). //! -//! 3. Wait for the response and forward the response via the [`futures::channel::oneshot::Sender`] provided earlier -//! with [`LightClientRequestSender::request`](sender::LightClientRequestSender::request). +//! 3. Wait for the response and forward the response via the [`futures::channel::oneshot::Sender`] +//! provided earlier with [`LightClientRequestSender::request`](sender::LightClientRequestSender:: +//! request). use crate::{ config::ProtocolId, diff --git a/substrate/client/network/src/protocol/message.rs b/substrate/client/network/src/protocol/message.rs index 95f5ffa3a5..1ffc57de18 100644 --- a/substrate/client/network/src/protocol/message.rs +++ b/substrate/client/network/src/protocol/message.rs @@ -16,7 +16,8 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -//! Network packet message types. These get serialized and put into the lower level protocol payload. +//! Network packet message types. These get serialized and put into the lower level protocol +//! payload. pub use self::generic::{ BlockAnnounce, FromBlock, RemoteCallRequest, RemoteChangesRequest, RemoteChangesResponse, @@ -392,7 +393,8 @@ pub mod generic { pub to: Option, /// Sequence direction. pub direction: Direction, - /// Maximum number of blocks to return. An implementation defined maximum is used when unspecified. + /// Maximum number of blocks to return. An implementation defined maximum is used when + /// unspecified. pub max: Option, } diff --git a/substrate/client/network/src/protocol/notifications/behaviour.rs b/substrate/client/network/src/protocol/notifications/behaviour.rs index 1466e9d426..648abc391f 100644 --- a/substrate/client/network/src/protocol/notifications/behaviour.rs +++ b/substrate/client/network/src/protocol/notifications/behaviour.rs @@ -63,8 +63,8 @@ use wasm_timer::Instant; /// - [`PeerState::Disabled`]: Has open TCP connection(s) unbeknownst to the peerset. No substream /// is open. /// - [`PeerState::Enabled`]: Has open TCP connection(s), acknowledged by the peerset. -/// - Notifications substreams are open on at least one connection, and external -/// API has been notified. +/// - Notifications substreams are open on at least one connection, and external API has been +/// notified. /// - Notifications substreams aren't open. /// - [`PeerState::Incoming`]: Has open TCP connection(s) and remote would like to open substreams. /// Peerset has been asked to attribute an inbound slot. @@ -1255,8 +1255,8 @@ impl NetworkBehaviour for Notifications { .iter() .any(|(_, s)| matches!(s, ConnectionState::OpenDesiredByRemote)); - // If no connection is `OpenDesiredByRemote` anymore, clean up the peerset incoming - // request. + // If no connection is `OpenDesiredByRemote` anymore, clean up the peerset + // incoming request. if no_desired_left { // In the incoming state, we don't report "Dropped". Instead we will just // ignore the corresponding Accept/Reject. diff --git a/substrate/client/network/src/protocol/notifications/upgrade/notifications.rs b/substrate/client/network/src/protocol/notifications/upgrade/notifications.rs index d01b1b5054..868544824f 100644 --- a/substrate/client/network/src/protocol/notifications/upgrade/notifications.rs +++ b/substrate/client/network/src/protocol/notifications/upgrade/notifications.rs @@ -21,17 +21,17 @@ use asynchronous_codec::Framed; /// /// The Substrate notifications protocol consists in the following: /// -/// - Node A opens a substream to node B and sends a message which contains some protocol-specific -/// higher-level logic. This message is prefixed with a variable-length integer message length. -/// This message can be empty, in which case `0` is sent. +/// - Node A opens a substream to node B and sends a message which contains some +/// protocol-specific higher-level logic. This message is prefixed with a variable-length +/// integer message length. This message can be empty, in which case `0` is sent. /// - If node B accepts the substream, it sends back a message with the same properties. /// - If instead B refuses the connection (which typically happens because no empty slot is /// available), then it immediately closes the substream without sending back anything. -/// - Node A can then send notifications to B, prefixed with a variable-length integer indicating -/// the length of the message. -/// - Either node A or node B can signal that it doesn't want this notifications substream anymore -/// by closing its writing side. The other party should respond by also closing their own -/// writing side soon after. +/// - Node A can then send notifications to B, prefixed with a variable-length integer +/// indicating the length of the message. +/// - Either node A or node B can signal that it doesn't want this notifications substream +/// anymore by closing its writing side. The other party should respond by also closing their +/// own writing side soon after. /// /// Notification substreams are unidirectional. If A opens a substream with B, then B is /// encouraged but not required to open a substream to A as well. diff --git a/substrate/client/network/src/protocol/sync.rs b/substrate/client/network/src/protocol/sync.rs index e9bf14a623..5cbe1fa135 100644 --- a/substrate/client/network/src/protocol/sync.rs +++ b/substrate/client/network/src/protocol/sync.rs @@ -27,7 +27,6 @@ //! The `ChainSync` struct maintains the state of the block requests. Whenever something happens on //! the network, or whenever a block has been successfully verified, call the appropriate method in //! order to update it. -//! use crate::{ protocol::message::{self, BlockAnnounce, BlockAttributes, BlockRequest, BlockResponse}, @@ -900,8 +899,8 @@ impl ChainSync { // If our best queued is more than `MAX_BLOCKS_TO_LOOK_BACKWARDS` blocks away from the // common number, the peer best number is higher than our best queued and the common // number is smaller than the last finalized block number, we should do an ancestor - // search to find a better common block. If the queue is full we wait till all blocks are - // imported though. + // search to find a better common block. If the queue is full we wait till all blocks + // are imported though. if best_queued.saturating_sub(peer.common_number) > MAX_BLOCKS_TO_LOOK_BACKWARDS.into() && best_queued < peer.best_number && peer.common_number < last_finalized && @@ -1149,8 +1148,8 @@ impl ChainSync { ancestry_request::(next_num), )) } else { - // Ancestry search is complete. Check if peer is on a stale fork unknown to us and - // add it to sync targets if necessary. + // Ancestry search is complete. Check if peer is on a stale fork unknown + // to us and add it to sync targets if necessary. trace!( target: "sync", "Ancestry search complete. Ours={} ({}), Theirs={} ({}), Common={:?} ({})", @@ -1774,8 +1773,8 @@ impl ChainSync { /// /// This should be polled until it returns [`Poll::Pending`]. /// - /// If [`PollBlockAnnounceValidation::ImportHeader`] is returned, then the caller MUST try to import passed - /// header (call `on_block_data`). The network request isn't sent in this case. + /// If [`PollBlockAnnounceValidation::ImportHeader`] is returned, then the caller MUST try to + /// import passed header (call `on_block_data`). The network request isn't sent in this case. pub fn poll_block_announce_validation( &mut self, cx: &mut std::task::Context, @@ -2002,7 +2001,8 @@ impl ChainSync { }) } - /// Find a block to start sync from. If we sync with state, that's the latest block we have state for. + /// Find a block to start sync from. If we sync with state, that's the latest block we have + /// state for. fn reset_sync_start_point(&mut self) -> Result<(), ClientError> { let info = self.client.info(); if matches!(self.mode, SyncMode::LightState { .. }) && info.finalized_state.is_some() { @@ -2132,8 +2132,8 @@ fn ancestry_request(block: NumberFor) -> BlockRequest { } } -/// The ancestor search state expresses which algorithm, and its stateful parameters, we are using to -/// try to find an ancestor block +/// The ancestor search state expresses which algorithm, and its stateful parameters, we are using +/// to try to find an ancestor block #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum AncestorSearchState { /// Use exponential backoff to find an ancestor, then switch to binary search. @@ -2161,7 +2161,8 @@ fn handle_ancestor_search_state( AncestorSearchState::ExponentialBackoff(next_distance_to_tip) => { let next_distance_to_tip = *next_distance_to_tip; if block_hash_match && next_distance_to_tip == One::one() { - // We found the ancestor in the first step so there is no need to execute binary search. + // We found the ancestor in the first step so there is no need to execute binary + // search. return None } if block_hash_match { @@ -2645,13 +2646,13 @@ mod test { /// This test is a regression test as observed on a real network. /// - /// The node is connected to multiple peers. Both of these peers are having a best block (1) that - /// is below our best block (3). Now peer 2 announces a fork of block 3 that we will + /// The node is connected to multiple peers. Both of these peers are having a best block (1) + /// that is below our best block (3). Now peer 2 announces a fork of block 3 that we will /// request from peer 2. After importing the fork, peer 2 and then peer 1 will announce block 4. - /// But as peer 1 in our view is still at block 1, we will request block 2 (which we already have) - /// from it. In the meanwhile peer 2 sends us block 4 and 3 and we send another request for block - /// 2 to peer 2. Peer 1 answers with block 2 and then peer 2. This will need to succeed, as we - /// have requested block 2 from both peers. + /// But as peer 1 in our view is still at block 1, we will request block 2 (which we already + /// have) from it. In the meanwhile peer 2 sends us block 4 and 3 and we send another request + /// for block 2 to peer 2. Peer 1 answers with block 2 and then peer 2. This will need to + /// succeed, as we have requested block 2 from both peers. #[test] fn do_not_report_peer_on_block_response_for_block_request() { sp_tracing::try_init_simple(); @@ -2756,9 +2757,9 @@ mod test { /// /// The scenario is that the node is doing a full resync and is connected to some node that is /// doing a major sync as well. This other node that is doing a major sync will finish before - /// our node and send a block announcement message, but we don't have seen any block announcement - /// from this node in its sync process. Meaning our common number didn't change. It is now expected - /// that we start an ancestor search to find the common number. + /// our node and send a block announcement message, but we don't have seen any block + /// announcement from this node in its sync process. Meaning our common number didn't change. It + /// is now expected that we start an ancestor search to find the common number. #[test] fn do_ancestor_search_when_common_block_to_best_qeued_gap_is_to_big() { sp_tracing::try_init_simple(); diff --git a/substrate/client/network/src/protocol/sync/blocks.rs b/substrate/client/network/src/protocol/sync/blocks.rs index e93d0174b8..df3506e7a8 100644 --- a/substrate/client/network/src/protocol/sync/blocks.rs +++ b/substrate/client/network/src/protocol/sync/blocks.rs @@ -98,7 +98,8 @@ impl BlockCollection { ); } - /// Returns a set of block hashes that require a header download. The returned set is marked as being downloaded. + /// Returns a set of block hashes that require a header download. The returned set is marked as + /// being downloaded. pub fn needed_blocks( &mut self, who: PeerId, @@ -171,7 +172,8 @@ impl BlockCollection { Some(range) } - /// Get a valid chain of blocks ordered in descending order and ready for importing into blockchain. + /// Get a valid chain of blocks ordered in descending order and ready for importing into + /// blockchain. pub fn drain(&mut self, from: NumberFor) -> Vec> { let mut drained = Vec::new(); let mut ranges = Vec::new(); diff --git a/substrate/client/network/src/protocol/sync/extra_requests.rs b/substrate/client/network/src/protocol/sync/extra_requests.rs index 52419b5d77..3716384136 100644 --- a/substrate/client/network/src/protocol/sync/extra_requests.rs +++ b/substrate/client/network/src/protocol/sync/extra_requests.rs @@ -176,8 +176,8 @@ impl ExtraRequests { } if best_finalized_number > self.best_seen_finalized_number { - // normally we'll receive finality notifications for every block => finalize would be enough - // but if many blocks are finalized at once, some notifications may be omitted + // normally we'll receive finality notifications for every block => finalize would be + // enough but if many blocks are finalized at once, some notifications may be omitted // => let's use finalize_with_ancestors here match self.tree.finalize_with_ancestors( best_finalized_hash, @@ -315,7 +315,8 @@ impl<'a, B: BlockT> Matcher<'a, B> { for (peer, sync) in peers.iter().filter(|(_, sync)| sync.state == PeerSyncState::Available) { - // only ask peers that have synced at least up to the block number that we're asking the extra for + // only ask peers that have synced at least up to the block number that we're asking + // the extra for if sync.best_number < request.1 { continue } diff --git a/substrate/client/network/src/request_responses.rs b/substrate/client/network/src/request_responses.rs index bd20f1610d..87a09bed42 100644 --- a/substrate/client/network/src/request_responses.rs +++ b/substrate/client/network/src/request_responses.rs @@ -310,7 +310,8 @@ impl RequestResponsesBehaviour { /// Initiates sending a request. /// - /// If there is no established connection to the target peer, the behavior is determined by the choice of `connect`. + /// If there is no established connection to the target peer, the behavior is determined by the + /// choice of `connect`. /// /// An error is returned if the protocol doesn't match one that has been registered. pub fn send_request( @@ -700,8 +701,8 @@ impl NetworkBehaviour for RequestResponsesBehaviour { return Poll::Ready(NetworkBehaviourAction::GenerateEvent(out)) }, - // An inbound request failed, either while reading the request or due to failing - // to send a response. + // An inbound request failed, either while reading the request or due to + // failing to send a response. RequestResponseEvent::InboundFailure { request_id, peer, error, .. } => { diff --git a/substrate/client/network/src/service.rs b/substrate/client/network/src/service.rs index 31d4488bc9..c6a7a953fe 100644 --- a/substrate/client/network/src/service.rs +++ b/substrate/client/network/src/service.rs @@ -729,7 +729,8 @@ impl NetworkService { /// > preventing the message from being delivered. /// /// The protocol must have been registered with - /// [`NetworkConfiguration::notifications_protocols`](crate::config::NetworkConfiguration::notifications_protocols). + /// [`NetworkConfiguration::notifications_protocols`](crate::config::NetworkConfiguration:: + /// notifications_protocols). pub fn write_notification( &self, target: PeerId, @@ -774,7 +775,8 @@ impl NetworkService { /// Obtains a [`NotificationSender`] for a connected peer, if it exists. /// /// A `NotificationSender` is scoped to a particular connection to the peer that holds - /// a receiver. With a `NotificationSender` at hand, sending a notification is done in two steps: + /// a receiver. With a `NotificationSender` at hand, sending a notification is done in two + /// steps: /// /// 1. [`NotificationSender::ready`] is used to wait for the sender to become ready /// for another notification, yielding a [`NotificationSenderReady`] token. @@ -794,7 +796,8 @@ impl NetworkService { /// in which case enqueued notifications will be lost. /// /// The protocol must have been registered with - /// [`NetworkConfiguration::notifications_protocols`](crate::config::NetworkConfiguration::notifications_protocols). + /// [`NetworkConfiguration::notifications_protocols`](crate::config::NetworkConfiguration:: + /// notifications_protocols). /// /// # Usage /// @@ -883,10 +886,10 @@ impl NetworkService { /// notifications should remain the default ways of communicating information. For example, a /// peer can announce something through a notification, after which the recipient can obtain /// more information by performing a request. - /// As such, call this function with `IfDisconnected::ImmediateError` for `connect`. This way you - /// will get an error immediately for disconnected peers, instead of waiting for a potentially very - /// long connection attempt, which would suggest that something is wrong anyway, as you are - /// supposed to be connected because of the notification protocol. + /// As such, call this function with `IfDisconnected::ImmediateError` for `connect`. This way + /// you will get an error immediately for disconnected peers, instead of waiting for a + /// potentially very long connection attempt, which would suggest that something is wrong + /// anyway, as you are supposed to be connected because of the notification protocol. /// /// No limit or throttling of concurrent outbound requests per peer and protocol are enforced. /// Such restrictions, if desired, need to be enforced at the call site(s). @@ -914,7 +917,8 @@ impl NetworkService { } } - /// Variation of `request` which starts a request whose response is delivered on a provided channel. + /// Variation of `request` which starts a request whose response is delivered on a provided + /// channel. /// /// Instead of blocking and waiting for a reply, this function returns immediately, sending /// responses via the passed in sender. This alternative API exists to make it easier to @@ -1130,7 +1134,8 @@ impl NetworkService { /// /// Returns an `Err` if one of the given addresses is invalid or contains an /// invalid peer ID (which includes the local peer ID). - // NOTE: technically, this function only needs `Vec`, but we use `Multiaddr` here for convenience. + // NOTE: technically, this function only needs `Vec`, but we use `Multiaddr` here for + // convenience. pub fn remove_peers_from_reserved_set( &self, protocol: Cow<'static, str>, @@ -1198,7 +1203,8 @@ impl NetworkService { /// /// Returns an `Err` if one of the given addresses is invalid or contains an /// invalid peer ID (which includes the local peer ID). - // NOTE: technically, this function only needs `Vec`, but we use `Multiaddr` here for convenience. + // NOTE: technically, this function only needs `Vec`, but we use `Multiaddr` here for + // convenience. pub fn remove_from_peers_set( &self, protocol: Cow<'static, str>, @@ -1314,7 +1320,8 @@ pub struct NotificationSender { } impl NotificationSender { - /// Returns a future that resolves when the `NotificationSender` is ready to send a notification. + /// Returns a future that resolves when the `NotificationSender` is ready to send a + /// notification. pub async fn ready<'a>( &'a self, ) -> Result, NotificationSenderError> { @@ -1371,7 +1378,8 @@ impl<'a> NotificationSenderReady<'a> { /// Error returned by [`NetworkService::send_notification`]. #[derive(Debug, derive_more::Display, derive_more::Error)] pub enum NotificationSenderError { - /// The notification receiver has been closed, usually because the underlying connection closed. + /// The notification receiver has been closed, usually because the underlying connection + /// closed. /// /// Some of the notifications most recently sent may not have been received. However, /// the peer may still be connected and a new `NotificationSender` for the same diff --git a/substrate/client/network/src/warp_request_handler.rs b/substrate/client/network/src/warp_request_handler.rs index beb9d1ce52..0e45f2d43a 100644 --- a/substrate/client/network/src/warp_request_handler.rs +++ b/substrate/client/network/src/warp_request_handler.rs @@ -49,7 +49,8 @@ pub enum VerificationResult { /// Warp sync backend. Handles retrieveing and verifying warp sync proofs. pub trait WarpSyncProvider: Send + Sync { - /// Generate proof starting at given block hash. The proof is accumulated until maximum proof size is reached. + /// Generate proof starting at given block hash. The proof is accumulated until maximum proof + /// size is reached. fn generate( &self, start: B::Hash, @@ -61,11 +62,13 @@ pub trait WarpSyncProvider: Send + Sync { set_id: SetId, authorities: AuthorityList, ) -> Result, Box>; - /// Get current list of authorities. This is supposed to be genesis authorities when starting sync. + /// Get current list of authorities. This is supposed to be genesis authorities when starting + /// sync. fn current_authorities(&self) -> AuthorityList; } -/// Generates a [`RequestResponseConfig`] for the grandpa warp sync request protocol, refusing incoming requests. +/// Generates a [`RequestResponseConfig`] for the grandpa warp sync request protocol, refusing +/// incoming requests. pub fn generate_request_response_config(protocol_id: ProtocolId) -> RequestResponseConfig { RequestResponseConfig { name: generate_protocol_name(protocol_id).into(), diff --git a/substrate/client/offchain/src/api/http_dummy.rs b/substrate/client/offchain/src/api/http_dummy.rs index 386fc445d4..73d30396ab 100644 --- a/substrate/client/offchain/src/api/http_dummy.rs +++ b/substrate/client/offchain/src/api/http_dummy.rs @@ -25,7 +25,8 @@ use std::{ task::{Context, Poll}, }; -/// Wrapper struct (wrapping nothing in case of http_dummy) used for keeping the hyper_rustls client running. +/// Wrapper struct (wrapping nothing in case of http_dummy) used for keeping the hyper_rustls client +/// running. #[derive(Clone)] pub struct SharedClient; diff --git a/substrate/client/rpc-api/src/author/mod.rs b/substrate/client/rpc-api/src/author/mod.rs index dbf729ea18..720598e0b3 100644 --- a/substrate/client/rpc-api/src/author/mod.rs +++ b/substrate/client/rpc-api/src/author/mod.rs @@ -74,8 +74,8 @@ pub trait AuthorApi { /// Submit an extrinsic to watch. /// - /// See [`TransactionStatus`](sc_transaction_pool_api::TransactionStatus) for details on transaction - /// life cycle. + /// See [`TransactionStatus`](sc_transaction_pool_api::TransactionStatus) for details on + /// transaction life cycle. #[pubsub( subscription = "author_extrinsicUpdate", subscribe, diff --git a/substrate/client/rpc-api/src/state/mod.rs b/substrate/client/rpc-api/src/state/mod.rs index b3048d7bb5..5b8e0ffc7a 100644 --- a/substrate/client/rpc-api/src/state/mod.rs +++ b/substrate/client/rpc-api/src/state/mod.rs @@ -89,7 +89,8 @@ pub trait StateApi { #[rpc(name = "state_getRuntimeVersion", alias("chain_getRuntimeVersion"))] fn runtime_version(&self, hash: Option) -> FutureResult; - /// Query historical storage entries (by key) starting from a block given as the second parameter. + /// Query historical storage entries (by key) starting from a block given as the second + /// parameter. /// /// NOTE This first returned result contains the initial state of storage for all keys. /// Subsequent values in the vector represent changes to the previous state (diffs). @@ -176,7 +177,8 @@ pub trait StateApi { /// ## Node requirements /// /// - Fully synced archive node (i.e. a node that is not actively doing a "major" sync). - /// - [Tracing enabled WASM runtimes](#creating-tracing-enabled-wasm-runtimes) for all runtime versions + /// - [Tracing enabled WASM runtimes](#creating-tracing-enabled-wasm-runtimes) for all runtime + /// versions /// for which tracing is desired. /// /// ## Node recommendations @@ -192,10 +194,12 @@ pub trait StateApi { /// - Add feature `with-tracing = ["frame-executive/with-tracing", "sp-io/with-tracing"]` /// under `[features]` to the `runtime` packages' `Cargo.toml`. /// - Compile the runtime with `cargo build --release --features with-tracing` - /// - Tracing-enabled WASM runtime should be found in `./target/release/wbuild/{{chain}}-runtime` + /// - Tracing-enabled WASM runtime should be found in + /// `./target/release/wbuild/{{chain}}-runtime` /// and be called something like `{{your_chain}}_runtime.compact.wasm`. This can be /// renamed/modified however you like, as long as it retains the `.wasm` extension. - /// - Run the node with the wasm blob overrides by placing them in a folder with all your runtimes, + /// - Run the node with the wasm blob overrides by placing them in a folder with all your + /// runtimes, /// and passing the path of this folder to your chain, e.g.: /// - `./target/release/polkadot --wasm-runtime-overrides /home/user/my-custom-wasm-runtimes` /// diff --git a/substrate/client/rpc/src/author/mod.rs b/substrate/client/rpc/src/author/mod.rs index 966959050c..0cb24d25b2 100644 --- a/substrate/client/rpc/src/author/mod.rs +++ b/substrate/client/rpc/src/author/mod.rs @@ -215,7 +215,8 @@ where }, Err(err) => { warn!("Failed to submit extrinsic: {}", err); - // reject the subscriber (ignore errors - we don't care if subscriber is no longer there). + // reject the subscriber (ignore errors - we don't care if subscriber is no + // longer there). let _ = subscriber.reject(err.into()); }, }); diff --git a/substrate/client/rpc/src/state/mod.rs b/substrate/client/rpc/src/state/mod.rs index 9137404df3..472e50c749 100644 --- a/substrate/client/rpc/src/state/mod.rs +++ b/substrate/client/rpc/src/state/mod.rs @@ -119,7 +119,8 @@ where /// Get the runtime version. fn runtime_version(&self, block: Option) -> FutureResult; - /// Query historical storage entries (by key) starting from a block given as the second parameter. + /// Query historical storage entries (by key) starting from a block given as the second + /// parameter. /// /// NOTE This first returned result contains the initial state of storage for all keys. /// Subsequent values in the vector represent changes to the previous state (diffs). diff --git a/substrate/client/rpc/src/state/state_full.rs b/substrate/client/rpc/src/state/state_full.rs index 313e89bdf8..242a78d585 100644 --- a/substrate/client/rpc/src/state/state_full.rs +++ b/substrate/client/rpc/src/state/state_full.rs @@ -208,7 +208,8 @@ where Ok(()) } - /// Iterates through all blocks that are changing keys within range.filtered_range and collects these changes. + /// Iterates through all blocks that are changing keys within range.filtered_range and collects + /// these changes. fn query_storage_filtered( &self, range: &QueryStorageRange, diff --git a/substrate/client/service/src/builder.rs b/substrate/client/service/src/builder.rs index 18f701d6f1..f9b68c4ae3 100644 --- a/substrate/client/service/src/builder.rs +++ b/substrate/client/service/src/builder.rs @@ -254,8 +254,9 @@ impl KeystoreContainer { /// /// # Note /// - /// Using the [`LocalKeystore`] will result in loosing the ability to use any other keystore implementation, like - /// a remote keystore for example. Only use this if you a certain that you require it! + /// Using the [`LocalKeystore`] will result in loosing the ability to use any other keystore + /// implementation, like a remote keystore for example. Only use this if you a certain that you + /// require it! pub fn local_keystore(&self) -> Option> { Some(self.local.clone()) } diff --git a/substrate/client/service/src/chain_ops/import_blocks.rs b/substrate/client/service/src/chain_ops/import_blocks.rs index 396e5b80f2..1ba9e0bd61 100644 --- a/substrate/client/service/src/chain_ops/import_blocks.rs +++ b/substrate/client/service/src/chain_ops/import_blocks.rs @@ -272,8 +272,8 @@ where { /// We are reading from the BlockIter structure, adding those blocks to the queue if possible. Reading { block_iter: BlockIter }, - /// The queue is full (contains at least MAX_PENDING_BLOCKS blocks) and we are waiting for it to - /// catch up. + /// The queue is full (contains at least MAX_PENDING_BLOCKS blocks) and we are waiting for it + /// to catch up. WaitingForImportQueueToCatchUp { block_iter: BlockIter, delay: Delay, diff --git a/substrate/client/service/src/client/call_executor.rs b/substrate/client/service/src/client/call_executor.rs index 0710c4ae87..23cc08b7e1 100644 --- a/substrate/client/service/src/client/call_executor.rs +++ b/substrate/client/service/src/client/call_executor.rs @@ -253,7 +253,6 @@ where ) .set_parent_hash(at_hash); // TODO: https://github.com/paritytech/substrate/issues/4455 - // .with_storage_transaction_cache(storage_transaction_cache.as_mut().map(|c| &mut **c)) state_machine.execute_using_consensus_failure_handler( execution_manager, native_call.map(|n| || (n)().map_err(|e| Box::new(e) as Box<_>)), diff --git a/substrate/client/service/src/client/client.rs b/substrate/client/service/src/client/client.rs index 727d58dfa0..9439a06a5a 100644 --- a/substrate/client/service/src/client/client.rs +++ b/substrate/client/service/src/client/client.rs @@ -827,8 +827,8 @@ where let state_root = operation.op.reset_storage(storage)?; if state_root != *import_headers.post().state_root() { - // State root mismatch when importing state. This should not happen in safe fast sync mode, - // but may happen in unsafe mode. + // State root mismatch when importing state. This should not happen in + // safe fast sync mode, but may happen in unsafe mode. warn!("Error imporing state: State root mismatch."); return Err(Error::InvalidStateRoot) } diff --git a/substrate/client/service/src/config.rs b/substrate/client/service/src/config.rs index 6b10545886..67a4a2acfc 100644 --- a/substrate/client/service/src/config.rs +++ b/substrate/client/service/src/config.rs @@ -120,7 +120,8 @@ pub struct Configuration { pub disable_grandpa: bool, /// Development key seed. /// - /// When running in development mode, the seed will be used to generate authority keys by the keystore. + /// When running in development mode, the seed will be used to generate authority keys by the + /// keystore. /// /// Should only be set when `node` is running development mode. pub dev_key_seed: Option, diff --git a/substrate/client/service/src/lib.rs b/substrate/client/service/src/lib.rs index b1dcc615a4..e9a6d21606 100644 --- a/substrate/client/service/src/lib.rs +++ b/substrate/client/service/src/lib.rs @@ -342,7 +342,8 @@ mod waiting { } } -/// Starts RPC servers that run in their own thread, and returns an opaque object that keeps them alive. +/// Starts RPC servers that run in their own thread, and returns an opaque object that keeps them +/// alive. #[cfg(not(target_os = "unknown"))] fn start_rpc_servers< H: FnMut( @@ -428,7 +429,8 @@ fn start_rpc_servers< ))) } -/// Starts RPC servers that run in their own thread, and returns an opaque object that keeps them alive. +/// Starts RPC servers that run in their own thread, and returns an opaque object that keeps them +/// alive. #[cfg(target_os = "unknown")] fn start_rpc_servers< H: FnMut( @@ -539,7 +541,8 @@ where }, Err(e) => { debug!("Error converting pool error: {:?}", e); - // it is not bad at least, just some internal node logic error, so peer is innocent. + // it is not bad at least, just some internal node logic error, so peer is + // innocent. TransactionImport::KnownGood }, }, diff --git a/substrate/client/service/test/src/client/mod.rs b/substrate/client/service/test/src/client/mod.rs index 01d46c9678..84a9c5b914 100644 --- a/substrate/client/service/test/src/client/mod.rs +++ b/substrate/client/service/test/src/client/mod.rs @@ -1826,7 +1826,8 @@ fn imports_blocks_with_changes_tries_config_change() { // blocks 24,25 are changing the key // block 26 is empty // block 27 changes the key - // block 28 is the L1 digest (NOT SKEWED!!!) that covers changes AND changes configuration to 3^1 + // block 28 is the L1 digest (NOT SKEWED!!!) that covers changes AND changes configuration to + // `3^1` // =================================================================== // block 29 is empty // block 30 changes the key diff --git a/substrate/client/state-db/src/lib.rs b/substrate/client/state-db/src/lib.rs index cdff39895d..44629975d7 100644 --- a/substrate/client/state-db/src/lib.rs +++ b/substrate/client/state-db/src/lib.rs @@ -25,15 +25,17 @@ //! There's a limit of 32 blocks that may have the same block number in the canonicalization window. //! //! Canonicalization function selects one root from the top of the tree and discards all other roots -//! and their subtrees. Upon canonicalization all trie nodes that were inserted in the block are added to -//! the backing DB and block tracking is moved to the pruning window, where no forks are allowed. +//! and their subtrees. Upon canonicalization all trie nodes that were inserted in the block are +//! added to the backing DB and block tracking is moved to the pruning window, where no forks are +//! allowed. //! //! # Canonicalization vs Finality -//! Database engine uses a notion of canonicality, rather then finality. A canonical block may not be yet finalized -//! from the perspective of the consensus engine, but it still can't be reverted in the database. Most of the time -//! during normal operation last canonical block is the same as last finalized. However if finality stall for a -//! long duration for some reason, there's only a certain number of blocks that can fit in the non-canonical overlay, -//! so canonicalization of an unfinalized block may be forced. +//! Database engine uses a notion of canonicality, rather then finality. A canonical block may not +//! be yet finalized from the perspective of the consensus engine, but it still can't be reverted in +//! the database. Most of the time during normal operation last canonical block is the same as last +//! finalized. However if finality stall for a long duration for some reason, there's only a certain +//! number of blocks that can fit in the non-canonical overlay, so canonicalization of an +//! unfinalized block may be forced. //! //! # Pruning. //! See `RefWindow` for pruning algorithm details. `StateDb` prunes on each canonicalization until @@ -177,7 +179,8 @@ pub struct CommitSet { /// Pruning constraints. If none are specified pruning is #[derive(Default, Debug, Clone, Eq, PartialEq)] pub struct Constraints { - /// Maximum blocks. Defaults to 0 when unspecified, effectively keeping only non-canonical states. + /// Maximum blocks. Defaults to 0 when unspecified, effectively keeping only non-canonical + /// states. pub max_blocks: Option, /// Maximum memory in the pruning overlay. pub max_mem: Option, diff --git a/substrate/client/state-db/src/noncanonical.rs b/substrate/client/state-db/src/noncanonical.rs index eff440d337..c726ceae4b 100644 --- a/substrate/client/state-db/src/noncanonical.rs +++ b/substrate/client/state-db/src/noncanonical.rs @@ -241,7 +241,8 @@ impl NonCanonicalOverlay { }) } - /// Insert a new block into the overlay. If inserted on the second level or lover expects parent to be present in the window. + /// Insert a new block into the overlay. If inserted on the second level or lover expects parent + /// to be present in the window. pub fn insert( &mut self, hash: &BlockHash, @@ -501,7 +502,8 @@ impl NonCanonicalOverlay { !self.pending_canonicalizations.contains(hash) } - /// Revert a single level. Returns commit set that deletes the journal or `None` if not possible. + /// Revert a single level. Returns commit set that deletes the journal or `None` if not + /// possible. pub fn revert_one(&mut self) -> Option> { self.levels.pop_back().map(|level| { let mut commit = CommitSet::default(); @@ -514,7 +516,8 @@ impl NonCanonicalOverlay { }) } - /// Revert a single block. Returns commit set that deletes the journal or `None` if not possible. + /// Revert a single block. Returns commit set that deletes the journal or `None` if not + /// possible. pub fn remove(&mut self, hash: &BlockHash) -> Option> { let mut commit = CommitSet::default(); let level_count = self.levels.len(); @@ -548,7 +551,8 @@ impl NonCanonicalOverlay { self.pending_insertions.reverse(); for hash in self.pending_insertions.drain(..) { self.parents.remove(&hash); - // find a level. When iterating insertions backwards the hash is always last in the level. + // find a level. When iterating insertions backwards the hash is always last in the + // level. let level_index = self .levels .iter() @@ -870,6 +874,7 @@ mod tests { fn complex_tree() { let mut db = make_db(&[]); + #[rustfmt::skip] // - 1 - 1_1 - 1_1_1 // \ 1_2 - 1_2_1 // \ 1_2_2 @@ -1027,6 +1032,7 @@ mod tests { fn keeps_pinned() { let mut db = make_db(&[]); + #[rustfmt::skip] // - 0 - 1_1 // \ 1_2 @@ -1053,6 +1059,7 @@ mod tests { fn keeps_pinned_ref_count() { let mut db = make_db(&[]); + #[rustfmt::skip] // - 0 - 1_1 // \ 1_2 // \ 1_3 @@ -1084,6 +1091,7 @@ mod tests { fn pin_keeps_parent() { let mut db = make_db(&[]); + #[rustfmt::skip] // - 0 - 1_1 - 2_1 // \ 1_2 @@ -1178,7 +1186,8 @@ mod tests { db.commit(&commit); overlay.apply_pending(); - // add another block at top level. It should reuse journal index 0 of previously discarded block + // add another block at top level. It should reuse journal index 0 of previously discarded + // block let h22 = H256::random(); db.commit(&overlay.insert::(&h22, 12, &h2, make_changeset(&[22], &[])).unwrap()); assert_eq!(overlay.levels[0].blocks[0].journal_index, 1); diff --git a/substrate/client/state-db/src/pruning.rs b/substrate/client/state-db/src/pruning.rs index bb0f7f7961..465c1ecda6 100644 --- a/substrate/client/state-db/src/pruning.rs +++ b/substrate/client/state-db/src/pruning.rs @@ -219,9 +219,10 @@ impl RefWindow { /// Revert all pending changes pub fn revert_pending(&mut self) { // Revert pending deletions. - // Note that pending insertions might cause some existing deletions to be removed from `death_index` - // We don't bother to track and revert that for now. This means that a few nodes might end up no being - // deleted in case transaction fails and `revert_pending` is called. + // Note that pending insertions might cause some existing deletions to be removed from + // `death_index` We don't bother to track and revert that for now. This means that a few + // nodes might end up no being deleted in case transaction fails and `revert_pending` is + // called. self.death_rows.truncate(self.death_rows.len() - self.pending_canonicalizations); if self.count_insertions { let new_max_block = self.death_rows.len() as u64 + self.pending_number; diff --git a/substrate/client/telemetry/src/lib.rs b/substrate/client/telemetry/src/lib.rs index 5bd839e074..929931e3b6 100644 --- a/substrate/client/telemetry/src/lib.rs +++ b/substrate/client/telemetry/src/lib.rs @@ -29,10 +29,10 @@ //! identify which substrate node is reporting the telemetry. Every task spawned using sc-service's //! `TaskManager` automatically inherit this span. //! -//! Substrate's nodes initialize/register with the [`TelemetryWorker`] using a [`TelemetryWorkerHandle`]. -//! This handle can be cloned and passed around. It uses an asynchronous channel to communicate with -//! the running [`TelemetryWorker`] dedicated to registration. Registering can happen at any point -//! in time during the process execution. +//! Substrate's nodes initialize/register with the [`TelemetryWorker`] using a +//! [`TelemetryWorkerHandle`]. This handle can be cloned and passed around. It uses an asynchronous +//! channel to communicate with the running [`TelemetryWorker`] dedicated to registration. +//! Registering can happen at any point in time during the process execution. #![warn(missing_docs)] diff --git a/substrate/client/telemetry/src/node.rs b/substrate/client/telemetry/src/node.rs index 9e5738cb84..4d845c328f 100644 --- a/substrate/client/telemetry/src/node.rs +++ b/substrate/client/telemetry/src/node.rs @@ -39,14 +39,14 @@ pub(crate) fn connection_notifier_channel() -> (ConnectionNotifierSender, Connec /// Handler for a single telemetry node. /// /// This is a wrapper `Sink` around a network `Sink` with 3 particularities: -/// - It is infallible: if the connection stops, it will reconnect automatically when the server -/// becomes available again. -/// - It holds a list of "connection messages" which are sent automatically when the connection is -/// (re-)established. This is used for the "system.connected" message that needs to be send for -/// every substrate node that connects. -/// - It doesn't stay in pending while waiting for connection. Instead, it moves data into the -/// void if the connection could not be established. This is important for the `Dispatcher` -/// `Sink` which we don't want to block if one connection is broken. +/// - It is infallible: if the connection stops, it will reconnect automatically when the server +/// becomes available again. +/// - It holds a list of "connection messages" which are sent automatically when the connection is +/// (re-)established. This is used for the "system.connected" message that needs to be send for +/// every substrate node that connects. +/// - It doesn't stay in pending while waiting for connection. Instead, it moves data into the void +/// if the connection could not be established. This is important for the `Dispatcher` `Sink` +/// which we don't want to block if one connection is broken. #[derive(Debug)] pub(crate) struct Node { /// Address of the node. diff --git a/substrate/client/transaction-pool/api/src/lib.rs b/substrate/client/transaction-pool/api/src/lib.rs index eb9b1b09b8..e861e6e042 100644 --- a/substrate/client/transaction-pool/api/src/lib.rs +++ b/substrate/client/transaction-pool/api/src/lib.rs @@ -203,7 +203,8 @@ pub trait TransactionPool: Send + Sync { xt: TransactionFor, ) -> PoolFuture, Self::Error>; - /// Returns a future that import a single transaction and starts to watch their progress in the pool. + /// Returns a future that import a single transaction and starts to watch their progress in the + /// pool. fn submit_and_watch( &self, at: &BlockId, diff --git a/substrate/client/transaction-pool/src/graph/base_pool.rs b/substrate/client/transaction-pool/src/graph/base_pool.rs index 86433bea49..b5ff036c01 100644 --- a/substrate/client/transaction-pool/src/graph/base_pool.rs +++ b/substrate/client/transaction-pool/src/graph/base_pool.rs @@ -322,7 +322,8 @@ impl BasePool BasePool Pool { extrinsics.iter().map(|extrinsic| self.hash_of(extrinsic)).collect::>(); let in_pool_tags = self.validated_pool.extrinsics_tags(&in_pool_hashes); - // Zip the ones from the pool with the full list (we get pairs `(Extrinsic, Option>)`) + // Zip the ones from the pool with the full list (we get pairs `(Extrinsic, + // Option>)`) let all = extrinsics.iter().zip(in_pool_tags.into_iter()); let mut future_tags = Vec::new(); @@ -1112,13 +1113,14 @@ mod tests { block_on(pool.submit_one(&BlockId::Number(0), SOURCE, xt)).unwrap(); assert_eq!(pool.validated_pool().status().ready, 1); - // Now block import happens before the second transaction is able to finish verification. + // Now block import happens before the second transaction is able to finish + // verification. block_on(pool.prune_tags(&BlockId::Number(1), vec![provides], vec![])).unwrap(); assert_eq!(pool.validated_pool().status().ready, 0); // so when we release the verification of the previous one it will have - // something in `requires`, but should go to ready directly, since the previous transaction was imported - // correctly. + // something in `requires`, but should go to ready directly, since the previous + // transaction was imported correctly. tx.send(()).unwrap(); // then diff --git a/substrate/client/transaction-pool/src/graph/ready.rs b/substrate/client/transaction-pool/src/graph/ready.rs index ac842b99bf..03689aeb32 100644 --- a/substrate/client/transaction-pool/src/graph/ready.rs +++ b/substrate/client/transaction-pool/src/graph/ready.rs @@ -114,7 +114,8 @@ pub struct ReadyTransactions { provided_tags: HashMap, /// Transactions that are ready (i.e. don't have any requirements external to the pool) ready: TrackedMap>, - /// Best transactions that are ready to be included to the block without any other previous transaction. + /// Best transactions that are ready to be included to the block without any other previous + /// transaction. best: BTreeSet>, } @@ -145,10 +146,12 @@ impl ReadyTransactions { /// /// Transactions are returned in order: /// 1. First by the dependencies: - /// - never return transaction that requires a tag, which was not provided by one of the previously + /// - never return transaction that requires a tag, which was not provided by one of the + /// previously /// returned transactions /// 2. Then by priority: - /// - If there are two transactions with all requirements satisfied the one with higher priority goes first. + /// - If there are two transactions with all requirements satisfied the one with higher priority + /// goes first. /// 3. Then by the ttl that's left /// - transactions that are valid for a shorter time go first /// 4. Lastly we sort by the time in the queue @@ -252,8 +255,8 @@ impl ReadyTransactions { /// Removes a subtree of transactions from the ready pool. /// - /// NOTE removing a transaction will also cause a removal of all transactions that depend on that one - /// (i.e. the entire subgraph that this transaction is a start of will be removed). + /// NOTE removing a transaction will also cause a removal of all transactions that depend on + /// that one (i.e. the entire subgraph that this transaction is a start of will be removed). /// All removed transactions are returned. pub fn remove_subtree(&mut self, hashes: &[Hash]) -> Vec>> { let to_remove = hashes.to_vec(); diff --git a/substrate/client/transaction-pool/src/graph/validated_pool.rs b/substrate/client/transaction-pool/src/graph/validated_pool.rs index 3ac7f00207..a0adeef683 100644 --- a/substrate/client/transaction-pool/src/graph/validated_pool.rs +++ b/substrate/client/transaction-pool/src/graph/validated_pool.rs @@ -393,8 +393,9 @@ impl ValidatedPool { }, Err(err) => { // we do not want to fail if single transaction import has failed - // nor we do want to propagate this error, because it could tx unknown to caller - // => let's just notify listeners (and issue debug message) + // nor we do want to propagate this error, because it could tx + // unknown to caller => let's just notify listeners (and issue debug + // message) log::warn!( target: "txpool", "[{:?}] Removing invalid transaction from update: {}", @@ -490,7 +491,8 @@ impl ValidatedPool { // Resubmit pruned transactions let results = self.submit(pruned_xts); - // Collect the hashes of transactions that now became invalid (meaning that they are successfully pruned). + // Collect the hashes of transactions that now became invalid (meaning that they are + // successfully pruned). let hashes = results.into_iter().enumerate().filter_map(|(idx, r)| { match r.map_err(error::IntoPoolError::into_pool_error) { Err(Ok(error::Error::InvalidTransaction(_))) => Some(pruned_hashes[idx]), diff --git a/substrate/frame/assets/src/functions.rs b/substrate/frame/assets/src/functions.rs index 6e6847ad7d..81b490eaf8 100644 --- a/substrate/frame/assets/src/functions.rs +++ b/substrate/frame/assets/src/functions.rs @@ -439,7 +439,8 @@ impl, I: 'static> Pallet { // Burn any dust if needed. if let Some(burn) = maybe_burn { - // Debit dust from supply; this will not saturate since it's already checked in prep. + // Debit dust from supply; this will not saturate since it's already checked in + // prep. debug_assert!(details.supply >= burn, "checked in prep; qed"); details.supply = details.supply.saturating_sub(burn); } diff --git a/substrate/frame/assets/src/lib.rs b/substrate/frame/assets/src/lib.rs index 65878672c9..386a3ea05c 100644 --- a/substrate/frame/assets/src/lib.rs +++ b/substrate/frame/assets/src/lib.rs @@ -43,8 +43,8 @@ //! account that issues the asset. This is a privileged operation. //! * **Asset transfer**: The reduction of the balance of an asset of one account with the //! corresponding increase in the balance of another. -//! * **Asset destruction**: The process of reduce the balance of an asset of one account. This is -//! a privileged operation. +//! * **Asset destruction**: The process of reduce the balance of an asset of one account. This is a +//! privileged operation. //! * **Fungible asset**: An asset whose units are interchangeable. //! * **Issuer**: An account ID uniquely privileged to be able to mint a particular class of assets. //! * **Freezer**: An account ID uniquely privileged to be able to freeze an account from @@ -54,8 +54,8 @@ //! * **Non-fungible asset**: An asset for which each unit has unique characteristics. //! * **Owner**: An account ID uniquely privileged to be able to destroy a particular asset class, //! or to set the Issuer, Freezer or Admin of that asset class. -//! * **Approval**: The act of allowing an account the permission to transfer some -//! balance of asset from the approving account into some third-party destination account. +//! * **Approval**: The act of allowing an account the permission to transfer some balance of asset +//! from the approving account into some third-party destination account. //! * **Sufficiency**: The idea of a minimum-balance of an asset being sufficient to allow the //! account's existence on the system without requiring any other existential-deposit. //! @@ -104,7 +104,8 @@ //! * `set_team`: Changes an asset class's Admin, Freezer and Issuer; called by the asset class's //! Owner. //! -//! Please refer to the [`Call`] enum and its associated variants for documentation on each function. +//! Please refer to the [`Call`] enum and its associated variants for documentation on each +//! function. //! //! ### Public Functions //! @@ -339,7 +340,8 @@ pub mod pallet { BadWitness, /// Minimum balance should be non-zero. MinBalanceZero, - /// No provider reference exists to allow a non-zero balance of a non-self-sufficient asset. + /// No provider reference exists to allow a non-zero balance of a non-self-sufficient + /// asset. NoProvider, /// Invalid metadata given. BadMetadata, @@ -418,8 +420,8 @@ pub mod pallet { /// - `id`: The identifier of the new asset. This must not be currently in use to identify /// an existing asset. /// - `owner`: The owner of this class of assets. The owner has full superuser permissions - /// over this asset, but may later change and configure the permissions using `transfer_ownership` - /// and `set_team`. + /// over this asset, but may later change and configure the permissions using + /// `transfer_ownership` and `set_team`. /// - `min_balance`: The minimum balance of this new asset that any single account must /// have. If an account's balance is reduced below this, then it collapses to zero. /// diff --git a/substrate/frame/assets/src/types.rs b/substrate/frame/assets/src/types.rs index 810b83506e..5e867550b3 100644 --- a/substrate/frame/assets/src/types.rs +++ b/substrate/frame/assets/src/types.rs @@ -183,7 +183,8 @@ pub enum ConversionError { MinBalanceZero, /// The asset is not present in storage. AssetMissing, - /// The asset is not sufficient and thus does not have a reliable `min_balance` so it cannot be converted. + /// The asset is not sufficient and thus does not have a reliable `min_balance` so it cannot be + /// converted. AssetNotSufficient, } @@ -210,10 +211,11 @@ where { type Error = ConversionError; - /// Convert the given balance value into an asset balance based on the ratio between the fungible's - /// minimum balance and the minimum asset balance. + /// Convert the given balance value into an asset balance based on the ratio between the + /// fungible's minimum balance and the minimum asset balance. /// - /// Will return `Err` if the asset is not found, not sufficient or the fungible's minimum balance is zero. + /// Will return `Err` if the asset is not found, not sufficient or the fungible's minimum + /// balance is zero. fn to_asset_balance( balance: BalanceOf, asset_id: AssetIdOf, diff --git a/substrate/frame/atomic-swap/src/lib.rs b/substrate/frame/atomic-swap/src/lib.rs index ac78024a10..b068dc7ba1 100644 --- a/substrate/frame/atomic-swap/src/lib.rs +++ b/substrate/frame/atomic-swap/src/lib.rs @@ -165,14 +165,14 @@ pub mod pallet { type SwapAction: SwapAction + Parameter; /// Limit of proof size. /// - /// Atomic swap is only atomic if once the proof is revealed, both parties can submit the proofs - /// on-chain. If A is the one that generates the proof, then it requires that either: + /// Atomic swap is only atomic if once the proof is revealed, both parties can submit the + /// proofs on-chain. If A is the one that generates the proof, then it requires that either: /// - A's blockchain has the same proof length limit as B's blockchain. /// - Or A's blockchain has shorter proof length limit as B's blockchain. /// - /// If B sees A is on a blockchain with larger proof length limit, then it should kindly refuse - /// to accept the atomic swap request if A generates the proof, and asks that B generates the - /// proof instead. + /// If B sees A is on a blockchain with larger proof length limit, then it should kindly + /// refuse to accept the atomic swap request if A generates the proof, and asks that B + /// generates the proof instead. #[pallet::constant] type ProofLimit: Get; } diff --git a/substrate/frame/aura/src/lib.rs b/substrate/frame/aura/src/lib.rs index ebb869194a..1138a3e850 100644 --- a/substrate/frame/aura/src/lib.rs +++ b/substrate/frame/aura/src/lib.rs @@ -28,7 +28,8 @@ //! //! ### Public Functions //! -//! - `slot_duration` - Determine the Aura slot-duration based on the Timestamp module configuration. +//! - `slot_duration` - Determine the Aura slot-duration based on the Timestamp module +//! configuration. //! //! ## Related Modules //! @@ -99,7 +100,8 @@ pub mod pallet { } } - // TODO [#3398] Generate offence report for all authorities that skipped their slots. + // TODO [#3398] Generate offence report for all authorities that skipped their + // slots. T::DbWeight::get().reads_writes(2, 1) } else { diff --git a/substrate/frame/authorship/src/lib.rs b/substrate/frame/authorship/src/lib.rs index 43d48df464..325f80c74a 100644 --- a/substrate/frame/authorship/src/lib.rs +++ b/substrate/frame/authorship/src/lib.rs @@ -140,8 +140,8 @@ pub mod pallet { /// further constraints on what uncles can be included, other than their ancestry. /// /// For PoW, as long as the seals are checked, there is no need to use anything - /// but the `VerifySeal` implementation as the filter. This is because the cost of making many equivocating - /// uncles is high. + /// but the `VerifySeal` implementation as the filter. This is because the cost of making + /// many equivocating uncles is high. /// /// For PoS, there is no such limitation, so a further constraint must be imposed /// beyond a seal check in order to prevent an arbitrary number of diff --git a/substrate/frame/babe/src/lib.rs b/substrate/frame/babe/src/lib.rs index cb2f2168a2..b39074bb3f 100644 --- a/substrate/frame/babe/src/lib.rs +++ b/substrate/frame/babe/src/lib.rs @@ -135,8 +135,8 @@ pub mod pallet { /// BABE requires some logic to be triggered on every block to query for whether an epoch /// has ended and to perform the transition to the next epoch. /// - /// Typically, the `ExternalTrigger` type should be used. An internal trigger should only be used - /// when no other module is responsible for changing authority set. + /// Typically, the `ExternalTrigger` type should be used. An internal trigger should only be + /// used when no other module is responsible for changing authority set. type EpochChangeTrigger: EpochChangeTrigger; /// A way to check whether a given validator is disabled and should not be authoring blocks. @@ -281,7 +281,8 @@ pub mod pallet { #[pallet::getter(fn lateness)] pub(super) type Lateness = StorageValue<_, T::BlockNumber, ValueQuery>; - /// The configuration for the current epoch. Should never be `None` as it is initialized in genesis. + /// The configuration for the current epoch. Should never be `None` as it is initialized in + /// genesis. #[pallet::storage] pub(super) type EpochConfig = StorageValue<_, BabeEpochConfiguration>; @@ -496,11 +497,11 @@ impl Pallet { }) } - /// DANGEROUS: Enact an epoch change. Should be done on every block where `should_epoch_change` has returned `true`, - /// and the caller is the only caller of this function. + /// DANGEROUS: Enact an epoch change. Should be done on every block where `should_epoch_change` + /// has returned `true`, and the caller is the only caller of this function. /// - /// Typically, this is not handled directly by the user, but by higher-level validator-set manager logic like - /// `pallet-session`. + /// Typically, this is not handled directly by the user, but by higher-level validator-set + /// manager logic like `pallet-session`. pub fn enact_epoch_change( authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, next_authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, diff --git a/substrate/frame/balances/src/lib.rs b/substrate/frame/balances/src/lib.rs index c955d917a6..7ab8a54de2 100644 --- a/substrate/frame/balances/src/lib.rs +++ b/substrate/frame/balances/src/lib.rs @@ -38,17 +38,18 @@ //! //! ### Terminology //! -//! - **Existential Deposit:** The minimum balance required to create or keep an account open. This prevents -//! "dust accounts" from filling storage. When the free plus the reserved balance (i.e. the total balance) -//! fall below this, then the account is said to be dead; and it loses its functionality as well as any -//! prior history and all information on it is removed from the chain's state. -//! No account should ever have a total balance that is strictly between 0 and the existential -//! deposit (exclusive). If this ever happens, it indicates either a bug in this pallet or an -//! erroneous raw mutation of storage. +//! - **Existential Deposit:** The minimum balance required to create or keep an account open. This +//! prevents "dust accounts" from filling storage. When the free plus the reserved balance (i.e. +//! the total balance) fall below this, then the account is said to be dead; and it loses its +//! functionality as well as any prior history and all information on it is removed from the +//! chain's state. No account should ever have a total balance that is strictly between 0 and the +//! existential deposit (exclusive). If this ever happens, it indicates either a bug in this +//! pallet or an erroneous raw mutation of storage. //! //! - **Total Issuance:** The total number of units in existence in a system. //! -//! - **Reaping an account:** The act of removing an account by resetting its nonce. Happens after its +//! - **Reaping an account:** The act of removing an account by resetting its nonce. Happens after +//! its //! total balance has become zero (or, strictly speaking, less than the Existential Deposit). //! //! - **Free Balance:** The portion of a balance that is not reserved. The free balance is the only @@ -57,18 +58,21 @@ //! - **Reserved Balance:** Reserved balance still belongs to the account holder, but is suspended. //! Reserved balance can still be slashed, but only after all the free balance has been slashed. //! -//! - **Imbalance:** A condition when some funds were credited or debited without equal and opposite accounting -//! (i.e. a difference between total issuance and account balances). Functions that result in an imbalance will -//! return an object of the `Imbalance` trait that can be managed within your runtime logic. (If an imbalance is -//! simply dropped, it should automatically maintain any book-keeping such as total issuance.) +//! - **Imbalance:** A condition when some funds were credited or debited without equal and opposite +//! accounting +//! (i.e. a difference between total issuance and account balances). Functions that result in an +//! imbalance will return an object of the `Imbalance` trait that can be managed within your runtime +//! logic. (If an imbalance is simply dropped, it should automatically maintain any book-keeping +//! such as total issuance.) //! -//! - **Lock:** A freeze on a specified amount of an account's free balance until a specified block number. Multiple +//! - **Lock:** A freeze on a specified amount of an account's free balance until a specified block +//! number. Multiple //! locks always operate over the same funds, so they "overlay" rather than "stack". //! //! ### Implementations //! -//! The Balances pallet provides implementations for the following traits. If these traits provide the functionality -//! that you need, then you can avoid coupling with the Balances pallet. +//! The Balances pallet provides implementations for the following traits. If these traits provide +//! the functionality that you need, then you can avoid coupling with the Balances pallet. //! //! - [`Currency`](frame_support::traits::Currency): Functions for dealing with a //! fungible assets system. @@ -78,8 +82,8 @@ //! - [`LockableCurrency`](frame_support::traits::LockableCurrency): Functions for //! dealing with accounts that allow liquidity restrictions. //! - [`Imbalance`](frame_support::traits::Imbalance): Functions for handling -//! imbalances between total issuance in the system and account balances. Must be used when a function -//! creates new funds (e.g. a reward) or destroys some funds (e.g. a system fee). +//! imbalances between total issuance in the system and account balances. Must be used when a +//! function creates new funds (e.g. a reward) or destroys some funds (e.g. a system fee). //! //! ## Interface //! @@ -94,7 +98,8 @@ //! //! ### Examples from the FRAME //! -//! The Contract pallet uses the `Currency` trait to handle gas payment, and its types inherit from `Currency`: +//! The Contract pallet uses the `Currency` trait to handle gas payment, and its types inherit from +//! `Currency`: //! //! ``` //! use frame_support::traits::Currency; @@ -249,18 +254,19 @@ pub mod pallet { /// The dispatch origin for this call must be `Signed` by the transactor. /// /// # - /// - Dependent on arguments but not critical, given proper implementations for - /// input config types. See related functions below. - /// - It contains a limited number of reads and writes internally and no complex computation. + /// - Dependent on arguments but not critical, given proper implementations for input config + /// types. See related functions below. + /// - It contains a limited number of reads and writes internally and no complex + /// computation. /// /// Related functions: /// /// - `ensure_can_withdraw` is always called internally but has a bounded complexity. /// - Transferring balances to accounts that did not exist before will cause - /// `T::OnNewAccount::on_new_account` to be called. + /// `T::OnNewAccount::on_new_account` to be called. /// - Removing enough funds from an account will trigger `T::DustRemoval::on_unbalanced`. - /// - `transfer_keep_alive` works the same way as `transfer`, but has an additional - /// check that the transfer will not kill the origin account. + /// - `transfer_keep_alive` works the same way as `transfer`, but has an additional check + /// that the transfer will not kill the origin account. /// --------------------------------- /// - Base Weight: 73.64 µs, worst case scenario (account created, account removed) /// - DB Weight: 1 Read and 1 Write to destination account @@ -344,8 +350,8 @@ pub mod pallet { /// Exactly as `transfer`, except the origin must be root and the source account may be /// specified. /// # - /// - Same as transfer, but additional read and write because the source account is - /// not assumed to be in the overlay. + /// - Same as transfer, but additional read and write because the source account is not + /// assumed to be in the overlay. /// # #[pallet::weight(T::WeightInfo::force_transfer())] pub fn force_transfer( @@ -403,8 +409,7 @@ pub mod pallet { /// - `keep_alive`: A boolean to determine if the `transfer_all` operation should send all /// of the funds the account has, causing the sender account to be killed (false), or /// transfer everything except at least the existential deposit, which will guarantee to - /// keep the sender account alive (true). - /// # + /// keep the sender account alive (true). # /// - O(1). Just like transfer, but reading the user's transferable balance first. /// # #[pallet::weight(T::WeightInfo::transfer_all())] @@ -1052,8 +1057,8 @@ impl, I: 'static> fungible::Inspect for Pallet if frame_system::Pallet::::can_dec_provider(who) && !keep_alive { liquid } else { - // `must_remain_to_exist` is the part of liquid balance which must remain to keep total over - // ED. + // `must_remain_to_exist` is the part of liquid balance which must remain to keep total + // over ED. let must_remain_to_exist = T::ExistentialDeposit::get().saturating_sub(a.total() - liquid); liquid.saturating_sub(must_remain_to_exist) @@ -1464,8 +1469,8 @@ where .checked_sub(&value) .ok_or(Error::::InsufficientBalance)?; - // NOTE: total stake being stored in the same type means that this could never overflow - // but better to be safe than sorry. + // NOTE: total stake being stored in the same type means that this could + // never overflow but better to be safe than sorry. to_account.free = to_account.free.checked_add(&value).ok_or(ArithmeticError::Overflow)?; @@ -1480,8 +1485,8 @@ where ) .map_err(|_| Error::::LiquidityRestrictions)?; - // TODO: This is over-conservative. There may now be other providers, and this pallet - // may not even be a provider. + // TODO: This is over-conservative. There may now be other providers, and + // this pallet may not even be a provider. let allow_death = existence_requirement == ExistenceRequirement::AllowDeath; let allow_death = allow_death && system::Pallet::::can_dec_provider(transactor); @@ -1509,9 +1514,9 @@ where /// Is a no-op if `value` to be slashed is zero or the account does not exist. /// /// NOTE: `slash()` prefers free balance, but assumes that reserve balance can be drawn - /// from in extreme circumstances. `can_slash()` should be used prior to `slash()` to avoid having - /// to draw from reserved funds, however we err on the side of punishment if things are inconsistent - /// or `can_slash` wasn't used appropriately. + /// from in extreme circumstances. `can_slash()` should be used prior to `slash()` to avoid + /// having to draw from reserved funds, however we err on the side of punishment if things are + /// inconsistent or `can_slash` wasn't used appropriately. fn slash(who: &T::AccountId, value: Self::Balance) -> (Self::NegativeImbalance, Self::Balance) { if value.is_zero() { return (NegativeImbalance::zero(), Zero::zero()) @@ -1528,7 +1533,8 @@ where -> Result<(Self::NegativeImbalance, Self::Balance), DispatchError> { // Best value is the most amount we can slash following liveness rules. let best_value = match attempt { - // First attempt we try to slash the full amount, and see if liveness issues happen. + // First attempt we try to slash the full amount, and see if liveness issues + // happen. 0 => value, // If acting as a critical provider (i.e. first attempt failed), then slash // as much as possible while leaving at least at ED. @@ -1548,7 +1554,8 @@ where account.reserved -= reserved_slash; // Safe because of above check Ok(( NegativeImbalance::new(free_slash + reserved_slash), - value - free_slash - reserved_slash, /* Safe because value is gt or eq total slashed */ + value - free_slash - reserved_slash, /* Safe because value is gt or + * eq total slashed */ )) } else { // Else we are done! @@ -1593,8 +1600,10 @@ where /// /// This function is a no-op if: /// - the `value` to be deposited is zero; or - /// - the `value` to be deposited is less than the required ED and the account does not yet exist; or - /// - the deposit would necessitate the account to exist and there are no provider references; or + /// - the `value` to be deposited is less than the required ED and the account does not yet + /// exist; or + /// - the deposit would necessitate the account to exist and there are no provider references; + /// or /// - `value` is so large it would cause the balance of `who` to overflow. fn deposit_creating(who: &T::AccountId, value: Self::Balance) -> Self::PositiveImbalance { if value.is_zero() { @@ -1744,8 +1753,8 @@ where let actual = match Self::mutate_account(who, |account| { let actual = cmp::min(account.reserved, value); account.reserved -= actual; - // defensive only: this can never fail since total issuance which is at least free+reserved - // fits into the same data type. + // defensive only: this can never fail since total issuance which is at least + // free+reserved fits into the same data type. account.free = account.free.saturating_add(actual); actual }) { @@ -1991,7 +2000,8 @@ where status, )?; - // remain should always be zero but just to be defensive here + // remain should always be zero but just to be defensive + // here let actual = to_change.saturating_sub(remain); // this add can't overflow but just to be defensive. @@ -2009,7 +2019,8 @@ where status, )?; - // remain should always be zero but just to be defensive here + // remain should always be zero but just to be defensive + // here let actual = to_change.saturating_sub(remain); reserves diff --git a/substrate/frame/benchmarking/src/analysis.rs b/substrate/frame/benchmarking/src/analysis.rs index fffa6828ce..4944de8553 100644 --- a/substrate/frame/benchmarking/src/analysis.rs +++ b/substrate/frame/benchmarking/src/analysis.rs @@ -74,8 +74,8 @@ impl TryFrom> for AnalysisChoice { } impl Analysis { - // Useful for when there are no components, and we just need an median value of the benchmark results. - // Note: We choose the median value because it is more robust to outliers. + // Useful for when there are no components, and we just need an median value of the benchmark + // results. Note: We choose the median value because it is more robust to outliers. fn median_value(r: &Vec, selector: BenchmarkSelector) -> Option { if r.is_empty() { return None diff --git a/substrate/frame/benchmarking/src/lib.rs b/substrate/frame/benchmarking/src/lib.rs index 1680e73315..673f6dee6f 100644 --- a/substrate/frame/benchmarking/src/lib.rs +++ b/substrate/frame/benchmarking/src/lib.rs @@ -675,7 +675,7 @@ macro_rules! benchmark_backend { // Every variant must implement [`BenchmarkingSetup`]. // // ```nocompile -// +// // struct Transfer; // impl BenchmarkingSetup for Transfer { ... } // @@ -1032,11 +1032,12 @@ macro_rules! impl_benchmark_test { /// ); /// ``` /// -/// There is an optional fourth argument, with keyword syntax: `benchmarks_path = path_to_benchmarks_invocation`. -/// In the typical case in which this macro is in the same module as the `benchmarks!` invocation, -/// you don't need to supply this. However, if the `impl_benchmark_test_suite!` invocation is in a -/// different module than the `benchmarks!` invocation, then you should provide the path to the -/// module containing the `benchmarks!` invocation: +/// There is an optional fourth argument, with keyword syntax: `benchmarks_path = +/// path_to_benchmarks_invocation`. In the typical case in which this macro is in the same module as +/// the `benchmarks!` invocation, you don't need to supply this. However, if the +/// `impl_benchmark_test_suite!` invocation is in a different module than the `benchmarks!` +/// invocation, then you should provide the path to the module containing the `benchmarks!` +/// invocation: /// /// ```rust,ignore /// mod benches { @@ -1065,7 +1066,8 @@ macro_rules! impl_benchmark_test { /// to these restrictions: /// /// - It must be the name of a method applied to the output of the `new_test_ext` argument. -/// - That method must have a signature capable of receiving a single argument of the form `impl FnOnce()`. +/// - That method must have a signature capable of receiving a single argument of the form `impl +/// FnOnce()`. // ## Notes (not for rustdoc) // // The biggest challenge for this macro is communicating the actual test functions to be run. We @@ -1258,8 +1260,8 @@ pub fn show_benchmark_debug_info( /// ``` /// /// The `whitelist` is a parameter you pass to control the DB read/write tracking. -/// We use a vector of [TrackedStorageKey](./struct.TrackedStorageKey.html), which is a simple struct used to set -/// if a key has been read or written to. +/// We use a vector of [TrackedStorageKey](./struct.TrackedStorageKey.html), which is a simple +/// struct used to set if a key has been read or written to. /// /// For values that should be skipped entirely, we can just pass `key.into()`. For example: /// diff --git a/substrate/frame/benchmarking/src/utils.rs b/substrate/frame/benchmarking/src/utils.rs index c9662bf6fd..8be25f7f5e 100644 --- a/substrate/frame/benchmarking/src/utils.rs +++ b/substrate/frame/benchmarking/src/utils.rs @@ -202,7 +202,8 @@ pub trait Benchmarking { fn add_to_whitelist(&mut self, add: TrackedStorageKey) { let mut whitelist = self.get_whitelist(); match whitelist.iter_mut().find(|x| x.key == add.key) { - // If we already have this key in the whitelist, update to be the most constrained value. + // If we already have this key in the whitelist, update to be the most constrained + // value. Some(item) => { item.reads += add.reads; item.writes += add.writes; @@ -239,8 +240,8 @@ pub trait Benchmarking { /// extrinsic, so these are sometimes just called "extrinsics". /// /// Parameters - /// - `extra`: Also return benchmarks marked "extra" which would otherwise not be - /// needed for weight calculation. + /// - `extra`: Also return benchmarks marked "extra" which would otherwise not be needed for + /// weight calculation. fn benchmarks(extra: bool) -> Vec; /// Run the benchmarks for this pallet. diff --git a/substrate/frame/bounties/src/lib.rs b/substrate/frame/bounties/src/lib.rs index 4700b1d34d..a5be4a00cb 100644 --- a/substrate/frame/bounties/src/lib.rs +++ b/substrate/frame/bounties/src/lib.rs @@ -161,7 +161,8 @@ pub enum BountyStatus { Approved, /// The bounty is funded and waiting for curator assignment. Funded, - /// A curator has been proposed by the `ApproveOrigin`. Waiting for acceptance from the curator. + /// A curator has been proposed by the `ApproveOrigin`. Waiting for acceptance from the + /// curator. CuratorProposed { /// The assigned curator of this bounty. curator: AccountId, diff --git a/substrate/frame/bounties/src/tests.rs b/substrate/frame/bounties/src/tests.rs index f945d0b2db..ff058a3601 100644 --- a/substrate/frame/bounties/src/tests.rs +++ b/substrate/frame/bounties/src/tests.rs @@ -774,7 +774,8 @@ fn cancel_and_refund() { assert_ok!(Bounties::close_bounty(Origin::root(), 0)); - assert_eq!(Treasury::pot(), 85); // - 25 + 10 + // `- 25 + 10` + assert_eq!(Treasury::pot(), 85); }); } diff --git a/substrate/frame/contracts/src/benchmarking/mod.rs b/substrate/frame/contracts/src/benchmarking/mod.rs index 9760cddcc5..e36f917386 100644 --- a/substrate/frame/contracts/src/benchmarking/mod.rs +++ b/substrate/frame/contracts/src/benchmarking/mod.rs @@ -114,7 +114,8 @@ where Endow::CollectRent => { // storage_size cannot be zero because otherwise a contract that is just above // the subsistence threshold does not pay rent given a large enough subsistence - // threshold. But we need rent payments to occur in order to benchmark for worst cases. + // threshold. But we need rent payments to occur in order to benchmark for worst + // cases. let storage_size = u32::MAX / 10; // Endowment should be large but not as large to inhibit rent payments. diff --git a/substrate/frame/contracts/src/chain_extension.rs b/substrate/frame/contracts/src/chain_extension.rs index 13696240fe..1408010293 100644 --- a/substrate/frame/contracts/src/chain_extension.rs +++ b/substrate/frame/contracts/src/chain_extension.rs @@ -86,8 +86,8 @@ pub trait ChainExtension { /// imported wasm function. /// /// # Parameters - /// - `func_id`: The first argument to `seal_call_chain_extension`. Usually used to - /// determine which function to realize. + /// - `func_id`: The first argument to `seal_call_chain_extension`. Usually used to determine + /// which function to realize. /// - `env`: Access to the remaining arguments and the execution environment. /// /// # Return diff --git a/substrate/frame/contracts/src/exec.rs b/substrate/frame/contracts/src/exec.rs index a3b48ca3bc..ef19c443c7 100644 --- a/substrate/frame/contracts/src/exec.rs +++ b/substrate/frame/contracts/src/exec.rs @@ -173,8 +173,8 @@ pub trait Ext: sealing::Sealed { /// Instantiate a contract from the given code. /// /// Returns the original code size of the called contract. - /// The newly created account will be associated with `code`. `value` specifies the amount of value - /// transferred from this to the newly created account (also known as endowment). + /// The newly created account will be associated with `code`. `value` specifies the amount of + /// value transferred from this to the newly created account (also known as endowment). /// /// # Return Value /// @@ -190,8 +190,8 @@ pub trait Ext: sealing::Sealed { /// Transfer all funds to `beneficiary` and delete the contract. /// - /// Since this function removes the self contract eagerly, if succeeded, no further actions should - /// be performed on this `Ext` instance. + /// Since this function removes the self contract eagerly, if succeeded, no further actions + /// should be performed on this `Ext` instance. /// /// This function will fail if the same contract is present on the contract /// call stack. @@ -199,8 +199,8 @@ pub trait Ext: sealing::Sealed { /// Restores the given destination contract sacrificing the current one. /// - /// Since this function removes the self contract eagerly, if succeeded, no further actions should - /// be performed on this `Ext` instance. + /// Since this function removes the self contract eagerly, if succeeded, no further actions + /// should be performed on this `Ext` instance. /// /// This function will fail if the same contract is present /// on the contract call stack. @@ -1283,8 +1283,8 @@ mod sealing { /// These tests exercise the executive layer. /// -/// In these tests the VM/loader are mocked. Instead of dealing with wasm bytecode they use simple closures. -/// This allows you to tackle executive logic more thoroughly without writing a +/// In these tests the VM/loader are mocked. Instead of dealing with wasm bytecode they use simple +/// closures. This allows you to tackle executive logic more thoroughly without writing a /// wasm VM code. #[cfg(test)] mod tests { diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index 4860937c42..87db8048b3 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -17,43 +17,47 @@ //! # Contract Pallet //! -//! The Contract module provides functionality for the runtime to deploy and execute WebAssembly smart-contracts. +//! The Contract module provides functionality for the runtime to deploy and execute WebAssembly +//! smart-contracts. //! //! - [`Config`] //! - [`Call`] //! //! ## Overview //! -//! This module extends accounts based on the [`Currency`] trait to have smart-contract functionality. It can -//! be used with other modules that implement accounts based on [`Currency`]. These "smart-contract accounts" -//! have the ability to instantiate smart-contracts and make calls to other contract and non-contract accounts. +//! This module extends accounts based on the [`Currency`] trait to have smart-contract +//! functionality. It can be used with other modules that implement accounts based on [`Currency`]. +//! These "smart-contract accounts" have the ability to instantiate smart-contracts and make calls +//! to other contract and non-contract accounts. //! //! The smart-contract code is stored once in a code cache, and later retrievable via its hash. -//! This means that multiple smart-contracts can be instantiated from the same hash, without replicating -//! the code each time. +//! This means that multiple smart-contracts can be instantiated from the same hash, without +//! replicating the code each time. //! -//! When a smart-contract is called, its associated code is retrieved via the code hash and gets executed. -//! This call can alter the storage entries of the smart-contract account, instantiate new smart-contracts, -//! or call other smart-contracts. +//! When a smart-contract is called, its associated code is retrieved via the code hash and gets +//! executed. This call can alter the storage entries of the smart-contract account, instantiate new +//! smart-contracts, or call other smart-contracts. //! -//! Finally, when an account is reaped, its associated code and storage of the smart-contract account -//! will also be deleted. +//! Finally, when an account is reaped, its associated code and storage of the smart-contract +//! account will also be deleted. //! //! ### Gas //! -//! Senders must specify a gas limit with every call, as all instructions invoked by the smart-contract require gas. -//! Unused gas is refunded after the call, regardless of the execution outcome. +//! Senders must specify a gas limit with every call, as all instructions invoked by the +//! smart-contract require gas. Unused gas is refunded after the call, regardless of the execution +//! outcome. //! -//! If the gas limit is reached, then all calls and state changes (including balance transfers) are only -//! reverted at the current call's contract level. For example, if contract A calls B and B runs out of gas mid-call, -//! then all of B's calls are reverted. Assuming correct error handling by contract A, A's other calls and state -//! changes still persist. +//! If the gas limit is reached, then all calls and state changes (including balance transfers) are +//! only reverted at the current call's contract level. For example, if contract A calls B and B +//! runs out of gas mid-call, then all of B's calls are reverted. Assuming correct error handling by +//! contract A, A's other calls and state changes still persist. //! //! ### Notable Scenarios //! -//! Contract call failures are not always cascading. When failures occur in a sub-call, they do not "bubble up", -//! and the call will only revert at the specific contract level. For example, if contract A calls contract B, and B -//! fails, A can decide how to handle that failure, either proceeding or reverting A's changes. +//! Contract call failures are not always cascading. When failures occur in a sub-call, they do not +//! "bubble up", and the call will only revert at the specific contract level. For example, if +//! contract A calls contract B, and B fails, A can decide how to handle that failure, either +//! proceeding or reverting A's changes. //! //! ## Interface //! @@ -226,17 +230,18 @@ pub mod pallet { /// deposited while the contract is alive. Costs for additional storage are added to /// this base cost. /// - /// This is a simple way to ensure that contracts with empty storage eventually get deleted by - /// making them pay rent. This creates an incentive to remove them early in order to save rent. + /// This is a simple way to ensure that contracts with empty storage eventually get deleted + /// by making them pay rent. This creates an incentive to remove them early in order to save + /// rent. #[pallet::constant] type DepositPerContract: Get>; /// The balance a contract needs to deposit per storage byte to stay alive indefinitely. /// - /// Let's suppose the deposit is 1,000 BU (balance units)/byte and the rent is 1 BU/byte/day, - /// then a contract with 1,000,000 BU that uses 1,000 bytes of storage would pay no rent. - /// But if the balance reduced to 500,000 BU and the storage stayed the same at 1,000, - /// then it would pay 500 BU/day. + /// Let's suppose the deposit is 1,000 BU (balance units)/byte and the rent is 1 + /// BU/byte/day, then a contract with 1,000,000 BU that uses 1,000 bytes of storage would + /// pay no rent. But if the balance reduced to 500,000 BU and the storage stayed the same at + /// 1,000, then it would pay 500 BU/day. #[pallet::constant] type DepositPerStorageByte: Get>; @@ -353,7 +358,8 @@ pub mod pallet { /// /// Instantiation is executed as follows: /// - /// - The supplied `code` is instrumented, deployed, and a `code_hash` is created for that code. + /// - The supplied `code` is instrumented, deployed, and a `code_hash` is created for that + /// code. /// - If the `code_hash` already exists on the chain the underlying `code` will be shared. /// - The destination address is computed based on the sender, code_hash and the salt. /// - The smart-contract account is created at the computed address. @@ -458,7 +464,8 @@ pub mod pallet { // Add some advantage for block producers (who send unsigned extrinsics) by // adding a handicap: for signed extrinsics we use a slightly older block number - // for the eviction check. This can be viewed as if we pushed regular users back in past. + // for the eviction check. This can be viewed as if we pushed regular users back in + // past. let handicap = if signed { T::SignedClaimHandicap::get() } else { Zero::zero() }; // If poking the contract has lead to eviction of the contract, give out the rewards. @@ -530,8 +537,8 @@ pub mod pallet { /// # Params /// /// - `contract`: The contract that emitted the event. - /// - `data`: Data supplied by the contract. Metadata generated during contract - /// compilation is needed to decode it. + /// - `data`: Data supplied by the contract. Metadata generated during contract compilation + /// is needed to decode it. ContractEmitted(T::AccountId, Vec), /// A code with the specified hash was removed. diff --git a/substrate/frame/contracts/src/rent.rs b/substrate/frame/contracts/src/rent.rs index 9446b027ec..336f03153c 100644 --- a/substrate/frame/contracts/src/rent.rs +++ b/substrate/frame/contracts/src/rent.rs @@ -96,8 +96,8 @@ where /// /// The `handicap` parameter gives a way to check the rent to a moment in the past instead /// of current block. E.g. if the contract is going to be evicted at the current block, - /// `handicap = 1` can defer the eviction for 1 block. This is useful to handicap certain snitchers - /// relative to others. + /// `handicap = 1` can defer the eviction for 1 block. This is useful to handicap certain + /// snitchers relative to others. /// /// NOTE this function performs eviction eagerly. All changes are read and written directly to /// storage. @@ -148,12 +148,12 @@ where /// accessed at the beginning of the current block. Returns `None` in case if the contract was /// evicted before or as a result of the rent collection. /// - /// The returned value is only an estimation. It doesn't take into account any top ups, changing the - /// rent allowance, or any problems coming from withdrawing the dues. + /// The returned value is only an estimation. It doesn't take into account any top ups, changing + /// the rent allowance, or any problems coming from withdrawing the dues. /// /// NOTE that this is not a side-effect free function! It will actually collect rent and then - /// compute the projection. This function is only used for implementation of an RPC method through - /// `RuntimeApi` meaning that the changes will be discarded anyway. + /// compute the projection. This function is only used for implementation of an RPC method + /// through `RuntimeApi` meaning that the changes will be discarded anyway. pub fn compute_projection(account: &T::AccountId) -> RentProjectionResult { use ContractAccessError::IsTombstone; @@ -357,8 +357,8 @@ where /// Returns amount of funds available to consume by rent mechanism. /// - /// Rent mechanism cannot consume more than `rent_allowance` set by the contract and it cannot make - /// the balance lower than [`subsistence_threshold`]. + /// Rent mechanism cannot consume more than `rent_allowance` set by the contract and it cannot + /// make the balance lower than [`subsistence_threshold`]. /// /// In case the toal_balance is below the subsistence threshold, this function returns `None`. fn rent_budget( @@ -381,8 +381,8 @@ where /// Consider the case for rent payment of the given account and returns a `Verdict`. /// - /// Use `handicap` in case you want to change the reference block number. (To get more details see - /// `try_eviction` ). + /// Use `handicap` in case you want to change the reference block number. (To get more details + /// see `try_eviction` ). fn consider_case( account: &T::AccountId, current_block_number: T::BlockNumber, @@ -435,8 +435,8 @@ where .unwrap_or_else(|| >::max_value()); let insufficient_rent = rent_budget < dues; - // If the rent payment cannot be withdrawn due to locks on the account balance, then evict the - // account. + // If the rent payment cannot be withdrawn due to locks on the account balance, then evict + // the account. // // NOTE: This seems problematic because it provides a way to tombstone an account while // avoiding the last rent payment. In effect, someone could retroactively set rent_allowance @@ -566,8 +566,8 @@ impl OutstandingAmount { enum Verdict { /// The contract is exempted from paying rent. /// - /// For example, it already paid its rent in the current block, or it has enough deposit for not - /// paying rent at all. + /// For example, it already paid its rent in the current block, or it has enough deposit for + /// not paying rent at all. Exempt, /// The contract cannot afford payment within its rent budget so it gets evicted. However, /// because its balance is greater than the subsistence threshold it leaves a tombstone. diff --git a/substrate/frame/contracts/src/storage.rs b/substrate/frame/contracts/src/storage.rs index 847b57c89d..0781983483 100644 --- a/substrate/frame/contracts/src/storage.rs +++ b/substrate/frame/contracts/src/storage.rs @@ -167,8 +167,8 @@ where { /// Reads a storage kv pair of a contract. /// - /// The read is performed from the `trie_id` only. The `address` is not necessary. If the contract - /// doesn't store under the given `key` `None` is returned. + /// The read is performed from the `trie_id` only. The `address` is not necessary. If the + /// contract doesn't store under the given `key` `None` is returned. pub fn read(trie_id: &TrieId, key: &StorageKey) -> Option> { child::get_raw(&child_trie_info(&trie_id), &blake2_256(key)) } @@ -230,7 +230,8 @@ where Ok(()) } - /// Creates a new contract descriptor in the storage with the given code hash at the given address. + /// Creates a new contract descriptor in the storage with the given code hash at the given + /// address. /// /// Returns `Err` if there is already a contract (or a tombstone) exists at the given address. pub fn new_contract( diff --git a/substrate/frame/contracts/src/wasm/code_cache.rs b/substrate/frame/contracts/src/wasm/code_cache.rs index 06329a7e81..0a20485cab 100644 --- a/substrate/frame/contracts/src/wasm/code_cache.rs +++ b/substrate/frame/contracts/src/wasm/code_cache.rs @@ -23,9 +23,10 @@ //! - Before running contract code we check if the cached code has the schedule version that //! is equal to the current saved schedule. //! If it is equal then run the code, if it isn't reinstrument with the current schedule. -//! - When we update the schedule we want it to have strictly greater version than the current saved one: -//! this guarantees that every instrumented contract code in cache cannot have the version equal to the current one. -//! Thus, before executing a contract it should be reinstrument with new schedule. +//! - When we update the schedule we want it to have strictly greater version than the current saved +//! one: +//! this guarantees that every instrumented contract code in cache cannot have the version equal to +//! the current one. Thus, before executing a contract it should be reinstrument with new schedule. #[cfg(feature = "runtime-benchmarks")] pub use self::private::reinstrument; diff --git a/substrate/frame/contracts/src/wasm/prepare.rs b/substrate/frame/contracts/src/wasm/prepare.rs index 280dedc39e..c766914f3d 100644 --- a/substrate/frame/contracts/src/wasm/prepare.rs +++ b/substrate/frame/contracts/src/wasm/prepare.rs @@ -279,8 +279,7 @@ impl<'a, T: Config> ContractModule<'a, T> { /// /// This accomplishes two tasks: /// - /// - checks any imported function against defined host functions set, incl. - /// their signatures. + /// - checks any imported function against defined host functions set, incl. their signatures. /// - if there is a memory import, returns it's descriptor /// `import_fn_banlist`: list of function names that are disallowed to be imported fn scan_imports( diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index c04f25766d..2edd7b8209 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -534,8 +534,8 @@ where /// when the caller is not interested in the result. /// /// `create_token` can optionally instruct this function to charge the gas meter with the token - /// it returns. `create_token` receives the variable amount of bytes that are about to be copied by - /// this function. + /// it returns. `create_token` receives the variable amount of bytes that are about to be copied + /// by this function. /// /// In addition to the error conditions of `write_sandbox_memory` this functions returns /// `Err` if the size of the buffer located at `out_ptr` is too small to fit `buf`. diff --git a/substrate/frame/democracy/src/lib.rs b/substrate/frame/democracy/src/lib.rs index 2f955b70ab..7c2e53a817 100644 --- a/substrate/frame/democracy/src/lib.rs +++ b/substrate/frame/democracy/src/lib.rs @@ -46,12 +46,12 @@ //! - **Conviction:** An indication of a voter's strength of belief in their vote. An increase //! of one in conviction indicates that a token holder is willing to lock their tokens for twice //! as many lock periods after enactment. -//! - **Vote:** A value that can either be in approval ("Aye") or rejection ("Nay") -//! of a particular referendum. +//! - **Vote:** A value that can either be in approval ("Aye") or rejection ("Nay") of a particular +//! referendum. //! - **Proposal:** A submission to the chain that represents an action that a proposer (either an //! account or an external origin) suggests that the system adopt. -//! - **Referendum:** A proposal that is in the process of being voted on for -//! either acceptance or rejection as a change to the system. +//! - **Referendum:** A proposal that is in the process of being voted on for either acceptance or +//! rejection as a change to the system. //! - **Delegation:** The act of granting your voting power to the decisions of another account for //! up to a certain conviction. //! @@ -92,50 +92,50 @@ //! - `unlock` - Redetermine the account's balance lock, potentially making tokens available. //! //! Preimage actions: -//! - `note_preimage` - Registers the preimage for an upcoming proposal, requires -//! a deposit that is returned once the proposal is enacted. +//! - `note_preimage` - Registers the preimage for an upcoming proposal, requires a deposit that is +//! returned once the proposal is enacted. //! - `note_preimage_operational` - same but provided by `T::OperationalPreimageOrigin`. -//! - `note_imminent_preimage` - Registers the preimage for an upcoming proposal. -//! Does not require a deposit, but the proposal must be in the dispatch queue. +//! - `note_imminent_preimage` - Registers the preimage for an upcoming proposal. Does not require a +//! deposit, but the proposal must be in the dispatch queue. //! - `note_imminent_preimage_operational` - same but provided by `T::OperationalPreimageOrigin`. -//! - `reap_preimage` - Removes the preimage for an expired proposal. Will only -//! work under the condition that it's the same account that noted it and -//! after the voting period, OR it's a different account after the enactment period. +//! - `reap_preimage` - Removes the preimage for an expired proposal. Will only work under the +//! condition that it's the same account that noted it and after the voting period, OR it's a +//! different account after the enactment period. //! //! #### Cancellation Origin //! //! This call can only be made by the `CancellationOrigin`. //! -//! - `emergency_cancel` - Schedules an emergency cancellation of a referendum. -//! Can only happen once to a specific referendum. +//! - `emergency_cancel` - Schedules an emergency cancellation of a referendum. Can only happen once +//! to a specific referendum. //! //! #### ExternalOrigin //! //! This call can only be made by the `ExternalOrigin`. //! -//! - `external_propose` - Schedules a proposal to become a referendum once it is is legal -//! for an externally proposed referendum. +//! - `external_propose` - Schedules a proposal to become a referendum once it is is legal for an +//! externally proposed referendum. //! //! #### External Majority Origin //! //! This call can only be made by the `ExternalMajorityOrigin`. //! -//! - `external_propose_majority` - Schedules a proposal to become a majority-carries -//! referendum once it is legal for an externally proposed referendum. +//! - `external_propose_majority` - Schedules a proposal to become a majority-carries referendum +//! once it is legal for an externally proposed referendum. //! //! #### External Default Origin //! //! This call can only be made by the `ExternalDefaultOrigin`. //! -//! - `external_propose_default` - Schedules a proposal to become a negative-turnout-bias -//! referendum once it is legal for an externally proposed referendum. +//! - `external_propose_default` - Schedules a proposal to become a negative-turnout-bias referendum +//! once it is legal for an externally proposed referendum. //! //! #### Fast Track Origin //! //! This call can only be made by the `FastTrackOrigin`. //! -//! - `fast_track` - Schedules the current externally proposed proposal that -//! is "majority-carries" to become a referendum immediately. +//! - `fast_track` - Schedules the current externally proposed proposal that is "majority-carries" +//! to become a referendum immediately. //! //! #### Veto Origin //! @@ -263,11 +263,12 @@ pub mod pallet { type Currency: ReservableCurrency + LockableCurrency; - /// The minimum period of locking and the period between a proposal being approved and enacted. + /// The minimum period of locking and the period between a proposal being approved and + /// enacted. /// /// It should generally be a little more than the unstake period to ensure that - /// voting stakers have an opportunity to remove themselves from the system in the case where - /// they are on the losing side of a vote. + /// voting stakers have an opportunity to remove themselves from the system in the case + /// where they are on the losing side of a vote. #[pallet::constant] type EnactmentPeriod: Get; @@ -287,27 +288,27 @@ pub mod pallet { /// "super-majority-required" referendum. type ExternalOrigin: EnsureOrigin; - /// Origin from which the next tabled referendum may be forced; this allows for the tabling of - /// a majority-carries referendum. + /// Origin from which the next tabled referendum may be forced; this allows for the tabling + /// of a majority-carries referendum. type ExternalMajorityOrigin: EnsureOrigin; - /// Origin from which the next tabled referendum may be forced; this allows for the tabling of - /// a negative-turnout-bias (default-carries) referendum. + /// Origin from which the next tabled referendum may be forced; this allows for the tabling + /// of a negative-turnout-bias (default-carries) referendum. type ExternalDefaultOrigin: EnsureOrigin; - /// Origin from which the next majority-carries (or more permissive) referendum may be tabled to - /// vote according to the `FastTrackVotingPeriod` asynchronously in a similar manner to the - /// emergency origin. It retains its threshold method. + /// Origin from which the next majority-carries (or more permissive) referendum may be + /// tabled to vote according to the `FastTrackVotingPeriod` asynchronously in a similar + /// manner to the emergency origin. It retains its threshold method. type FastTrackOrigin: EnsureOrigin; - /// Origin from which the next majority-carries (or more permissive) referendum may be tabled to - /// vote immediately and asynchronously in a similar manner to the emergency origin. It retains - /// its threshold method. + /// Origin from which the next majority-carries (or more permissive) referendum may be + /// tabled to vote immediately and asynchronously in a similar manner to the emergency + /// origin. It retains its threshold method. type InstantOrigin: EnsureOrigin; - /// Indicator for whether an emergency origin is even allowed to happen. Some chains may want - /// to set this permanently to `false`, others may want to condition it on things such as - /// an upgrade having happened recently. + /// Indicator for whether an emergency origin is even allowed to happen. Some chains may + /// want to set this permanently to `false`, others may want to condition it on things such + /// as an upgrade having happened recently. #[pallet::constant] type InstantAllowed: Get; @@ -446,8 +447,8 @@ pub mod pallet { /// True if the last referendum tabled was submitted externally. False if it was a public /// proposal. - // TODO: There should be any number of tabling origins, not just public and "external" (council). - // https://github.com/paritytech/substrate/issues/5322 + // TODO: There should be any number of tabling origins, not just public and "external" + // (council). https://github.com/paritytech/substrate/issues/5322 #[pallet::storage] pub type LastTabledWasExternal = StorageValue<_, bool, ValueQuery>; @@ -508,7 +509,8 @@ pub mod pallet { pub enum Event { /// A motion has been proposed by a public account. \[proposal_index, deposit\] Proposed(PropIndex, BalanceOf), - /// A public proposal has been tabled for referendum vote. \[proposal_index, deposit, depositors\] + /// A public proposal has been tabled for referendum vote. \[proposal_index, deposit, + /// depositors\] Tabled(PropIndex, BalanceOf, Vec), /// An external proposal has been tabled. ExternalTabled, @@ -824,7 +826,8 @@ pub mod pallet { delay: T::BlockNumber, ) -> DispatchResult { // Rather complicated bit of code to ensure that either: - // - `voting_period` is at least `FastTrackVotingPeriod` and `origin` is `FastTrackOrigin`; or + // - `voting_period` is at least `FastTrackVotingPeriod` and `origin` is + // `FastTrackOrigin`; or // - `InstantAllowed` is `true` and `origin` is `InstantOrigin`. let maybe_ensure_instant = if voting_period < T::FastTrackVotingPeriod::get() { Some(origin) @@ -932,8 +935,8 @@ pub mod pallet { /// - `to`: The account whose voting the `target` account's voting power will follow. /// - `conviction`: The conviction that will be attached to the delegated votes. When the /// account is undelegated, the funds will be locked for the corresponding period. - /// - `balance`: The amount of the account's balance to be used in delegating. This must - /// not be more than the account's current balance. + /// - `balance`: The amount of the account's balance to be used in delegating. This must not + /// be more than the account's current balance. /// /// Emits `Delegated`. /// @@ -1035,8 +1038,9 @@ pub mod pallet { encoded_proposal: Vec, ) -> DispatchResultWithPostInfo { Self::note_imminent_preimage_inner(ensure_signed(origin)?, encoded_proposal)?; - // We check that this preimage was not uploaded before in `note_imminent_preimage_inner`, - // thus this call can only be successful once. If successful, user does not pay a fee. + // We check that this preimage was not uploaded before in + // `note_imminent_preimage_inner`, thus this call can only be successful once. If + // successful, user does not pay a fee. Ok(Pays::No.into()) } @@ -1051,8 +1055,9 @@ pub mod pallet { ) -> DispatchResultWithPostInfo { let who = T::OperationalPreimageOrigin::ensure_origin(origin)?; Self::note_imminent_preimage_inner(who, encoded_proposal)?; - // We check that this preimage was not uploaded before in `note_imminent_preimage_inner`, - // thus this call can only be successful once. If successful, user does not pay a fee. + // We check that this preimage was not uploaded before in + // `note_imminent_preimage_inner`, thus this call can only be successful once. If + // successful, user does not pay a fee. Ok(Pays::No.into()) } @@ -1061,8 +1066,8 @@ pub mod pallet { /// The dispatch origin of this call must be _Signed_. /// /// - `proposal_hash`: The preimage hash of a proposal. - /// - `proposal_length_upper_bound`: an upper bound on length of the proposal. - /// Extrinsic is weighted according to this value with no refund. + /// - `proposal_length_upper_bound`: an upper bound on length of the proposal. Extrinsic is + /// weighted according to this value with no refund. /// /// This will only work after `VotingPeriod` blocks from the time that the preimage was /// noted, if it's the same account doing it. If it's a different account, then it'll only @@ -1620,11 +1625,10 @@ impl Pallet { /// Table the waiting public proposal with the highest backing for a vote. fn launch_public(now: T::BlockNumber) -> DispatchResult { let mut public_props = Self::public_props(); - if let Some((winner_index, _)) = public_props.iter() - .enumerate() - .max_by_key(|x| Self::backing_for((x.1).0).unwrap_or_else(Zero::zero) - /* ^^ defensive only: All current public proposals have an amount locked*/) - { + if let Some((winner_index, _)) = public_props.iter().enumerate().max_by_key( + // defensive only: All current public proposals have an amount locked + |x| Self::backing_for((x.1).0).unwrap_or_else(Zero::zero), + ) { let (prop_index, proposal, _) = public_props.swap_remove(winner_index); >::put(public_props); diff --git a/substrate/frame/election-provider-multi-phase/src/lib.rs b/substrate/frame/election-provider-multi-phase/src/lib.rs index a115d12c8a..44a4d66ca4 100644 --- a/substrate/frame/election-provider-multi-phase/src/lib.rs +++ b/substrate/frame/election-provider-multi-phase/src/lib.rs @@ -334,8 +334,8 @@ pub enum Phase { /// number. /// /// We do not yet check whether the unsigned phase is active or passive. The intent is for the - /// blockchain to be able to declare: "I believe that there exists an adequate signed solution," - /// advising validators not to bother running the unsigned offchain worker. + /// blockchain to be able to declare: "I believe that there exists an adequate signed + /// solution," advising validators not to bother running the unsigned offchain worker. /// /// As validator nodes are free to edit their OCW code, they could simply ignore this advisory /// and always compute their own solution. However, by default, when the unsigned phase is @@ -716,20 +716,23 @@ pub mod pallet { Phase::Signed | Phase::Off if remaining <= unsigned_deadline && remaining > Zero::zero() => { - // our needs vary according to whether or not the unsigned phase follows a signed phase + // our needs vary according to whether or not the unsigned phase follows a + // signed phase let (need_snapshot, enabled, signed_weight) = if current_phase == Phase::Signed { - // there was previously a signed phase: close the signed phase, no need for snapshot. + // there was previously a signed phase: close the signed phase, no need for + // snapshot. // // Notes: // - // - `Self::finalize_signed_phase()` also appears in `fn do_elect`. This is - // a guard against the case that `elect` is called prematurely. This adds - // a small amount of overhead, but that is unfortunately unavoidable. + // - `Self::finalize_signed_phase()` also appears in `fn do_elect`. This + // is a guard against the case that `elect` is called prematurely. This + // adds a small amount of overhead, but that is unfortunately + // unavoidable. let (_success, weight) = Self::finalize_signed_phase(); // In the future we can consider disabling the unsigned phase if the signed - // phase completes successfully, but for now we're enabling it unconditionally - // as a defensive measure. + // phase completes successfully, but for now we're enabling it + // unconditionally as a defensive measure. (false, true, weight) } else { // No signed phase: create a new snapshot, definitely `enable` the unsigned @@ -1068,6 +1071,7 @@ pub mod pallet { #[pallet::origin] pub struct Origin(PhantomData); + #[pallet::validate_unsigned] impl ValidateUnsigned for Pallet { type Call = Call; @@ -1320,7 +1324,8 @@ impl Pallet { >::put(desired_targets); // instead of using storage APIs, we do a manual encoding into a fixed-size buffer. - // `encoded_size` encodes it without storing it anywhere, this should not cause any allocation. + // `encoded_size` encodes it without storing it anywhere, this should not cause any + // allocation. let snapshot = RoundSnapshot { voters, targets }; let size = snapshot.encoded_size(); log!(info, "snapshot pre-calculated size {:?}", size); @@ -1473,7 +1478,8 @@ impl Pallet { // We have to unconditionally try finalizing the signed phase here. There are only two // possibilities: // - // - signed phase was open, in which case this is essential for correct functioning of the system + // - signed phase was open, in which case this is essential for correct functioning of the + // system // - signed phase was complete or not started, in which case finalization is idempotent and // inexpensive (1 read of an empty vector). let (_, signed_finalize_weight) = Self::finalize_signed_phase(); diff --git a/substrate/frame/elections-phragmen/src/lib.rs b/substrate/frame/elections-phragmen/src/lib.rs index b67680b9ab..12e6965633 100644 --- a/substrate/frame/elections-phragmen/src/lib.rs +++ b/substrate/frame/elections-phragmen/src/lib.rs @@ -401,9 +401,9 @@ pub mod pallet { /// origin is removed as a runner-up. /// - `origin` is a current member. In this case, the deposit is unreserved and origin is /// removed as a member, consequently not being a candidate for the next round anymore. - /// Similar to [`remove_member`](Self::remove_member), if replacement runners exists, - /// they are immediately used. If the prime is renouncing, then no prime will exist until - /// the next round. + /// Similar to [`remove_member`](Self::remove_member), if replacement runners exists, they + /// are immediately used. If the prime is renouncing, then no prime will exist until the + /// next round. /// /// The dispatch origin of this call must be signed, and have one of the above roles. /// @@ -673,9 +673,10 @@ pub mod pallet { "Genesis member does not have enough stake.", ); - // Note: all members will only vote for themselves, hence they must be given exactly - // their own stake as total backing. Any sane election should behave as such. - // Nonetheless, stakes will be updated for term 1 onwards according to the election. + // Note: all members will only vote for themselves, hence they must be given + // exactly their own stake as total backing. Any sane election should behave as + // such. Nonetheless, stakes will be updated for term 1 onwards according to the + // election. Members::::mutate(|members| { match members.binary_search_by(|m| m.who.cmp(member)) { Ok(_) => @@ -692,9 +693,9 @@ pub mod pallet { }); // set self-votes to make persistent. Genesis voters don't have any bond, nor do - // they have any lock. NOTE: this means that we will still try to remove a lock once - // this genesis voter is removed, and for now it is okay because remove_lock is noop - // if lock is not there. + // they have any lock. NOTE: this means that we will still try to remove a lock + // once this genesis voter is removed, and for now it is okay because + // remove_lock is noop if lock is not there. >::insert( &member, Voter { votes: vec![member.clone()], stake: *stake, deposit: Zero::zero() }, diff --git a/substrate/frame/elections/src/lib.rs b/substrate/frame/elections/src/lib.rs index c4c88e4349..5057a6e00f 100644 --- a/substrate/frame/elections/src/lib.rs +++ b/substrate/frame/elections/src/lib.rs @@ -73,8 +73,8 @@ mod tests; // - remove inactive voter (either you or the target is removed; if the target, you get their // "voter" bond back; O(1); one fewer DB entry, one DB change) // - submit candidacy (you pay a "candidate" bond; O(1); one extra DB entry, two DB changes) -// - present winner/runner-up (you may pay a "presentation" bond of O(voters) if the presentation -// is invalid; O(voters) compute; ) protected operations: +// - present winner/runner-up (you may pay a "presentation" bond of O(voters) if the presentation is +// invalid; O(voters) compute; ) protected operations: // - remove candidacy (remove all votes for a candidate) (one fewer DB entry, two DB changes) // to avoid a potentially problematic case of not-enough approvals prior to voting causing a @@ -128,8 +128,8 @@ pub struct VoterInfo { /// Used to demonstrate the status of a particular index in the global voter list. #[derive(PartialEq, Eq, RuntimeDebug)] pub enum CellStatus { - /// Any out of bound index. Means a push a must happen to the chunk pointed by `NextVoterSet`. - /// Voting fee is applied in case a new chunk is created. + /// Any out of bound index. Means a push a must happen to the chunk pointed by + /// `NextVoterSet`. Voting fee is applied in case a new chunk is created. Head, /// Already occupied by another voter. Voting fee is applied. Occupied, @@ -850,13 +850,14 @@ impl Pallet { None } else { let c = Self::members(); - let (next_possible, count, coming) = - if let Some((tally_end, comers, leavers)) = Self::next_finalize() { - // if there's a tally in progress, then next tally can begin immediately afterwards - (tally_end, c.len() - leavers.len() + comers as usize, comers) - } else { - (>::block_number(), c.len(), 0) - }; + let (next_possible, count, coming) = if let Some((tally_end, comers, leavers)) = + Self::next_finalize() + { + // if there's a tally in progress, then next tally can begin immediately afterwards + (tally_end, c.len() - leavers.len() + comers as usize, comers) + } else { + (>::block_number(), c.len(), 0) + }; if count < desired_seats as usize { Some(next_possible) } else { diff --git a/substrate/frame/example-offchain-worker/src/lib.rs b/substrate/frame/example-offchain-worker/src/lib.rs index 01f3c355fa..9e043c8bfb 100644 --- a/substrate/frame/example-offchain-worker/src/lib.rs +++ b/substrate/frame/example-offchain-worker/src/lib.rs @@ -131,7 +131,8 @@ pub mod pallet { /// Number of blocks of cooldown after unsigned transaction is included. /// - /// This ensures that we only accept unsigned transactions once, every `UnsignedInterval` blocks. + /// This ensures that we only accept unsigned transactions once, every `UnsignedInterval` + /// blocks. #[pallet::constant] type UnsignedInterval: Get; @@ -439,9 +440,9 @@ impl Pallet { // Submit signed will return a vector of results for all accounts that were found in the // local keystore with expected `KEY_TYPE`. let results = signer.send_signed_transaction(|_account| { - // Received price is wrapped into a call to `submit_price` public function of this pallet. - // This means that the transaction, when executed, will simply call that function passing - // `price` as an argument. + // Received price is wrapped into a call to `submit_price` public function of this + // pallet. This means that the transaction, when executed, will simply call that + // function passing `price` as an argument. Call::submit_price(price) }); diff --git a/substrate/frame/example/src/lib.rs b/substrate/frame/example/src/lib.rs index 48b356df79..f588e11a61 100644 --- a/substrate/frame/example/src/lib.rs +++ b/substrate/frame/example/src/lib.rs @@ -26,27 +26,35 @@ //! //! ### Documentation Guidelines: //! -//! -//! +//! //!
    -//!
  • Documentation comments (i.e. /// comment) - should -//! accompany pallet functions and be restricted to the pallet interface, -//! not the internals of the pallet implementation. Only state inputs, -//! outputs, and a brief description that mentions whether calling it -//! requires root, but without repeating the source code details. -//! Capitalize the first word of each documentation comment and end it with -//! a full stop. See -//! Generic example of annotating source code with documentation comments
  • -//!
  • Self-documenting code - Try to refactor code to be self-documenting.
  • -//!
  • Code comments - Supplement complex code with a brief explanation, not every line of code.
  • -//!
  • Identifiers - surround by backticks (i.e. INHERENT_IDENTIFIER, InherentType, -//! u64)
  • -//!
  • Usage scenarios - should be simple doctests. The compiler should ensure they stay valid.
  • -//!
  • Extended tutorials - should be moved to external files and refer to.
  • -//! -//!
  • Mandatory - include all of the sections/subsections where MUST is specified.
  • -//!
  • Optional - optionally include sections/subsections where CAN is specified.
  • +//!
  • Documentation comments (i.e. /// comment) - should +//! accompany pallet functions and be restricted to the pallet interface, +//! not the internals of the pallet implementation. Only state inputs, +//! outputs, and a brief description that mentions whether calling it +//! requires root, but without repeating the source code details. +//! Capitalize the first word of each documentation comment and end it with +//! a full stop. See +//! Generic example of annotating source code with documentation comments
  • +//! +//!
  • Self-documenting code - Try to refactor code to be self-documenting.
  • +//! +//!
  • Code comments - Supplement complex code with a brief explanation, not every line of +//! code.
  • +//! +//!
  • Identifiers - surround by backticks (i.e. INHERENT_IDENTIFIER, +//! InherentType, u64)
  • +//! +//!
  • Usage scenarios - should be simple doctests. The compiler should ensure they stay +//! valid.
  • +//! +//!
  • Extended tutorials - should be moved to external files and refer to.
  • +//! +//!
  • Mandatory - include all of the sections/subsections where MUST is specified.
  • +//! +//!
  • Optional - optionally include sections/subsections where CAN is specified.
  • //!
//! //! ### Documentation Template:
@@ -84,12 +92,13 @@ //! //! \## Terminology //! -//! // Add terminology used in the custom pallet. Include concepts, storage items, or actions that you think -//! // deserve to be noted to give context to the rest of the documentation or pallet usage. The author needs to -//! // use some judgment about what is included. We don't want a list of every storage item nor types - the user -//! // can go to the code for that. For example, "transfer fee" is obvious and should not be included, but -//! // "free balance" and "reserved balance" should be noted to give context to the pallet. -//! // Please do not link to outside resources. The reference docs should be the ultimate source of truth. +//! // Add terminology used in the custom pallet. Include concepts, storage items, or actions that +//! you think // deserve to be noted to give context to the rest of the documentation or pallet +//! usage. The author needs to // use some judgment about what is included. We don't want a list of +//! every storage item nor types - the user // can go to the code for that. For example, "transfer +//! fee" is obvious and should not be included, but // "free balance" and "reserved balance" should +//! be noted to give context to the pallet. // Please do not link to outside resources. The +//! reference docs should be the ultimate source of truth. //! //! //! @@ -106,7 +115,8 @@ //! \#### //! //! // Describe requirements prior to interacting with the custom pallet. -//! // Describe the process of interacting with the custom pallet for this scenario and public API functions used. +//! // Describe the process of interacting with the custom pallet for this scenario and public API +//! functions used. //! //! \## Interface //! @@ -130,14 +140,16 @@ //! //! //! -//! // Reference documentation of aspects such as `storageItems` and `dispatchable` functions should only be -//! // included in the Rustdocs for Substrate and not repeated in the README file. +//! // Reference documentation of aspects such as `storageItems` and `dispatchable` functions should +//! // only be included in the Rustdocs for Substrate and not repeated in the +//! // README file. //! //! \### Dispatchable Functions //! //! //! -//! // A brief description of dispatchable functions and a link to the rustdoc with their actual documentation. +//! // A brief description of dispatchable functions and a link to the rustdoc with their actual +//! documentation. //! //! // MUST have link to Call enum //! // MUST have origin information included in function doc @@ -154,7 +166,8 @@ //! //! //! -//! // It is up to the writer of the respective pallet (with respect to how much information to provide). +//! // It is up to the writer of the respective pallet (with respect to how much information to +//! provide). //! //! \#### Public Inspection functions - Immutable (getters) //! @@ -217,7 +230,8 @@ //! //! \### Simple Code Snippet //! -//! // Show a simple example (e.g. how to query a public getter function of ) +//! // Show a simple example (e.g. how to query a public getter function of +//! ) //! //! \### Example from FRAME //! @@ -408,10 +422,10 @@ pub mod pallet { // - Public calls that are signed by an external account. // - Root calls that are allowed to be made only by the governance system. // - Unsigned calls that can be of two kinds: - // * "Inherent extrinsics" that are opinions generally held by the block - // authors that build child blocks. - // * Unsigned Transactions that are of intrinsic recognizable utility to the - // network, and are validated by the runtime. + // * "Inherent extrinsics" that are opinions generally held by the block authors that build + // child blocks. + // * Unsigned Transactions that are of intrinsic recognizable utility to the network, and are + // validated by the runtime. // // Information about where this dispatch initiated from is provided as the first argument // "origin". As such functions must always look like: @@ -466,10 +480,10 @@ pub mod pallet { // // If you don't respect these rules, it is likely that your chain will be attackable. // - // Each transaction must define a `#[pallet::weight(..)]` attribute to convey a set of static - // information about its dispatch. FRAME System and FRAME Executive pallet then use this - // information to properly execute the transaction, whilst keeping the total load of the - // chain in a moderate rate. + // Each transaction must define a `#[pallet::weight(..)]` attribute to convey a set of + // static information about its dispatch. FRAME System and FRAME Executive pallet then use + // this information to properly execute the transaction, whilst keeping the total load of + // the chain in a moderate rate. // // The parenthesized value of the `#[pallet::weight(..)]` attribute can be any type that // implements a set of traits, namely [`WeighData`] and [`ClassifyDispatch`]. @@ -478,8 +492,8 @@ pub mod pallet { // call. A higher weight means a larger transaction (less of which can be placed in a // single block). // - // The weight for this extrinsic we rely on the auto-generated `WeightInfo` from the benchmark - // toolchain. + // The weight for this extrinsic we rely on the auto-generated `WeightInfo` from the + // benchmark toolchain. #[pallet::weight( ::WeightInfo::accumulate_dummy((*increase_by).saturated_into()) )] @@ -522,8 +536,8 @@ pub mod pallet { // assume it's a one-off operation and substantial processing/storage/memory can be used // without worrying about gameability or attack scenarios. // - // The weight for this extrinsic we use our own weight object `WeightForSetDummy` to determine - // its weight + // The weight for this extrinsic we use our own weight object `WeightForSetDummy` to + // determine its weight #[pallet::weight(WeightForSetDummy::(>::from(100u32)))] pub fn set_dummy( origin: OriginFor, @@ -531,8 +545,8 @@ pub mod pallet { ) -> DispatchResult { ensure_root(origin)?; - // Print out log or debug message in the console via log::{error, warn, info, debug, trace}, - // accepting format strings similar to `println!`. + // Print out log or debug message in the console via log::{error, warn, info, debug, + // trace}, accepting format strings similar to `println!`. // https://substrate.dev/rustdocs/v3.0.0/log/index.html info!("New value is now: {:?}", new_value); @@ -631,7 +645,8 @@ impl Pallet { let _sender = ensure_signed(origin)?; let prev = >::get(); - // Because Foo has 'default', the type of 'foo' in closure is the raw type instead of an Option<> type. + // Because Foo has 'default', the type of 'foo' in closure is the raw type instead of an + // Option<> type. let result = >::mutate(|foo| { *foo = foo.saturating_add(increase_by); *foo diff --git a/substrate/frame/executive/src/lib.rs b/substrate/frame/executive/src/lib.rs index 8f857d2c82..5f1ae23c2f 100644 --- a/substrate/frame/executive/src/lib.rs +++ b/substrate/frame/executive/src/lib.rs @@ -150,8 +150,7 @@ pub type OriginOf = as Dispatchable>::Origin; /// - `UnsignedValidator`: The unsigned transaction validator of the runtime. /// - `AllPallets`: Tuple that contains all modules. Will be used to call e.g. `on_initialize`. /// - `OnRuntimeUpgrade`: Custom logic that should be called after a runtime upgrade. Modules are -/// already called by `AllPallets`. It will be called before all modules will -/// be called. +/// already called by `AllPallets`. It will be called before all modules will be called. pub struct Executive( PhantomData<(System, Block, Context, UnsignedValidator, AllPallets, OnRuntimeUpgrade)>, ); @@ -479,7 +478,8 @@ where } /// Check a given signed transaction for validity. This doesn't execute any - /// side-effects; it merely checks whether the transaction would panic if it were included or not. + /// side-effects; it merely checks whether the transaction would panic if it were included or + /// not. /// /// Changes made to storage should be discarded. pub fn validate_transaction( diff --git a/substrate/frame/gilt/src/lib.rs b/substrate/frame/gilt/src/lib.rs index 3803d78c05..7bfca872dc 100644 --- a/substrate/frame/gilt/src/lib.rs +++ b/substrate/frame/gilt/src/lib.rs @@ -294,8 +294,8 @@ pub mod pallet { DurationTooBig, /// The amount of the bid is less than the minimum allowed. AmountTooSmall, - /// The queue for the bid's duration is full and the amount bid is too low to get in through - /// replacing an existing bid. + /// The queue for the bid's duration is full and the amount bid is too low to get in + /// through replacing an existing bid. BidTooLow, /// Gilt index is unknown. Unknown, @@ -506,8 +506,8 @@ pub mod pallet { pub struct IssuanceInfo { /// The balance held in reserve over all active gilts. pub reserved: Balance, - /// The issuance not held in reserve for active gilts. Together with `reserved` this sums to - /// `Currency::total_issuance`. + /// The issuance not held in reserve for active gilts. Together with `reserved` this sums + /// to `Currency::total_issuance`. pub non_gilt: Balance, /// The balance that `reserved` is effectively worth, at present. This is not issued funds /// and could be less than `reserved` (though in most cases should be greater). @@ -586,8 +586,8 @@ pub mod pallet { let amount = bid.amount; // Can never overflow due to block above. remaining -= amount; - // Should never underflow since it should track the total of the bids - // exactly, but we'll be defensive. + // Should never underflow since it should track the total of the + // bids exactly, but we'll be defensive. qs[queue_index].1 = qs[queue_index].1.saturating_sub(bid.amount); // Now to activate the bid... diff --git a/substrate/frame/identity/src/lib.rs b/substrate/frame/identity/src/lib.rs index 19251cfbb8..b56df59e11 100644 --- a/substrate/frame/identity/src/lib.rs +++ b/substrate/frame/identity/src/lib.rs @@ -118,8 +118,8 @@ pub mod pallet { type FieldDeposit: Get>; /// The amount held on deposit for a registered subaccount. This should account for the fact - /// that one storage item's value will increase by the size of an account ID, and there will be - /// another trie item whose value is the size of an account ID plus 32 bytes. + /// that one storage item's value will increase by the size of an account ID, and there will + /// be another trie item whose value is the size of an account ID plus 32 bytes. #[pallet::constant] type SubAccountDeposit: Get>; @@ -451,7 +451,8 @@ pub mod pallet { Ok(Some( T::WeightInfo::set_subs_old(old_ids.len() as u32) // P: Real number of old accounts removed. - .saturating_add(T::WeightInfo::set_subs_new(new_subs as u32)), /* S: New subs added. */ + // S: New subs added + .saturating_add(T::WeightInfo::set_subs_new(new_subs as u32)), ) .into()) } diff --git a/substrate/frame/im-online/src/lib.rs b/substrate/frame/im-online/src/lib.rs index 99500ece83..842f593de7 100644 --- a/substrate/frame/im-online/src/lib.rs +++ b/substrate/frame/im-online/src/lib.rs @@ -222,7 +222,8 @@ pub type ValidatorId = <::ValidatorSet as ValidatorSet< ::AccountId, >>::ValidatorId; -/// A tuple of (ValidatorId, Identification) where `Identification` is the full identification of `ValidatorId`. +/// A tuple of (ValidatorId, Identification) where `Identification` is the full identification of +/// `ValidatorId`. pub type IdentificationTuple = ( ValidatorId, <::ValidatorSet as ValidatorSetWithIdentification< @@ -375,8 +376,8 @@ pub mod pallet { #[pallet::call] impl Pallet { /// # - /// - Complexity: `O(K + E)` where K is length of `Keys` (heartbeat.validators_len) - /// and E is length of `heartbeat.network_state.external_address` + /// - Complexity: `O(K + E)` where K is length of `Keys` (heartbeat.validators_len) and E is + /// length of `heartbeat.network_state.external_address` /// - `O(K)`: decoding of length `K` /// - `O(E)`: decoding/encoding of length `E` /// - DbReads: pallet_session `Validators`, pallet_session `CurrentIndex`, `Keys`, @@ -447,7 +448,8 @@ pub mod pallet { } } - /// Invalid transaction custom error. Returned when validators_len field in heartbeat is incorrect. + /// Invalid transaction custom error. Returned when validators_len field in heartbeat is + /// incorrect. pub(crate) const INVALID_VALIDATORS_LEN: u8 = 10; #[pallet::validate_unsigned] diff --git a/substrate/frame/indices/src/lib.rs b/substrate/frame/indices/src/lib.rs index ced8c1e061..331873d424 100644 --- a/substrate/frame/indices/src/lib.rs +++ b/substrate/frame/indices/src/lib.rs @@ -48,8 +48,8 @@ pub mod pallet { /// The module's config trait. #[pallet::config] pub trait Config: frame_system::Config { - /// Type used for storing an account's index; implies the maximum number of accounts the system - /// can hold. + /// Type used for storing an account's index; implies the maximum number of accounts the + /// system can hold. type AccountIndex: Parameter + Member + MaybeSerializeDeserialize @@ -223,7 +223,8 @@ pub mod pallet { Ok(()) } - /// Freeze an index so it will always point to the sender account. This consumes the deposit. + /// Freeze an index so it will always point to the sender account. This consumes the + /// deposit. /// /// The dispatch origin for this call must be _Signed_ and the signing account must have a /// non-frozen account `index`. diff --git a/substrate/frame/lottery/src/lib.rs b/substrate/frame/lottery/src/lib.rs index e2e56860e6..c879a819b0 100644 --- a/substrate/frame/lottery/src/lib.rs +++ b/substrate/frame/lottery/src/lib.rs @@ -266,9 +266,9 @@ pub mod pallet { *lottery = None; return T::WeightInfo::on_initialize_end() } - // We choose not need to kill Participants and Tickets to avoid a large number - // of writes at one time. Instead, data persists between lotteries, but is not used - // if it is not relevant. + // We choose not need to kill Participants and Tickets to avoid a large + // number of writes at one time. Instead, data persists between lotteries, + // but is not used if it is not relevant. } } return T::DbWeight::get().reads(1) diff --git a/substrate/frame/merkle-mountain-range/src/lib.rs b/substrate/frame/merkle-mountain-range/src/lib.rs index 974b868f61..83fdc5b171 100644 --- a/substrate/frame/merkle-mountain-range/src/lib.rs +++ b/substrate/frame/merkle-mountain-range/src/lib.rs @@ -96,14 +96,14 @@ pub mod pallet { /// and some of the inner mmr nodes might be pruned from on-chain storage. /// The latter will contain all the entries in their full form. /// - /// Each node is stored in the Off-chain DB under key derived from the [`Self::INDEXING_PREFIX`] and - /// it's in-tree index (MMR position). + /// Each node is stored in the Off-chain DB under key derived from the + /// [`Self::INDEXING_PREFIX`] and it's in-tree index (MMR position). const INDEXING_PREFIX: &'static [u8]; /// A hasher type for MMR. /// - /// To construct trie nodes that result in merging (bagging) two peaks, depending on the node - /// kind we take either: + /// To construct trie nodes that result in merging (bagging) two peaks, depending on the + /// node kind we take either: /// - The node (hash) itself if it's an inner node. /// - The hash of SCALE-encoding of the leaf data if it's a leaf node. /// @@ -128,22 +128,22 @@ pub mod pallet { /// Data stored in the leaf nodes. /// - /// The [LeafData](primitives::LeafDataProvider) is responsible for returning the entire leaf - /// data that will be inserted to the MMR. + /// The [LeafData](primitives::LeafDataProvider) is responsible for returning the entire + /// leaf data that will be inserted to the MMR. /// [LeafDataProvider](primitives::LeafDataProvider)s can be composed into tuples to put - /// multiple elements into the tree. In such a case it might be worth using [primitives::Compact] - /// to make MMR proof for one element of the tuple leaner. + /// multiple elements into the tree. In such a case it might be worth using + /// [primitives::Compact] to make MMR proof for one element of the tuple leaner. /// - /// Note that the leaf at each block MUST be unique. You may want to include a block hash or block - /// number as an easiest way to ensure that. + /// Note that the leaf at each block MUST be unique. You may want to include a block hash or + /// block number as an easiest way to ensure that. type LeafData: primitives::LeafDataProvider; /// A hook to act on the new MMR root. /// /// For some applications it might be beneficial to make the MMR root available externally - /// apart from having it in the storage. For instance you might output it in the header digest - /// (see [`frame_system::Pallet::deposit_log`]) to make it available for Light Clients. - /// Hook complexity should be `O(1)`. + /// apart from having it in the storage. For instance you might output it in the header + /// digest (see [`frame_system::Pallet::deposit_log`]) to make it available for Light + /// Clients. Hook complexity should be `O(1)`. type OnNewRoot: primitives::OnNewRoot<>::Hash>; /// Weights for this pallet. diff --git a/substrate/frame/multisig/src/lib.rs b/substrate/frame/multisig/src/lib.rs index 6522abd72f..b1ef5f11a5 100644 --- a/substrate/frame/multisig/src/lib.rs +++ b/substrate/frame/multisig/src/lib.rs @@ -127,8 +127,8 @@ pub mod pallet { /// The currency mechanism. type Currency: ReservableCurrency; - /// The base amount of currency needed to reserve for creating a multisig execution or to store - /// a dispatch call for later. + /// The base amount of currency needed to reserve for creating a multisig execution or to + /// store a dispatch call for later. /// /// This is held for an additional storage item whose value size is /// `4 + sizeof((BlockNumber, Balance, AccountId))` bytes and whose key size is @@ -333,9 +333,8 @@ pub mod pallet { /// - I/O: 1 read `O(S)`, up to 1 mutate `O(S)`. Up to one remove. /// - One event. /// - The weight of the `call`. - /// - Storage: inserts one item, value size bounded by `MaxSignatories`, with a - /// deposit taken for its lifetime of - /// `DepositBase + threshold * DepositFactor`. + /// - Storage: inserts one item, value size bounded by `MaxSignatories`, with a deposit + /// taken for its lifetime of `DepositBase + threshold * DepositFactor`. /// ------------------------------- /// - DB Weight: /// - Reads: Multisig Storage, [Caller Account], Calls (if `store_call`) @@ -400,9 +399,8 @@ pub mod pallet { /// - Up to one binary search and insert (`O(logS + S)`). /// - I/O: 1 read `O(S)`, up to 1 mutate `O(S)`. Up to one remove. /// - One event. - /// - Storage: inserts one item, value size bounded by `MaxSignatories`, with a - /// deposit taken for its lifetime of - /// `DepositBase + threshold * DepositFactor`. + /// - Storage: inserts one item, value size bounded by `MaxSignatories`, with a deposit + /// taken for its lifetime of `DepositBase + threshold * DepositFactor`. /// ---------------------------------- /// - DB Weight: /// - Read: Multisig Storage, [Caller Account] diff --git a/substrate/frame/multisig/src/tests.rs b/substrate/frame/multisig/src/tests.rs index 635906d47c..2809a106d6 100644 --- a/substrate/frame/multisig/src/tests.rs +++ b/substrate/frame/multisig/src/tests.rs @@ -812,8 +812,9 @@ fn weight_check_works() { #[test] fn multisig_handles_no_preimage_after_all_approve() { - // This test checks the situation where everyone approves a multi-sig, but no-one provides the call data. - // In the end, any of the multisig callers can approve again with the call data and the call will go through. + // This test checks the situation where everyone approves a multi-sig, but no-one provides the + // call data. In the end, any of the multisig callers can approve again with the call data and + // the call will go through. new_test_ext().execute_with(|| { let multi = Multisig::multi_account_id(&[1, 2, 3][..], 3); assert_ok!(Balances::transfer(Origin::signed(1), multi, 5)); diff --git a/substrate/frame/proxy/src/lib.rs b/substrate/frame/proxy/src/lib.rs index 3647ead700..6a853c8e2b 100644 --- a/substrate/frame/proxy/src/lib.rs +++ b/substrate/frame/proxy/src/lib.rs @@ -67,8 +67,8 @@ pub struct ProxyDefinition { pub delegate: AccountId, /// A value defining the subset of calls that it is allowed to make. pub proxy_type: ProxyType, - /// The number of blocks that an announcement must be in place for before the corresponding call - /// may be dispatched. If zero, then no announcement is needed. + /// The number of blocks that an announcement must be in place for before the corresponding + /// call may be dispatched. If zero, then no announcement is needed. pub delay: BlockNumber, } @@ -132,9 +132,9 @@ pub mod pallet { /// The amount of currency needed per proxy added. /// - /// This is held for adding 32 bytes plus an instance of `ProxyType` more into a pre-existing - /// storage value. Thus, when configuring `ProxyDepositFactor` one should take into account - /// `32 + proxy_type.encode().len()` bytes of data. + /// This is held for adding 32 bytes plus an instance of `ProxyType` more into a + /// pre-existing storage value. Thus, when configuring `ProxyDepositFactor` one should take + /// into account `32 + proxy_type.encode().len()` bytes of data. #[pallet::constant] type ProxyDepositFactor: Get>; @@ -154,7 +154,8 @@ pub mod pallet { /// The base amount of currency needed to reserve for creating an announcement. /// - /// This is held when a new storage item holding a `Balance` is created (typically 16 bytes). + /// This is held when a new storage item holding a `Balance` is created (typically 16 + /// bytes). #[pallet::constant] type AnnouncementDepositBase: Get>; @@ -539,7 +540,8 @@ pub mod pallet { /// A proxy was executed correctly, with the given \[result\]. ProxyExecuted(DispatchResult), /// Anonymous account has been created by new proxy with given - /// disambiguation index and proxy type. \[anonymous, who, proxy_type, disambiguation_index\] + /// disambiguation index and proxy type. \[anonymous, who, proxy_type, + /// disambiguation_index\] AnonymousCreated(T::AccountId, T::AccountId, T::ProxyType, u16), /// An announcement was placed to make a call in the future. \[real, proxy, call_hash\] Announced(T::AccountId, T::AccountId, CallHashOf), @@ -761,11 +763,13 @@ impl Pallet { let c = ::Call::from_ref(c); // We make sure the proxy call does access this pallet to change modify proxies. match c.is_sub_type() { - // Proxy call cannot add or remove a proxy with more permissions than it already has. + // Proxy call cannot add or remove a proxy with more permissions than it already + // has. Some(Call::add_proxy(_, ref pt, _)) | Some(Call::remove_proxy(_, ref pt, _)) if !def.proxy_type.is_superset(&pt) => false, - // Proxy call cannot remove all proxies or kill anonymous proxies unless it has full permissions. + // Proxy call cannot remove all proxies or kill anonymous proxies unless it has full + // permissions. Some(Call::remove_proxies(..)) | Some(Call::kill_anonymous(..)) if def.proxy_type != T::ProxyType::default() => false, diff --git a/substrate/frame/recovery/src/lib.rs b/substrate/frame/recovery/src/lib.rs index 0214a38b0e..ad61baae60 100644 --- a/substrate/frame/recovery/src/lib.rs +++ b/substrate/frame/recovery/src/lib.rs @@ -33,12 +33,12 @@ //! //! The recovery process for each recoverable account can be configured by the account owner. //! They are able to choose: -//! * `friends` - The list of friends that the account owner trusts to protect the -//! recovery process for their account. -//! * `threshold` - The number of friends that need to approve a recovery process for -//! the account to be successfully recovered. -//! * `delay_period` - The minimum number of blocks after the beginning of the recovery -//! process that need to pass before the account can be successfully recovered. +//! * `friends` - The list of friends that the account owner trusts to protect the recovery process +//! for their account. +//! * `threshold` - The number of friends that need to approve a recovery process for the account to +//! be successfully recovered. +//! * `delay_period` - The minimum number of blocks after the beginning of the recovery process that +//! need to pass before the account can be successfully recovered. //! //! There is a configurable deposit that all users need to pay to create a recovery //! configuration. This deposit is composed of a base deposit plus a multiplier for @@ -101,25 +101,23 @@ //! security of an account if used incorrectly. Some recommended practices for users //! of this pallet are: //! -//! * Configure a significant `delay_period` for your recovery process: As long as you -//! have access to your recoverable account, you need only check the blockchain once -//! every `delay_period` blocks to ensure that no recovery attempt is successful -//! against your account. Using off-chain notification systems can help with this, -//! but ultimately, setting a large `delay_period` means that even the most skilled -//! attacker will need to wait this long before they can access your account. -//! * Use a high threshold of approvals: Setting a value of 1 for the threshold means -//! that any of your friends would be able to recover your account. They would -//! simply need to start a recovery process and approve their own process. Similarly, -//! a threshold of 2 would mean that any 2 friends could work together to gain -//! access to your account. The only way to prevent against these kinds of attacks -//! is to choose a high threshold of approvals and select from a diverse friend -//! group that would not be able to reasonably coordinate with one another. -//! * Reset your configuration over time: Since the entire deposit of creating a -//! recovery configuration is returned to the user, the only cost of updating -//! your recovery configuration is the transaction fees for the calls. Thus, -//! it is strongly encouraged to regularly update your recovery configuration -//! as your life changes and your relationship with new and existing friends -//! change as well. +//! * Configure a significant `delay_period` for your recovery process: As long as you have access +//! to your recoverable account, you need only check the blockchain once every `delay_period` +//! blocks to ensure that no recovery attempt is successful against your account. Using off-chain +//! notification systems can help with this, but ultimately, setting a large `delay_period` means +//! that even the most skilled attacker will need to wait this long before they can access your +//! account. +//! * Use a high threshold of approvals: Setting a value of 1 for the threshold means that any of +//! your friends would be able to recover your account. They would simply need to start a recovery +//! process and approve their own process. Similarly, a threshold of 2 would mean that any 2 +//! friends could work together to gain access to your account. The only way to prevent against +//! these kinds of attacks is to choose a high threshold of approvals and select from a diverse +//! friend group that would not be able to reasonably coordinate with one another. +//! * Reset your configuration over time: Since the entire deposit of creating a recovery +//! configuration is returned to the user, the only cost of updating your recovery configuration +//! is the transaction fees for the calls. Thus, it is strongly encouraged to regularly update +//! your recovery configuration as your life changes and your relationship with new and existing +//! friends change as well. //! //! ## Interface //! @@ -131,22 +129,27 @@ //! * `initiate_recovery` - Start the recovery process for a recoverable account. //! //! #### For Friends of a Recoverable Account -//! * `vouch_recovery` - As a `friend` of a recoverable account, vouch for a recovery attempt on the account. +//! * `vouch_recovery` - As a `friend` of a recoverable account, vouch for a recovery attempt on the +//! account. //! //! #### For a User Who Successfully Recovered an Account //! -//! * `claim_recovery` - Claim access to the account that you have successfully completed the recovery process for. -//! * `as_recovered` - Send a transaction as an account that you have recovered. See other functions below. +//! * `claim_recovery` - Claim access to the account that you have successfully completed the +//! recovery process for. +//! * `as_recovered` - Send a transaction as an account that you have recovered. See other functions +//! below. //! //! #### For the Recoverable Account //! -//! * `close_recovery` - Close an active recovery process for your account and reclaim the recovery deposit. -//! * `remove_recovery` - Remove the recovery configuration from the account, making it un-recoverable. +//! * `close_recovery` - Close an active recovery process for your account and reclaim the recovery +//! deposit. +//! * `remove_recovery` - Remove the recovery configuration from the account, making it +//! un-recoverable. //! //! #### For Super Users //! -//! * `set_recovered` - The ROOT origin is able to skip the recovery process and directly allow -//! one account to access another. +//! * `set_recovered` - The ROOT origin is able to skip the recovery process and directly allow one +//! account to access another. // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] @@ -231,9 +234,11 @@ pub mod pallet { #[pallet::constant] type ConfigDepositBase: Get>; - /// The amount of currency needed per additional user when creating a recovery configuration. + /// The amount of currency needed per additional user when creating a recovery + /// configuration. /// - /// This is held for adding `sizeof(AccountId)` bytes more into a pre-existing storage value. + /// This is held for adding `sizeof(AccountId)` bytes more into a pre-existing storage + /// value. #[pallet::constant] type FriendDepositFactor: Get>; @@ -417,13 +422,13 @@ pub mod pallet { /// The dispatch origin for this call must be _Signed_. /// /// Parameters: - /// - `friends`: A list of friends you trust to vouch for recovery attempts. - /// Should be ordered and contain no duplicate values. - /// - `threshold`: The number of friends that must vouch for a recovery attempt - /// before the account can be recovered. Should be less than or equal to - /// the length of the list of friends. - /// - `delay_period`: The number of blocks after a recovery attempt is initialized - /// that needs to pass before the account can be recovered. + /// - `friends`: A list of friends you trust to vouch for recovery attempts. Should be + /// ordered and contain no duplicate values. + /// - `threshold`: The number of friends that must vouch for a recovery attempt before the + /// account can be recovered. Should be less than or equal to the length of the list of + /// friends. + /// - `delay_period`: The number of blocks after a recovery attempt is initialized that + /// needs to pass before the account can be recovered. /// /// # /// - Key: F (len of friends) @@ -480,8 +485,8 @@ pub mod pallet { /// The dispatch origin for this call must be _Signed_. /// /// Parameters: - /// - `account`: The lost account that you want to recover. This account - /// needs to be recoverable (i.e. have a recovery configuration). + /// - `account`: The lost account that you want to recover. This account needs to be + /// recoverable (i.e. have a recovery configuration). /// /// # /// - One storage read to check that account is recoverable. O(F) @@ -526,8 +531,7 @@ pub mod pallet { /// /// Parameters: /// - `lost`: The lost account that you want to recover. - /// - `rescuer`: The account trying to rescue the lost account that you - /// want to vouch for. + /// - `rescuer`: The account trying to rescue the lost account that you want to vouch for. /// /// The combination of these two parameters must point to an active recovery /// process. @@ -575,8 +579,8 @@ pub mod pallet { /// `threshold` or more vouches, waited `delay_period` blocks since initiation. /// /// Parameters: - /// - `account`: The lost account that you want to claim has been successfully - /// recovered by you. + /// - `account`: The lost account that you want to claim has been successfully recovered by + /// you. /// /// # /// Key: F (len of friends in config), V (len of vouching friends) diff --git a/substrate/frame/recovery/src/tests.rs b/substrate/frame/recovery/src/tests.rs index 9065e9afe8..122088bf5e 100644 --- a/substrate/frame/recovery/src/tests.rs +++ b/substrate/frame/recovery/src/tests.rs @@ -64,7 +64,8 @@ fn recovery_life_cycle_works() { run_to_block(10); // Using account 1, the user begins the recovery process to recover the lost account assert_ok!(Recovery::initiate_recovery(Origin::signed(1), 5)); - // Off chain, the user contacts their friends and asks them to vouch for the recovery attempt + // Off chain, the user contacts their friends and asks them to vouch for the recovery + // attempt assert_ok!(Recovery::vouch_recovery(Origin::signed(2), 5, 1)); assert_ok!(Recovery::vouch_recovery(Origin::signed(3), 5, 1)); assert_ok!(Recovery::vouch_recovery(Origin::signed(4), 5, 1)); diff --git a/substrate/frame/scheduler/src/lib.rs b/substrate/frame/scheduler/src/lib.rs index cb6aaeb9a9..ceb163a432 100644 --- a/substrate/frame/scheduler/src/lib.rs +++ b/substrate/frame/scheduler/src/lib.rs @@ -40,12 +40,11 @@ //! //! ### Dispatchable Functions //! -//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a -//! specified block and with a specified priority. -//! * `cancel` - cancel a scheduled dispatch, specified by block number and -//! index. -//! * `schedule_named` - augments the `schedule` interface with an additional -//! `Vec` parameter that can be used for identification. +//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and +//! with a specified priority. +//! * `cancel` - cancel a scheduled dispatch, specified by block number and index. +//! * `schedule_named` - augments the `schedule` interface with an additional `Vec` parameter +//! that can be used for identification. //! * `cancel_named` - the named complement to the cancel function. // Ensure we're `no_std` when compiling for Wasm. @@ -152,8 +151,8 @@ pub mod pallet { + GetDispatchInfo + From>; - /// The maximum weight that may be scheduled per block for any dispatchables of less priority - /// than `schedule::HARD_DEADLINE`. + /// The maximum weight that may be scheduled per block for any dispatchables of less + /// priority than `schedule::HARD_DEADLINE`. #[pallet::constant] type MaximumWeight: Get; @@ -1321,7 +1320,8 @@ mod tests { root(), Call::Logger(LoggerCall::log(69, MaximumSchedulerWeight::get() / 2)) )); - // With base weights, 69 and 42 should not fit together, but do because of hard deadlines + // With base weights, 69 and 42 should not fit together, but do because of hard + // deadlines run_to_block(4); assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]); }); diff --git a/substrate/frame/session/src/lib.rs b/substrate/frame/session/src/lib.rs index 5f6c05e650..3f5d853d4f 100644 --- a/substrate/frame/session/src/lib.rs +++ b/substrate/frame/session/src/lib.rs @@ -269,7 +269,8 @@ pub trait SessionHandler { /// All the key type ids this session handler can process. /// /// The order must be the same as it expects them in - /// [`on_new_session`](Self::on_new_session) and [`on_genesis_session`](Self::on_genesis_session). + /// [`on_new_session`](Self::on_new_session) and + /// [`on_genesis_session`](Self::on_genesis_session). const KEY_TYPE_IDS: &'static [KeyTypeId]; /// The given validator set will be used for the genesis session. @@ -490,8 +491,8 @@ decl_storage! { decl_event!( pub enum Event { - /// New session has happened. Note that the argument is the \[session_index\], not the block - /// number as the type might suggest. + /// New session has happened. Note that the argument is the \[session_index\], not the + /// block number as the type might suggest. NewSession(SessionIndex), } ); diff --git a/substrate/frame/society/src/lib.rs b/substrate/frame/society/src/lib.rs index ffe2759eb8..c19cd35ae7 100644 --- a/substrate/frame/society/src/lib.rs +++ b/substrate/frame/society/src/lib.rs @@ -1332,8 +1332,9 @@ impl, I: Instance> Module { // we assume there's at least one member or this logic won't work. if !members.is_empty() { let candidates = >::take(); - // NOTE: This may cause member length to surpass `MaxMembers`, but results in no consensus - // critical issues or side-effects. This is auto-correcting as members fall out of society. + // NOTE: This may cause member length to surpass `MaxMembers`, but results in no + // consensus critical issues or side-effects. This is auto-correcting as members fall + // out of society. members.reserve(candidates.len()); let maturity = @@ -1369,8 +1370,9 @@ impl, I: Instance> Module { let matching_vote = if is_accepted { Vote::Approve } else { Vote::Reject }; let bad_vote = |m: &T::AccountId| { - // Voter voted wrong way (or was just a lazy skeptic) then reduce their payout - // and increase their strikes. after MaxStrikes then they go into suspension. + // Voter voted wrong way (or was just a lazy skeptic) then reduce their + // payout and increase their strikes. after MaxStrikes then they go into + // suspension. let amount = Self::slash_payout(m, T::WrongSideDeduction::get()); let strikes = >::mutate(m, |s| { @@ -1405,9 +1407,10 @@ impl, I: Instance> Module { Self::pay_accepted_candidate(&candidate, value, kind, maturity); - // We track here the total_approvals so that every candidate has a unique range - // of numbers from 0 to `total_approvals` with length `approval_count` so each - // candidate is proportionally represented when selecting a "primary" below. + // We track here the total_approvals so that every candidate has a unique + // range of numbers from 0 to `total_approvals` with length `approval_count` + // so each candidate is proportionally represented when selecting a + // "primary" below. Some((candidate, total_approvals, value)) } else { // Suspend Candidate @@ -1474,8 +1477,9 @@ impl, I: Instance> Module { // Then write everything back out, signal the changed membership and leave an event. members.sort(); - // NOTE: This may cause member length to surpass `MaxMembers`, but results in no consensus - // critical issues or side-effects. This is auto-correcting as members fall out of society. + // NOTE: This may cause member length to surpass `MaxMembers`, but results in no + // consensus critical issues or side-effects. This is auto-correcting as members + // fall out of society. >::put(&members[..]); >::put(&primary); @@ -1565,7 +1569,8 @@ impl, I: Instance> Module { value }, BidKind::Vouch(voucher, tip) => { - // Check that the voucher is still vouching, else some other logic may have removed their status. + // Check that the voucher is still vouching, else some other logic may have removed + // their status. if >::take(&voucher) == Some(VouchingStatus::Vouching) { // In the case that a vouched-for bid is accepted we unset the // vouching status and transfer the tip over to the voucher. diff --git a/substrate/frame/staking/reward-curve/src/lib.rs b/substrate/frame/staking/reward-curve/src/lib.rs index 22ddc81709..06e35d1135 100644 --- a/substrate/frame/staking/reward-curve/src/lib.rs +++ b/substrate/frame/staking/reward-curve/src/lib.rs @@ -32,28 +32,27 @@ use syn::parse::{Parse, ParseStream}; /// [here](https://research.web3.foundation/en/latest/polkadot/Token%20Economics.html#inflation-model)) /// for those parameters. Parameters are: /// - `min_inflation`: the minimal amount to be rewarded between validators, expressed as a fraction -/// of total issuance. Known as `I_0` in the literature. -/// Expressed in millionth, must be between 0 and 1_000_000. +/// of total issuance. Known as `I_0` in the literature. Expressed in millionth, must be between 0 +/// and 1_000_000. /// /// - `max_inflation`: the maximum amount to be rewarded between validators, expressed as a fraction -/// of total issuance. This is attained only when `ideal_stake` is achieved. -/// Expressed in millionth, must be between min_inflation and 1_000_000. +/// of total issuance. This is attained only when `ideal_stake` is achieved. Expressed in +/// millionth, must be between min_inflation and 1_000_000. /// /// - `ideal_stake`: the fraction of total issued tokens that should be actively staked behind -/// validators. Known as `x_ideal` in the literature. -/// Expressed in millionth, must be between 0_100_000 and 0_900_000. +/// validators. Known as `x_ideal` in the literature. Expressed in millionth, must be between +/// 0_100_000 and 0_900_000. /// /// - `falloff`: Known as `decay_rate` in the literature. A co-efficient dictating the strength of /// the global incentivization to get the `ideal_stake`. A higher number results in less typical -/// inflation at the cost of greater volatility for validators. -/// Expressed in millionth, must be between 0 and 1_000_000. +/// inflation at the cost of greater volatility for validators. Expressed in millionth, must be +/// between 0 and 1_000_000. /// /// - `max_piece_count`: The maximum number of pieces in the curve. A greater number uses more -/// resources but results in higher accuracy. -/// Must be between 2 and 1_000. +/// resources but results in higher accuracy. Must be between 2 and 1_000. /// -/// - `test_precision`: The maximum error allowed in the generated test. -/// Expressed in millionth, must be between 0 and 1_000_000. +/// - `test_precision`: The maximum error allowed in the generated test. Expressed in millionth, +/// must be between 0 and 1_000_000. /// /// # Example /// diff --git a/substrate/frame/staking/reward-fn/src/lib.rs b/substrate/frame/staking/reward-fn/src/lib.rs index 3f91c39b40..dd5e629b39 100644 --- a/substrate/frame/staking/reward-fn/src/lib.rs +++ b/substrate/frame/staking/reward-fn/src/lib.rs @@ -45,19 +45,13 @@ use sp_arithmetic::{ /// [here](https://research.web3.foundation/en/latest/polkadot/economics/1-token-economics.html#inflation-model-with-parachains)) /// /// Arguments are: -/// * `stake`: -/// The fraction of total issued tokens that actively staked behind -/// validators. Known as `x` in the literature. -/// Must be between 0 and 1. -/// * `ideal_stake`: -/// The fraction of total issued tokens that should be actively staked behind -/// validators. Known as `x_ideal` in the literature. -/// Must be between 0 and 1. -/// * `falloff`: -/// Known as `decay_rate` in the literature. A co-efficient dictating the strength of +/// * `stake`: The fraction of total issued tokens that actively staked behind validators. Known as +/// `x` in the literature. Must be between 0 and 1. +/// * `ideal_stake`: The fraction of total issued tokens that should be actively staked behind +/// validators. Known as `x_ideal` in the literature. Must be between 0 and 1. +/// * `falloff`: Known as `decay_rate` in the literature. A co-efficient dictating the strength of /// the global incentivization to get the `ideal_stake`. A higher number results in less typical -/// inflation at the cost of greater volatility for validators. -/// Must be more than 0.01. +/// inflation at the cost of greater volatility for validators. Must be more than 0.01. pub fn compute_inflation(stake: P, ideal_stake: P, falloff: P) -> P { if stake < ideal_stake { // ideal_stake is more than 0 because it is strictly more than stake diff --git a/substrate/frame/staking/src/inflation.rs b/substrate/frame/staking/src/inflation.rs index 6f2bfe06ac..8e44a8c548 100644 --- a/substrate/frame/staking/src/inflation.rs +++ b/substrate/frame/staking/src/inflation.rs @@ -25,8 +25,8 @@ use sp_runtime::{curve::PiecewiseLinear, traits::AtLeast32BitUnsigned, Perbill}; /// The total payout to all validators (and their nominators) per era and maximum payout. /// /// Defined as such: -/// `staker-payout = yearly_inflation(npos_token_staked / total_tokens) * total_tokens / era_per_year` -/// `maximum-payout = max_yearly_inflation * total_tokens / era_per_year` +/// `staker-payout = yearly_inflation(npos_token_staked / total_tokens) * total_tokens / +/// era_per_year` `maximum-payout = max_yearly_inflation * total_tokens / era_per_year` /// /// `era_duration` is expressed in millisecond. pub fn compute_total_payout( diff --git a/substrate/frame/staking/src/pallet/impls.rs b/substrate/frame/staking/src/pallet/impls.rs index accd7a0cf0..64d66f5a5f 100644 --- a/substrate/frame/staking/src/pallet/impls.rs +++ b/substrate/frame/staking/src/pallet/impls.rs @@ -163,8 +163,9 @@ impl Pallet { Self::deposit_event(Event::::Rewarded(ledger.stash, imbalance.peek())); } - // Track the number of payout ops to nominators. Note: `WeightInfo::payout_stakers_alive_staked` - // always assumes at least a validator is paid out, so we do not need to count their payout op. + // Track the number of payout ops to nominators. Note: + // `WeightInfo::payout_stakers_alive_staked` always assumes at least a validator is paid + // out, so we do not need to count their payout op. let mut nominator_payout_count: u32 = 0; // Lets now calculate how this is split to the nominators. @@ -306,6 +307,7 @@ impl Pallet { } } + /// /// * Increment `active_era.index`, /// * reset `active_era.start`, /// * update `BondedEras` and apply slashes. @@ -674,7 +676,8 @@ impl Pallet { all_voters } - /// This is a very expensive function and result should be cached versus being called multiple times. + /// This is a very expensive function and result should be cached versus being called multiple + /// times. pub fn get_npos_targets() -> Vec { Validators::::iter().map(|(v, _)| v).collect::>() } diff --git a/substrate/frame/staking/src/pallet/mod.rs b/substrate/frame/staking/src/pallet/mod.rs index e7c5947ac0..ee09660d23 100644 --- a/substrate/frame/staking/src/pallet/mod.rs +++ b/substrate/frame/staking/src/pallet/mod.rs @@ -62,12 +62,12 @@ pub mod pallet { /// Time used for computing era duration. /// - /// It is guaranteed to start being called from the first `on_finalize`. Thus value at genesis - /// is not used. + /// It is guaranteed to start being called from the first `on_finalize`. Thus value at + /// genesis is not used. type UnixTime: UnixTime; - /// Convert a balance into a number used for election calculation. This must fit into a `u64` - /// but is allowed to be sensibly lossy. The `u64` is used to communicate with the + /// Convert a balance into a number used for election calculation. This must fit into a + /// `u64` but is allowed to be sensibly lossy. The `u64` is used to communicate with the /// [`sp_npos_elections`] crate which accepts u64 numbers and does operations in 128. /// Consequently, the backward convert is used convert the u128s from sp-elections back to a /// [`BalanceOf`]. @@ -129,13 +129,14 @@ pub mod pallet { /// See [Era payout](./index.html#era-payout). type EraPayout: EraPayout>; - /// Something that can estimate the next session change, accurately or as a best effort guess. + /// Something that can estimate the next session change, accurately or as a best effort + /// guess. type NextNewSession: EstimateNextNewSession; /// The maximum number of nominators rewarded for each validator. /// - /// For each validator only the `$MaxNominatorRewardedPerValidator` biggest stakers can claim - /// their reward. This used to limit the i/o cost for the nominator payout. + /// For each validator only the `$MaxNominatorRewardedPerValidator` biggest stakers can + /// claim their reward. This used to limit the i/o cost for the nominator payout. #[pallet::constant] type MaxNominatorRewardedPerValidator: Get; @@ -437,9 +438,9 @@ pub mod pallet { #[pallet::storage] pub(crate) type StorageVersion = StorageValue<_, Releases, ValueQuery>; - /// The threshold for when users can start calling `chill_other` for other validators / nominators. - /// The threshold is compared to the actual number of validators / nominators (`CountFor*`) in - /// the system compared to the configured max (`Max*Count`). + /// The threshold for when users can start calling `chill_other` for other validators / + /// nominators. The threshold is compared to the actual number of validators / nominators + /// (`CountFor*`) in the system compared to the configured max (`Max*Count`). #[pallet::storage] pub(crate) type ChillThreshold = StorageValue<_, Percent, OptionQuery>; @@ -598,11 +599,11 @@ pub mod pallet { BadTarget, /// The user has enough bond and thus cannot be chilled forcefully by an external person. CannotChillOther, - /// There are too many nominators in the system. Governance needs to adjust the staking settings - /// to keep things safe for the runtime. + /// There are too many nominators in the system. Governance needs to adjust the staking + /// settings to keep things safe for the runtime. TooManyNominators, - /// There are too many validators in the system. Governance needs to adjust the staking settings - /// to keep things safe for the runtime. + /// There are too many validators in the system. Governance needs to adjust the staking + /// settings to keep things safe for the runtime. TooManyValidators, } @@ -636,7 +637,8 @@ pub mod pallet { if active_era.start.is_none() { let now_as_millis_u64 = T::UnixTime::now().as_millis().saturated_into::(); active_era.start = Some(now_as_millis_u64); - // This write only ever happens once, we don't include it in the weight in general + // This write only ever happens once, we don't include it in the weight in + // general ActiveEra::::put(active_era); } } @@ -731,8 +733,8 @@ pub mod pallet { /// The dispatch origin for this call must be _Signed_ by the stash, not the controller. /// /// Use this if there are additional funds in your stash account that you wish to bond. - /// Unlike [`bond`](Self::bond) or [`unbond`](Self::unbond) this function does not impose any limitation - /// on the amount that can be added. + /// Unlike [`bond`](Self::bond) or [`unbond`](Self::unbond) this function does not impose + /// any limitation on the amount that can be added. /// /// Emits `Bonded`. /// @@ -854,23 +856,24 @@ pub mod pallet { ledger = ledger.consolidate_unlocked(current_era) } - let post_info_weight = - if ledger.unlocking.is_empty() && ledger.active < T::Currency::minimum_balance() { - // This account must have called `unbond()` with some value that caused the active - // portion to fall below existential deposit + will have no more unlocking chunks - // left. We can now safely remove all staking-related information. - Self::kill_stash(&stash, num_slashing_spans)?; - // Remove the lock. - T::Currency::remove_lock(STAKING_ID, &stash); - // This is worst case scenario, so we use the full weight and return None - None - } else { - // This was the consequence of a partial unbond. just update the ledger and move on. - Self::update_ledger(&controller, &ledger); + let post_info_weight = if ledger.unlocking.is_empty() && + ledger.active < T::Currency::minimum_balance() + { + // This account must have called `unbond()` with some value that caused the active + // portion to fall below existential deposit + will have no more unlocking chunks + // left. We can now safely remove all staking-related information. + Self::kill_stash(&stash, num_slashing_spans)?; + // Remove the lock. + T::Currency::remove_lock(STAKING_ID, &stash); + // This is worst case scenario, so we use the full weight and return None + None + } else { + // This was the consequence of a partial unbond. just update the ledger and move on. + Self::update_ledger(&controller, &ledger); - // This is only an update, so we use less overall weight. - Some(T::WeightInfo::withdraw_unbonded_update(num_slashing_spans)) - }; + // This is only an update, so we use less overall weight. + Some(T::WeightInfo::withdraw_unbonded_update(num_slashing_spans)) + }; // `old_total` should never be less than the new total because // `consolidate_unlocked` strictly subtracts balance. @@ -898,8 +901,9 @@ pub mod pallet { // Only check limits if they are not already a validator. if !Validators::::contains_key(stash) { - // If this error is reached, we need to adjust the `MinValidatorBond` and start calling `chill_other`. - // Until then, we explicitly block new validators to protect the runtime. + // If this error is reached, we need to adjust the `MinValidatorBond` and start + // calling `chill_other`. Until then, we explicitly block new validators to protect + // the runtime. if let Some(max_validators) = MaxValidatorsCount::::get() { ensure!( CounterForValidators::::get() < max_validators, @@ -937,8 +941,9 @@ pub mod pallet { // Only check limits if they are not already a nominator. if !Nominators::::contains_key(stash) { - // If this error is reached, we need to adjust the `MinNominatorBond` and start calling `chill_other`. - // Until then, we explicitly block new nominators to protect the runtime. + // If this error is reached, we need to adjust the `MinNominatorBond` and start + // calling `chill_other`. Until then, we explicitly block new nominators to protect + // the runtime. if let Some(max_nominators) = MaxNominatorsCount::::get() { ensure!( CounterForNominators::::get() < max_nominators, @@ -1180,8 +1185,8 @@ pub mod pallet { /// # /// O(S) where S is the number of slashing spans to be removed /// Reads: Bonded, Slashing Spans, Account, Locks - /// Writes: Bonded, Slashing Spans (if S > 0), Ledger, Payee, Validators, Nominators, Account, Locks - /// Writes Each: SpanSlash * S + /// Writes: Bonded, Slashing Spans (if S > 0), Ledger, Payee, Validators, Nominators, + /// Account, Locks Writes Each: SpanSlash * S /// # #[pallet::weight(T::WeightInfo::force_unstake(*num_slashing_spans))] pub fn force_unstake( @@ -1327,10 +1332,10 @@ pub mod pallet { /// /// Parameters: /// - `new_history_depth`: The new history depth you would like to set. - /// - `era_items_deleted`: The number of items that will be deleted by this dispatch. - /// This should report all the storage items that will be deleted by clearing old - /// era history. Needed to report an accurate weight for the dispatch. Trusted by - /// `Root` to report an accurate number. + /// - `era_items_deleted`: The number of items that will be deleted by this dispatch. This + /// should report all the storage items that will be deleted by clearing old era history. + /// Needed to report an accurate weight for the dispatch. Trusted by `Root` to report an + /// accurate number. /// /// Origin must be root. /// @@ -1341,7 +1346,8 @@ pub mod pallet { /// - Reads: Current Era, History Depth /// - Writes: History Depth /// - Clear Prefix Each: Era Stakers, EraStakersClipped, ErasValidatorPrefs - /// - Writes Each: ErasValidatorReward, ErasRewardPoints, ErasTotalStake, ErasStartSessionIndex + /// - Writes Each: ErasValidatorReward, ErasRewardPoints, ErasTotalStake, + /// ErasStartSessionIndex /// # #[pallet::weight(T::WeightInfo::set_history_depth(*_era_items_deleted))] pub fn set_history_depth( @@ -1375,7 +1381,8 @@ pub mod pallet { /// Complexity: O(S) where S is the number of slashing spans on the account. /// DB Weight: /// - Reads: Stash Account, Bonded, Slashing Spans, Locks - /// - Writes: Bonded, Slashing Spans (if S > 0), Ledger, Payee, Validators, Nominators, Stash Account, Locks + /// - Writes: Bonded, Slashing Spans (if S > 0), Ledger, Payee, Validators, Nominators, + /// Stash Account, Locks /// - Writes Each: SpanSlash * S /// # #[pallet::weight(T::WeightInfo::reap_stash(*num_slashing_spans))] @@ -1437,10 +1444,10 @@ pub mod pallet { /// /// * `min_nominator_bond`: The minimum active bond needed to be a nominator. /// * `min_validator_bond`: The minimum active bond needed to be a validator. - /// * `max_nominator_count`: The max number of users who can be a nominator at once. - /// When set to `None`, no limit is enforced. - /// * `max_validator_count`: The max number of users who can be a validator at once. - /// When set to `None`, no limit is enforced. + /// * `max_nominator_count`: The max number of users who can be a nominator at once. When + /// set to `None`, no limit is enforced. + /// * `max_validator_count`: The max number of users who can be a validator at once. When + /// set to `None`, no limit is enforced. /// /// Origin must be Root to call this function. /// diff --git a/substrate/frame/staking/src/tests.rs b/substrate/frame/staking/src/tests.rs index 364822ed3e..67a402060a 100644 --- a/substrate/frame/staking/src/tests.rs +++ b/substrate/frame/staking/src/tests.rs @@ -572,13 +572,15 @@ fn nominating_and_rewards_should_work() { mock::make_all_reward_payment(1); let payout_for_10 = total_payout_1 / 3; let payout_for_20 = 2 * total_payout_1 / 3; - // Nominator 2: has [400/1800 ~ 2/9 from 10] + [600/2200 ~ 3/11 from 20]'s reward. ==> 2/9 + 3/11 + // Nominator 2: has [400/1800 ~ 2/9 from 10] + [600/2200 ~ 3/11 from 20]'s reward. ==> + // 2/9 + 3/11 assert_eq_error_rate!( Balances::total_balance(&2), initial_balance + (2 * payout_for_10 / 9 + 3 * payout_for_20 / 11), 2, ); - // Nominator 4: has [400/1800 ~ 2/9 from 10] + [600/2200 ~ 3/11 from 20]'s reward. ==> 2/9 + 3/11 + // Nominator 4: has [400/1800 ~ 2/9 from 10] + [600/2200 ~ 3/11 from 20]'s reward. ==> + // 2/9 + 3/11 assert_eq_error_rate!( Balances::total_balance(&4), initial_balance + (2 * payout_for_10 / 9 + 3 * payout_for_20 / 11), @@ -591,7 +593,8 @@ fn nominating_and_rewards_should_work() { initial_balance + 5 * payout_for_10 / 9, 2, ); - // Validator 20: got `1200/2200` external stake => 12/22 =? 6/11 => Validator's share = 5/11 + // Validator 20: got 1200 / 2200 external stake => 12/22 =? 6/11 => Validator's share = + // 5/11 assert_eq_error_rate!( Balances::total_balance(&20), initial_balance_20 + 5 * payout_for_20 / 11, @@ -684,7 +687,8 @@ fn double_staking_should_fail() { #[test] fn double_controlling_should_fail() { // should test (in the same order): - // * an account already bonded as controller CANNOT be reused as the controller of another account. + // * an account already bonded as controller CANNOT be reused as the controller of another + // account. ExtBuilder::default().build_and_execute(|| { let arbitrary_value = 5; // 2 = controller, 1 stashed => ok @@ -1116,6 +1120,7 @@ fn bond_extra_works() { #[test] fn bond_extra_and_withdraw_unbonded_works() { + // // * Should test // * Given an account being bonded [and chosen as a validator](not mandatory) // * It can add extra funds to the bonded account. @@ -1282,6 +1287,7 @@ fn too_many_unbond_calls_should_not_work() { #[test] fn rebond_works() { + // // * Should test // * Given an account being bonded [and chosen as a validator](not mandatory) // * it can unbond a portion of its funds from the stash account. @@ -1683,7 +1689,8 @@ fn on_free_balance_zero_stash_removes_nominator() { #[test] fn switching_roles() { - // Test that it should be possible to switch between roles (nominator, validator, idle) with minimal overhead. + // Test that it should be possible to switch between roles (nominator, validator, idle) with + // minimal overhead. ExtBuilder::default().nominate(false).build_and_execute(|| { // Reset reward destination for i in &[10, 20] { @@ -3354,7 +3361,8 @@ fn payout_stakers_handles_weight_refund() { assert_ok!(result); assert_eq!(extract_actual_weight(&result, &info), zero_nom_payouts_weight); - // The validator is not rewarded in this era; so there will be zero payouts to claim for this era. + // The validator is not rewarded in this era; so there will be zero payouts to claim for + // this era. // Era 3 start_active_era(3); @@ -4118,7 +4126,8 @@ fn chill_other_works() { assert_eq!(CounterForNominators::::get(), 15 + initial_nominators); assert_eq!(CounterForValidators::::get(), 15 + initial_validators); - // Users can now be chilled down to 7 people, so we try to remove 9 of them (starting with 16) + // Users can now be chilled down to 7 people, so we try to remove 9 of them (starting + // with 16) for i in 6..15 { let b = 4 * i + 1; let d = 4 * i + 3; diff --git a/substrate/frame/sudo/src/lib.rs b/substrate/frame/sudo/src/lib.rs index 7f0f6f57bf..6dcb3bf5e4 100644 --- a/substrate/frame/sudo/src/lib.rs +++ b/substrate/frame/sudo/src/lib.rs @@ -41,9 +41,9 @@ //! ### Executing Privileged Functions //! //! The Sudo pallet itself is not intended to be used within other pallets. -//! Instead, you can build "privileged functions" (i.e. functions that require `Root` origin) in other pallets. -//! You can execute these privileged functions by calling `sudo` with the sudo key account. -//! Privileged functions cannot be directly executed via an extrinsic. +//! Instead, you can build "privileged functions" (i.e. functions that require `Root` origin) in +//! other pallets. You can execute these privileged functions by calling `sudo` with the sudo key +//! account. Privileged functions cannot be directly executed via an extrinsic. //! //! Learn more about privileged functions and `Root` origin in the [`Origin`] type documentation. //! @@ -52,7 +52,7 @@ //! This is an example of a pallet that exposes a privileged function: //! //! ``` -//! +//! //! #[frame_support::pallet] //! pub mod logger { //! use frame_support::pallet_prelude::*; @@ -181,7 +181,8 @@ pub mod pallet { Ok(Pays::No.into()) } - /// Authenticates the current sudo key and sets the given AccountId (`new`) as the new sudo key. + /// Authenticates the current sudo key and sets the given AccountId (`new`) as the new sudo + /// key. /// /// The dispatch origin for this call must be _Signed_. /// diff --git a/substrate/frame/sudo/src/tests.rs b/substrate/frame/sudo/src/tests.rs index 9437f20832..ebd7a11a70 100644 --- a/substrate/frame/sudo/src/tests.rs +++ b/substrate/frame/sudo/src/tests.rs @@ -109,7 +109,8 @@ fn set_key_basics() { }); new_test_ext(1).execute_with(|| { - // A non-root `key` will trigger a `RequireSudo` error and a non-root `key` cannot change the root `key`. + // A non-root `key` will trigger a `RequireSudo` error and a non-root `key` cannot change + // the root `key`. assert_noop!(Sudo::set_key(Origin::signed(2), 3), Error::::RequireSudo); }); } diff --git a/substrate/frame/support/procedural/src/lib.rs b/substrate/frame/support/procedural/src/lib.rs index 483d7c31c0..a8ac022c35 100644 --- a/substrate/frame/support/procedural/src/lib.rs +++ b/substrate/frame/support/procedural/src/lib.rs @@ -92,23 +92,24 @@ impl Counter { /// ``` /// /// * Map: `Foo: map hasher($hash) type => type`: Implements the -/// [`StorageMap`](../frame_support/storage/trait.StorageMap.html) trait using the -/// [`StorageMap generator`](../frame_support/storage/generator/trait.StorageMap.html). -/// And [`StoragePrefixedMap`](../frame_support/storage/trait.StoragePrefixedMap.html). +/// [`StorageMap`](../frame_support/storage/trait.StorageMap.html) trait using the [`StorageMap +/// generator`](../frame_support/storage/generator/trait.StorageMap.html). And +/// [`StoragePrefixedMap`](../frame_support/storage/trait.StoragePrefixedMap.html). /// /// `$hash` representing a choice of hashing algorithms available in the /// [`Hashable`](../frame_support/trait.Hashable.html) trait. You will generally want to use one /// of three hashers: /// * `blake2_128_concat`: The default, safe choice. Use if you are unsure or don't care. It is -/// secure against user-tainted keys, fairly fast and memory-efficient and supports -/// iteration over its keys and values. This must be used if the keys of your map can be -/// selected *en masse* by untrusted users. +/// secure against user-tainted keys, fairly fast and memory-efficient and supports iteration +/// over its keys and values. This must be used if the keys of your map can be selected *en +/// masse* by untrusted users. /// * `twox_64_concat`: This is an insecure hasher and can only be used safely if you know that /// the preimages cannot be chosen at will by untrusted users. It is memory-efficient, extremely /// performant and supports iteration over its keys and values. You can safely use this is the /// key is: /// - A (slowly) incrementing index. -/// - Known to be the result of a cryptographic hash (though `identity` is a better choice here). +/// - Known to be the result of a cryptographic hash (though `identity` is a better choice +/// here). /// - Known to be the public key of a cryptographic key pair in existence. /// * `identity`: This is not a hasher at all, and just uses the key material directly. Since it /// does no hashing or appending, it's the fastest possible hasher, however, it's also the least @@ -132,8 +133,9 @@ impl Counter { /// /// * Double map: `Foo: double_map hasher($hash1) u32, hasher($hash2) u32 => u32`: Implements the /// [`StorageDoubleMap`](../frame_support/storage/trait.StorageDoubleMap.html) trait using the -/// [`StorageDoubleMap generator`](../frame_support/storage/generator/trait.StorageDoubleMap.html). -/// And [`StoragePrefixedMap`](../frame_support/storage/trait.StoragePrefixedMap.html). +/// [`StorageDoubleMap +/// generator`](../frame_support/storage/generator/trait.StorageDoubleMap.html). And +/// [`StoragePrefixedMap`](../frame_support/storage/trait.StoragePrefixedMap.html). /// /// `$hash1` and `$hash2` representing choices of hashing algorithms available in the /// [`Hashable`](../frame_support/trait.Hashable.html) trait. They must be chosen with care, see @@ -147,8 +149,8 @@ impl Counter { /// /// Thus keys are stored at: /// ```nocompile -/// Twox128(module_prefix) ++ Twox128(storage_prefix) ++ Hasher1(encode(key1)) ++ Hasher2(encode(key2)) -/// ``` +/// Twox128(module_prefix) ++ Twox128(storage_prefix) ++ Hasher1(encode(key1)) ++ +/// Hasher2(encode(key2)) ``` /// /// Supported hashers (ordered from least to best security): /// @@ -176,8 +178,8 @@ impl Counter { /// Will include the item in `GenesisConfig`. /// * \[optional\] `build(#closure)`: Closure called with storage overlays. /// * \[optional\] `max_values(#expr)`: `expr` is an expression returning a `u32`. It is used to -/// implement `StorageInfoTrait`. Note this attribute is not available for storage value as the maximum -/// number of values is 1. +/// implement `StorageInfoTrait`. Note this attribute is not available for storage value as the +/// maximum number of values is 1. /// * `#type`: Storage type. /// * \[optional\] `#default`: Value returned when none. /// @@ -339,8 +341,8 @@ pub fn decl_storage(input: TokenStream) -> TokenStream { /// /// # Type definitions /// -/// * The macro generates a type alias for each pallet to their `Module` (or `Pallet`). -/// E.g. `type System = frame_system::Pallet` +/// * The macro generates a type alias for each pallet to their `Module` (or `Pallet`). E.g. `type +/// System = frame_system::Pallet` #[proc_macro] pub fn construct_runtime(input: TokenStream) -> TokenStream { construct_runtime::construct_runtime(input) diff --git a/substrate/frame/support/procedural/src/pallet/expand/call.rs b/substrate/frame/support/procedural/src/pallet/expand/call.rs index 4dcee9e24f..23ea9be9ea 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/call.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/call.rs @@ -19,6 +19,7 @@ use crate::{pallet::Def, COUNTER}; use frame_support_procedural_tools::clean_type_string; use syn::spanned::Spanned; +/// /// * Generate enum call and implement various trait on it. /// * Implement Callable and call_function on `Pallet` pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream { diff --git a/substrate/frame/support/procedural/src/pallet/expand/config.rs b/substrate/frame/support/procedural/src/pallet/expand/config.rs index 306578cc3a..17101b0be8 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/config.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/config.rs @@ -17,6 +17,7 @@ use crate::pallet::{parse::helper::get_doc_literals, Def}; +/// /// * Generate default rust doc pub fn expand_config(def: &mut Def) -> proc_macro2::TokenStream { let config = &def.config; diff --git a/substrate/frame/support/procedural/src/pallet/expand/constants.rs b/substrate/frame/support/procedural/src/pallet/expand/constants.rs index 58df22e361..fcf77ae8e4 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/constants.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/constants.rs @@ -30,6 +30,7 @@ struct ConstDef { pub default_byte_impl: proc_macro2::TokenStream, } +/// /// * Impl fn module_constant_metadata for pallet. pub fn expand_constants(def: &mut Def) -> proc_macro2::TokenStream { let frame_support = &def.frame_support; diff --git a/substrate/frame/support/procedural/src/pallet/expand/error.rs b/substrate/frame/support/procedural/src/pallet/expand/error.rs index ce3d3428fc..19c4296ad0 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/error.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/error.rs @@ -17,6 +17,7 @@ use crate::pallet::{parse::helper::get_doc_literals, Def}; +/// /// * impl various trait on Error /// * impl ModuleErrorMetadata for Error pub fn expand_error(def: &mut Def) -> proc_macro2::TokenStream { diff --git a/substrate/frame/support/procedural/src/pallet/expand/event.rs b/substrate/frame/support/procedural/src/pallet/expand/event.rs index 08e59ae7e8..2a2a3020a9 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/event.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/event.rs @@ -21,6 +21,7 @@ use crate::{ }; use syn::{spanned::Spanned, Ident}; +/// /// * Add __Ignore variant on Event /// * Impl various trait on Event including metadata /// * if deposit_event is defined, implement deposit_event on module. diff --git a/substrate/frame/support/procedural/src/pallet/expand/genesis_build.rs b/substrate/frame/support/procedural/src/pallet/expand/genesis_build.rs index c68f2339cf..06acaf3242 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/genesis_build.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/genesis_build.rs @@ -17,6 +17,7 @@ use crate::pallet::Def; +/// /// * implement the trait `sp_runtime::BuildModuleGenesisStorage` /// * add #[cfg(features = "std")] to GenesisBuild implementation. pub fn expand_genesis_build(def: &mut Def) -> proc_macro2::TokenStream { diff --git a/substrate/frame/support/procedural/src/pallet/expand/genesis_config.rs b/substrate/frame/support/procedural/src/pallet/expand/genesis_config.rs index b26be2b34a..8c540209f4 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/genesis_config.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/genesis_config.rs @@ -21,6 +21,7 @@ use crate::{ }; use syn::{spanned::Spanned, Ident}; +/// /// * add various derive trait on GenesisConfig struct. pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { let count = COUNTER.with(|counter| counter.borrow_mut().inc()); diff --git a/substrate/frame/support/procedural/src/pallet/expand/hooks.rs b/substrate/frame/support/procedural/src/pallet/expand/hooks.rs index 314f982c5a..e0b7e3669d 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/hooks.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/hooks.rs @@ -17,6 +17,7 @@ use crate::pallet::Def; +/// /// * implement the individual traits using the Hooks trait pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { let (where_clause, span, has_runtime_upgrade) = match def.hooks.as_ref() { diff --git a/substrate/frame/support/procedural/src/pallet/expand/instances.rs b/substrate/frame/support/procedural/src/pallet/expand/instances.rs index ceb86fcad7..2ecb5ec481 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/instances.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/instances.rs @@ -18,6 +18,7 @@ use crate::{pallet::Def, NUMBER_OF_INSTANCE}; use proc_macro2::Span; +/// /// * Provide inherent instance to be used by construct_runtime /// * Provide Instance1 ..= Instance16 for instantiable pallet pub fn expand_instances(def: &mut Def) -> proc_macro2::TokenStream { diff --git a/substrate/frame/support/procedural/src/pallet/expand/pallet_struct.rs b/substrate/frame/support/procedural/src/pallet/expand/pallet_struct.rs index ccc6fee5c2..40fc39b161 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/pallet_struct.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/pallet_struct.rs @@ -17,6 +17,7 @@ use crate::pallet::{expand::merge_where_clauses, parse::helper::get_doc_literals, Def}; +/// /// * Add derive trait on Pallet /// * Implement GetStorageVersion on Pallet /// * Implement OnGenesis on Pallet diff --git a/substrate/frame/support/procedural/src/pallet/expand/storage.rs b/substrate/frame/support/procedural/src/pallet/expand/storage.rs index 21d6628c8b..ac03a41deb 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/storage.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/storage.rs @@ -46,6 +46,7 @@ fn check_prefix_duplicates(storage_def: &StorageDef, set: &mut HashSet) Ok(()) } +/// /// * if generics are unnamed: replace the first generic `_` by the generated prefix structure /// * if generics are named: reorder the generic, remove their name, and add the missing ones. /// * Add `#[allow(type_alias_bounds)]` @@ -150,6 +151,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> { Ok(()) } +/// /// * generate StoragePrefix structs (e.g. for a storage `MyStorage` a struct with the name /// `_GeneratedPrefixForStorage$NameOfStorage` is generated) and implements StorageInstance trait. /// * if generics are unnamed: replace the first generic `_` by the generated prefix structure diff --git a/substrate/frame/support/procedural/src/pallet/expand/type_value.rs b/substrate/frame/support/procedural/src/pallet/expand/type_value.rs index b1b94eb4fb..535a187773 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/type_value.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/type_value.rs @@ -17,6 +17,7 @@ use crate::pallet::Def; +/// /// * Generate the struct /// * implement the `Get<..>` on it /// * Rename the name of the function to internal name diff --git a/substrate/frame/support/procedural/src/pallet/parse/storage.rs b/substrate/frame/support/procedural/src/pallet/parse/storage.rs index 7927aa2455..5df7bc132d 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/storage.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/storage.rs @@ -112,7 +112,8 @@ pub struct StorageDef { pub instances: Vec, /// Optional getter to generate. If some then query_kind is ensured to be some as well. pub getter: Option, - /// Optional expression that evaluates to a type that can be used as StoragePrefix instead of ident. + /// Optional expression that evaluates to a type that can be used as StoragePrefix instead of + /// ident. pub rename_as: Option, /// Whereas the querytype of the storage is OptionQuery or ValueQuery. /// Note that this is best effort as it can't be determined when QueryKind is generic, and diff --git a/substrate/frame/support/src/lib.rs b/substrate/frame/support/src/lib.rs index d1a62106dc..bf314161c7 100644 --- a/substrate/frame/support/src/lib.rs +++ b/substrate/frame/support/src/lib.rs @@ -271,10 +271,10 @@ macro_rules! generate_storage_alias { /// /// `twox_128(":" ++ NAME ++ ":")` where `NAME` is the name that is passed as type name. /// -/// - Using `static` to create a static parameter type. Its value is -/// being provided by a static variable with the equivalent name in `UPPER_SNAKE_CASE`. An -/// additional `set` function is provided in this case to alter the static variable. -/// **This is intended for testing ONLY and is ONLY available when `std` is enabled.** +/// - Using `static` to create a static parameter type. Its value is being provided by a static +/// variable with the equivalent name in `UPPER_SNAKE_CASE`. An additional `set` function is +/// provided in this case to alter the static variable. **This is intended for testing ONLY and is +/// ONLY available when `std` is enabled.** /// /// # Examples /// @@ -1314,11 +1314,11 @@ pub mod pallet_prelude { /// } /// ``` /// -/// Inside the module the macro will parse item with the attribute: `#[pallet::*]`, some attributes -/// are mandatory, some other optional. +/// Inside the module the macro will parse item with the attribute: `#[pallet::*]`, some +/// attributes are mandatory, some other optional. /// -/// The attribute are explained with the syntax of non instantiable pallets, to see how pallet with -/// instance work see below example. +/// The attribute are explained with the syntax of non instantiable pallets, to see how pallet +/// with instance work see below example. /// /// Note various type can be automatically imported using pallet_prelude in frame_support and /// frame_system: @@ -1348,7 +1348,8 @@ pub mod pallet_prelude { /// optionally other supertrait and where clause. /// /// The associated type `Event` is reserved, if defined it must bounds `From` and -/// `IsType<::Event>`, see `#[pallet::event]` for more information. +/// `IsType<::Event>`, see `#[pallet::event]` for more +/// information. /// /// To put `Get` associated type into metadatas, use the attribute `#[pallet::constant]`, e.g.: /// ```ignore @@ -1369,7 +1370,8 @@ pub mod pallet_prelude { /// /// ### Macro expansion: /// -/// The macro expand pallet constant metadata with the information given by `#[pallet::constant]`. +/// The macro expand pallet constant metadata with the information given by +/// `#[pallet::constant]`. /// /// # Pallet struct placeholder: `#[pallet::pallet]` mandatory /// @@ -1389,8 +1391,8 @@ pub mod pallet_prelude { /// #[pallet::generate_store(pub(super) trait Store)] /// pub struct Pallet(_); /// ``` -/// More precisely the store trait contains an associated type for each storage. It is implemented -/// for `Pallet` allowing to access the storage from pallet struct. +/// More precisely the store trait contains an associated type for each storage. It is +/// implemented for `Pallet` allowing to access the storage from pallet struct. /// /// Thus when defining a storage named `Foo`, it can later be accessed from `Pallet` using /// `::Foo`. @@ -1406,8 +1408,8 @@ pub mod pallet_prelude { /// This require all storage to implement the trait [`traits::StorageInfoTrait`], thus all keys /// and value types must bound [`pallet_prelude::MaxEncodedLen`]. /// -/// As the macro implements [`traits::GetStorageVersion`], the current storage version needs to be -/// communicated to the macro. This can be done by using the `storage_version` attribute: +/// As the macro implements [`traits::GetStorageVersion`], the current storage version needs to +/// be communicated to the macro. This can be done by using the `storage_version` attribute: /// /// ```ignore /// const STORAGE_VERSION: StorageVersion = StorageVersion::new(5); @@ -1439,14 +1441,15 @@ pub mod pallet_prelude { /// /// It declare `type Module` type alias for `Pallet`, used by [`construct_runtime`]. /// -/// It implements [`traits::PalletInfoAccess`] on `Pallet` to ease access to pallet informations -/// given by [`frame_support::traits::PalletInfo`]. +/// It implements [`traits::PalletInfoAccess`] on `Pallet` to ease access to pallet +/// informations given by [`frame_support::traits::PalletInfo`]. /// (The implementation use the associated type `frame_system::Config::PalletInfo`). /// -/// It implements [`traits::StorageInfoTrait`] on `Pallet` which give information about all storages. +/// It implements [`traits::StorageInfoTrait`] on `Pallet` which give information about all +/// storages. /// -/// If the attribute generate_store is set then the macro creates the trait `Store` and implements -/// it on `Pallet`. +/// If the attribute generate_store is set then the macro creates the trait `Store` and +/// implements it on `Pallet`. /// /// If the attribute set_storage_max_encoded_len is set then the macro call /// [`traits::StorageInfoTrait`] for each storage in the implementation of @@ -1468,8 +1471,8 @@ pub mod pallet_prelude { /// `Hooks>` (they are defined in preludes), for the type `Pallet` /// and with an optional where clause. /// -/// If no `#[pallet::hooks]` exists, then a default implementation corresponding to the following -/// code is automatically generated: +/// If no `#[pallet::hooks]` exists, then a default implementation corresponding to the +/// following code is automatically generated: /// ```ignore /// #[pallet::hooks] /// impl Hooks> for Pallet {} @@ -1483,8 +1486,8 @@ pub mod pallet_prelude { /// NOTE: OnRuntimeUpgrade is implemented with `Hooks::on_runtime_upgrade` and some additional /// logic. E.g. logic to write pallet version into storage. /// -/// NOTE: The macro also adds some tracing logic when implementing the above traits. The following -/// hooks emit traces: `on_initialize`, `on_finalize` and `on_runtime_upgrade`. +/// NOTE: The macro also adds some tracing logic when implementing the above traits. The +/// following hooks emit traces: `on_initialize`, `on_finalize` and `on_runtime_upgrade`. /// /// # Call: `#[pallet::call]` optional /// @@ -1511,30 +1514,30 @@ pub mod pallet_prelude { /// optional where clause. /// /// Each dispatchable needs to define a weight with `#[pallet::weight($expr)]` attribute, -/// the first argument must be `origin: OriginFor`, compact encoding for argument can be used -/// using `#[pallet::compact]`, function must return `DispatchResultWithPostInfo` or +/// the first argument must be `origin: OriginFor`, compact encoding for argument can be +/// used using `#[pallet::compact]`, function must return `DispatchResultWithPostInfo` or /// `DispatchResult`. /// -/// All arguments must implement `Debug`, `PartialEq`, `Eq`, `Decode`, `Encode`, `Clone`. For ease -/// of use, bound the trait `Member` available in frame_support::pallet_prelude. +/// All arguments must implement `Debug`, `PartialEq`, `Eq`, `Decode`, `Encode`, `Clone`. For +/// ease of use, bound the trait `Member` available in frame_support::pallet_prelude. /// -/// If no `#[pallet::call]` exists, then a default implementation corresponding to the following -/// code is automatically generated: +/// If no `#[pallet::call]` exists, then a default implementation corresponding to the +/// following code is automatically generated: /// ```ignore /// #[pallet::call] /// impl Pallet {} /// ``` /// /// **WARNING**: modifying dispatchables, changing their order, removing some must be done with -/// care. Indeed this will change the outer runtime call type (which is an enum with one variant -/// per pallet), this outer runtime call can be stored on-chain (e.g. in pallet-scheduler). -/// Thus migration might be needed. +/// care. Indeed this will change the outer runtime call type (which is an enum with one +/// variant per pallet), this outer runtime call can be stored on-chain (e.g. in +/// pallet-scheduler). Thus migration might be needed. /// /// ### Macro expansion /// /// The macro create an enum `Call` with one variant per dispatchable. This enum implements: -/// `Clone`, `Eq`, `PartialEq`, `Debug` (with stripped implementation in `not("std")`), `Encode`, -/// `Decode`, `GetDispatchInfo`, `GetCallName`, `UnfilteredDispatchable`. +/// `Clone`, `Eq`, `PartialEq`, `Debug` (with stripped implementation in `not("std")`), +/// `Encode`, `Decode`, `GetDispatchInfo`, `GetCallName`, `UnfilteredDispatchable`. /// /// The macro implement on `Pallet`, the `Callable` trait and a function `call_functions` which /// returns the dispatchable metadatas. @@ -1554,8 +1557,8 @@ pub mod pallet_prelude { /// ... /// } /// ``` -/// I.e. a regular rust implement block with some optional where clause and functions with 0 args, -/// 0 generics, and some return type. +/// I.e. a regular rust implement block with some optional where clause and functions with 0 +/// args, 0 generics, and some return type. /// /// ### Macro expansion /// @@ -1576,13 +1579,13 @@ pub mod pallet_prelude { /// } /// ``` /// I.e. a regular rust enum named `Error`, with generic `T` and fieldless variants. -/// The generic `T` mustn't bound anything and where clause is not allowed. But bounds and where -/// clause shouldn't be needed for any usecase. +/// The generic `T` mustn't bound anything and where clause is not allowed. But bounds and +/// where clause shouldn't be needed for any usecase. /// /// ### Macro expansion /// -/// The macro implements `Debug` trait and functions `as_u8` using variant position, and `as_str` -/// using variant doc. +/// The macro implements `Debug` trait and functions `as_u8` using variant position, and +/// `as_str` using variant doc. /// /// The macro implements `From>` for `&'static str`. /// The macro implements `From>` for `DispatchError`. @@ -1592,8 +1595,8 @@ pub mod pallet_prelude { /// /// # Event: `#[pallet::event]` optional /// -/// Allow to define pallet events, pallet events are stored in the block when they deposited (and -/// removed in next block). +/// Allow to define pallet events, pallet events are stored in the block when they deposited +/// (and removed in next block). /// /// Item is defined as: /// ```ignore @@ -1606,15 +1609,16 @@ pub mod pallet_prelude { /// ... /// } /// ``` -/// I.e. an enum (with named or unnamed fields variant), named Event, with generic: none or `T` or -/// `T: Config`, and optional where clause. +/// I.e. an enum (with named or unnamed fields variant), named Event, with generic: none or `T` +/// or `T: Config`, and optional where clause. /// -/// Each field must implement `Clone`, `Eq`, `PartialEq`, `Encode`, `Decode`, and `Debug` (on std -/// only). +/// Each field must implement `Clone`, `Eq`, `PartialEq`, `Encode`, `Decode`, and `Debug` (on +/// std only). /// For ease of use, bound the trait `Member` available in frame_support::pallet_prelude. /// /// Variant documentations and field types are put into metadata. -/// The attribute `#[pallet::metadata(..)]` allows to specify the metadata to put for some types. +/// The attribute `#[pallet::metadata(..)]` allows to specify the metadata to put for some +/// types. /// /// The metadata of a type is defined by: /// * if matching a type in `#[pallet::metadata(..)]`, then the corresponding metadata. @@ -1676,16 +1680,16 @@ pub mod pallet_prelude { /// For named generic argument: the name for each argument is the one as define on the storage /// struct: /// * [`pallet_prelude::StorageValue`] expect `Value` and optionally `QueryKind` and `OnEmpty`, -/// * [`pallet_prelude::StorageMap`] expect `Hasher`, `Key`, `Value` and optionally `QueryKind` and -/// `OnEmpty`, -/// * [`pallet_prelude::StorageDoubleMap`] expect `Hasher1`, `Key1`, `Hasher2`, `Key2`, `Value` and -/// optionally `QueryKind` and `OnEmpty`. +/// * [`pallet_prelude::StorageMap`] expect `Hasher`, `Key`, `Value` and optionally `QueryKind` +/// and `OnEmpty`, +/// * [`pallet_prelude::StorageDoubleMap`] expect `Hasher1`, `Key1`, `Hasher2`, `Key2`, `Value` +/// and optionally `QueryKind` and `OnEmpty`. /// -/// For unnamed generic argument: Their first generic must be `_` as it is replaced by the macro -/// and other generic must declared as a normal declaration of type generic in rust. +/// For unnamed generic argument: Their first generic must be `_` as it is replaced by the +/// macro and other generic must declared as a normal declaration of type generic in rust. /// -/// The Prefix generic written by the macro is generated using `PalletInfo::name::>()` -/// and the name of the storage type. +/// The Prefix generic written by the macro is generated using +/// `PalletInfo::name::>()` and the name of the storage type. /// E.g. if runtime names the pallet "MyExample" then the storage `type Foo = ...` use the /// prefix: `Twox128(b"MyExample") ++ Twox128(b"Foo")`. /// @@ -1714,12 +1718,12 @@ pub mod pallet_prelude { /// pub(super) type MyStorage = StorageValue; /// ``` /// -/// All the `cfg` attributes are automatically copied to the items generated for the storage, i.e. the -/// getter, storage prefix, and the metadata element etc. +/// All the `cfg` attributes are automatically copied to the items generated for the storage, +/// i.e. the getter, storage prefix, and the metadata element etc. /// -/// NOTE: If the `QueryKind` generic parameter is still generic at this stage or is using some type -/// alias then the generation of the getter might fail. In this case the getter can be implemented -/// manually. +/// NOTE: If the `QueryKind` generic parameter is still generic at this stage or is using some +/// type alias then the generation of the getter might fail. In this case the getter can be +/// implemented manually. /// /// NOTE: The generic `Hasher` must implement the [`StorageHasher`] trait (or the type is not /// usable at all). We use [`StorageHasher::METADATA`] for the metadata of the hasher of the @@ -1729,17 +1733,17 @@ pub mod pallet_prelude { /// /// For each storage item the macro generates a struct named /// `_GeneratedPrefixForStorage$NameOfStorage`, and implements -/// [`StorageInstance`](traits::StorageInstance) on it using the pallet and storage name. It then -/// uses it as the first generic of the aliased type. +/// [`StorageInstance`](traits::StorageInstance) on it using the pallet and storage name. It +/// then uses it as the first generic of the aliased type. /// /// For named generic, the macro will reorder the generics, and remove the names. /// -/// The macro implements the function `storage_metadata` on `Pallet` implementing the metadata for -/// all storage items based on their kind: +/// The macro implements the function `storage_metadata` on `Pallet` implementing the metadata +/// for all storage items based on their kind: /// * for a storage value, the type of the value is copied into the metadata /// * for a storage map, the type of the values and the key's type is copied into the metadata -/// * for a storage double map, the type of the values, and the types of key1 and key2 are copied into -/// the metadata. +/// * for a storage double map, the type of the values, and the types of key1 and key2 are +/// copied into the metadata. /// /// # Type value: `#[pallet::type_value]` optional /// @@ -1764,9 +1768,9 @@ pub mod pallet_prelude { /// /// ### Macro expansion /// -/// Macro renames the function to some internal name, generate a struct with the original name of -/// the function and its generic, and implement `Get<$ReturnType>` by calling the user defined -/// function. +/// Macro renames the function to some internal name, generate a struct with the original name +/// of the function and its generic, and implement `Get<$ReturnType>` by calling the user +/// defined function. /// /// # Genesis config: `#[pallet::genesis_config]` optional /// @@ -1805,8 +1809,8 @@ pub mod pallet_prelude { /// fn build(&self) { $expr } /// } /// ``` -/// I.e. a rust trait implementation with generic `T: Config`, of trait `GenesisBuild` on type -/// `GenesisConfig` with generics none or `T`. +/// I.e. a rust trait implementation with generic `T: Config`, of trait `GenesisBuild` on +/// type `GenesisConfig` with generics none or `T`. /// /// E.g.: /// ```ignore @@ -1821,8 +1825,8 @@ pub mod pallet_prelude { /// Macro will add the following attribute on it: /// * `#[cfg(feature = "std")]` /// -/// Macro will implement `sp_runtime::BuildModuleGenesisStorage` using `()` as second generic for -/// non-instantiable pallets. +/// Macro will implement `sp_runtime::BuildModuleGenesisStorage` using `()` as second generic +/// for non-instantiable pallets. /// /// # Inherent: `#[pallet::inherent]` optional /// @@ -1857,8 +1861,8 @@ pub mod pallet_prelude { /// I.e. a trait implementation with bound `T: Config`, of trait `ValidateUnsigned` for type /// `Pallet`, and some optional where clause. /// -/// NOTE: There is also `sp_runtime::traits::SignedExtension` that can be used to add some specific -/// logic for transaction validation. +/// NOTE: There is also `sp_runtime::traits::SignedExtension` that can be used to add some +/// specific logic for transaction validation. /// /// ### Macro expansion /// @@ -1877,19 +1881,19 @@ pub mod pallet_prelude { /// pub struct Origin(PhantomData<(T)>); /// ``` /// -/// **WARNING**: modifying origin changes the outer runtime origin. This outer runtime origin can -/// be stored on-chain (e.g. in pallet-scheduler), thus any change must be done with care as it -/// might require some migration. +/// **WARNING**: modifying origin changes the outer runtime origin. This outer runtime origin +/// can be stored on-chain (e.g. in pallet-scheduler), thus any change must be done with care +/// as it might require some migration. /// /// NOTE: for instantiable pallet, origin must be generic over T and I. /// /// # General notes on instantiable pallet /// -/// An instantiable pallet is one where Config is generic, i.e. `Config`. This allow runtime to -/// implement multiple instance of the pallet, by using different type for the generic. +/// An instantiable pallet is one where Config is generic, i.e. `Config`. This allow runtime +/// to implement multiple instance of the pallet, by using different type for the generic. /// This is the sole purpose of the generic `I`. -/// But because `PalletInfo` requires `Pallet` placeholder to be static it is important to bound -/// `'static` whenever `PalletInfo` can be used. +/// But because `PalletInfo` requires `Pallet` placeholder to be static it is important to +/// bound `'static` whenever `PalletInfo` can be used. /// And in order to have instantiable pallet usable as a regular pallet without instance, it is /// important to bound `= ()` on every types. /// @@ -2226,8 +2230,8 @@ pub mod pallet_prelude { /// /// 1. Export the metadata of the pallet for later checks /// - run your node with the pallet active -/// - query the metadata using the `state_getMetadata` RPC and curl, or use -/// `subsee -p > meta.json` +/// - query the metadata using the `state_getMetadata` RPC and curl, or use `subsee -p +/// > meta.json` /// 2. generate the template upgrade for the pallet provided by decl_storage /// with environment variable `PRINT_PALLET_UPGRADE`: /// `PRINT_PALLET_UPGRADE=1 cargo check -p my_pallet` This template can be @@ -2271,7 +2275,8 @@ pub mod pallet_prelude { /// impl Hooks for Pallet { /// } /// ``` -/// and write inside on_initialize/on_finalize/on_runtime_upgrade/offchain_worker/integrity_test +/// and write inside +/// `on_initialize`, `on_finalize`, `on_runtime_upgrade`, `offchain_worker`, `integrity_test`. /// /// then write: /// ```ignore @@ -2281,7 +2286,8 @@ pub mod pallet_prelude { /// ``` /// and write inside all the calls in decl_module with a few changes in the signature: /// - origin must now be written completely, e.g. `origin: OriginFor` -/// - result type must be `DispatchResultWithPostInfo`, you need to write it and also you might +/// - result type must be `DispatchResultWithPostInfo`, you need to write it and also you +/// might /// need to put `Ok(().into())` at the end or the function. /// - `#[compact]` must now be written `#[pallet::compact]` /// - `#[weight = ..]` must now be written `#[pallet::weight(..)]` @@ -2289,8 +2295,8 @@ pub mod pallet_prelude { /// 7. **migrate event**: /// rewrite as a simple enum under with the attribute `#[pallet::event]`, /// use `#[pallet::generate_deposit($vis fn deposit_event)]` to generate deposit_event, -/// use `#[pallet::metadata(...)]` to configure the metadata for types in order not to break them. -/// 8. **migrate error**: rewrite it with attribute `#[pallet::error]`. +/// use `#[pallet::metadata(...)]` to configure the metadata for types in order not to break +/// them. 8. **migrate error**: rewrite it with attribute `#[pallet::error]`. /// 9. **migrate storage**: /// decl_storage provide an upgrade template (see 3.). All storages, genesis config, genesis /// build and default implementation of genesis config can be taken from it directly. @@ -2308,7 +2314,8 @@ pub mod pallet_prelude { /// } /// #[pallet::genesis_build] /// impl GenesisBuild for GenesisConfig { -/// // impl GenesisBuild for GenesisConfig { for instantiable pallet +/// // for instantiable pallet: +/// // `impl GenesisBuild for GenesisConfig { /// fn build() { /// // The add_extra_genesis build logic /// } @@ -2325,10 +2332,12 @@ pub mod pallet_prelude { /// Once this is done you can migrate storage individually, a few notes: /// - for private storage use `pub(crate) type ` or `pub(super) type` or nothing, /// - for storage with `get(fn ..)` use `#[pallet::getter(fn ...)]` -/// - for storage with value being `Option<$something>` make generic `Value` being `$something` +/// - for storage with value being `Option<$something>` make generic `Value` being +/// `$something` /// and generic `QueryKind` being `OptionQuery` (note: this is default). Otherwise make /// `Value` the complete value type and `QueryKind` being `ValueQuery`. -/// - for storage with default value: `= $expr;` provide some specific OnEmpty generic. To do so +/// - for storage with default value: `= $expr;` provide some specific OnEmpty generic. To do +/// so /// use of `#[pallet::type_value]` to generate the wanted struct to put. /// example: `MyStorage: u32 = 3u32` would be written: /// ```ignore @@ -2361,9 +2370,11 @@ pub mod pallet_prelude { /// * error , error, constant, /// * manually check that: /// * `Origin` is moved inside the macro under `#[pallet::origin]` if it exists -/// * `ValidateUnsigned` is moved inside the macro under `#[pallet::validate_unsigned)]` if it exists +/// * `ValidateUnsigned` is moved inside the macro under `#[pallet::validate_unsigned)]` if it +/// exists /// * `ProvideInherent` is moved inside macro under `#[pallet::inherent)]` if it exists -/// * `on_initialize`/`on_finalize`/`on_runtime_upgrade`/`offchain_worker` are moved to `Hooks` +/// * `on_initialize`/`on_finalize`/`on_runtime_upgrade`/`offchain_worker` are moved to +/// `Hooks` /// implementation /// * storages with `config(..)` are converted to `GenesisConfig` field, and their default is /// `= $expr;` if the storage have default value @@ -2380,8 +2391,9 @@ pub mod pallet_prelude { /// as the name the pallet was giving to `decl_storage`, /// * or do a storage migration from the old prefix used to the new prefix used. /// -/// NOTE: The prefixes used by storage items are in the metadata. Thus, ensuring the metadata hasn't -/// changed does ensure that the `pallet_prefix`s used by the storage items haven't changed. +/// NOTE: The prefixes used by storage items are in the metadata. Thus, ensuring the metadata +/// hasn't changed does ensure that the `pallet_prefix`s used by the storage items haven't +/// changed. /// /// # Notes when macro fails to show proper error message spans: /// diff --git a/substrate/frame/support/src/storage/bounded_btree_map.rs b/substrate/frame/support/src/storage/bounded_btree_map.rs index f8ea35ae58..737c8953d2 100644 --- a/substrate/frame/support/src/storage/bounded_btree_map.rs +++ b/substrate/frame/support/src/storage/bounded_btree_map.rs @@ -125,7 +125,8 @@ where } } - /// Remove a key from the map, returning the value at the key if the key was previously in the map. + /// Remove a key from the map, returning the value at the key if the key was previously in the + /// map. /// /// The key may be any borrowed form of the map's key type, but the ordering on the borrowed /// form _must_ match the ordering on the key type. @@ -137,7 +138,8 @@ where self.0.remove(key) } - /// Remove a key from the map, returning the value at the key if the key was previously in the map. + /// Remove a key from the map, returning the value at the key if the key was previously in the + /// map. /// /// The key may be any borrowed form of the map's key type, but the ordering on the borrowed /// form _must_ match the ordering on the key type. diff --git a/substrate/frame/support/src/storage/mod.rs b/substrate/frame/support/src/storage/mod.rs index 57cbc6e31d..ac2ddaa73c 100644 --- a/substrate/frame/support/src/storage/mod.rs +++ b/substrate/frame/support/src/storage/mod.rs @@ -160,8 +160,8 @@ pub trait StorageValue { /// # Usage /// /// This would typically be called inside the module implementation of on_runtime_upgrade, while - /// ensuring **no usage of this storage are made before the call to `on_runtime_upgrade`**. (More - /// precisely prior initialized modules doesn't make use of this storage). + /// ensuring **no usage of this storage are made before the call to `on_runtime_upgrade`**. + /// (More precisely prior initialized modules doesn't make use of this storage). fn translate) -> Option>(f: F) -> Result, ()>; /// Store a value under this key into the provided storage instance. @@ -989,7 +989,8 @@ impl ChildTriePrefixIterator { } impl ChildTriePrefixIterator<(Vec, T)> { - /// Construct iterator to iterate over child trie items in `child_info` with the prefix `prefix`. + /// Construct iterator to iterate over child trie items in `child_info` with the prefix + /// `prefix`. /// /// NOTE: Iterator with [`Self::drain`] will remove any value who failed to decode pub fn with_prefix(child_info: &ChildInfo, prefix: &[u8]) -> Self { @@ -1012,7 +1013,8 @@ impl ChildTriePrefixIterator<(Vec, T)> { } impl ChildTriePrefixIterator<(K, T)> { - /// Construct iterator to iterate over child trie items in `child_info` with the prefix `prefix`. + /// Construct iterator to iterate over child trie items in `child_info` with the prefix + /// `prefix`. /// /// NOTE: Iterator with [`Self::drain`] will remove any key or value who failed to decode pub fn with_prefix_over_key( diff --git a/substrate/frame/support/src/storage/types/key.rs b/substrate/frame/support/src/storage/types/key.rs index a8cdb4546a..db66838e3f 100755 --- a/substrate/frame/support/src/storage/types/key.rs +++ b/substrate/frame/support/src/storage/types/key.rs @@ -58,7 +58,8 @@ pub trait KeyGeneratorMaxEncodedLen: KeyGenerator { fn key_max_encoded_len() -> usize; } -/// A trait containing methods that are only implemented on the Key struct instead of the entire tuple. +/// A trait containing methods that are only implemented on the Key struct instead of the entire +/// tuple. pub trait KeyGeneratorInner: KeyGenerator { type Hasher: StorageHasher; diff --git a/substrate/frame/support/src/storage/types/mod.rs b/substrate/frame/support/src/storage/types/mod.rs index f800f33dc3..d61ca6813c 100644 --- a/substrate/frame/support/src/storage/types/mod.rs +++ b/substrate/frame/support/src/storage/types/mod.rs @@ -39,10 +39,10 @@ pub use value::{StorageValue, StorageValueMetadata}; /// Trait implementing how the storage optional value is converted into the queried type. /// /// It is implemented by: -/// * `OptionQuery` which convert an optional value to an optional value, user when querying -/// storage will get an optional value. -/// * `ValueQuery` which convert an optional value to a value, user when querying storage will get -/// a value. +/// * `OptionQuery` which convert an optional value to an optional value, user when querying storage +/// will get an optional value. +/// * `ValueQuery` which convert an optional value to a value, user when querying storage will get a +/// value. pub trait QueryKindTrait { /// Metadata for the storage kind. const METADATA: StorageEntryModifier; diff --git a/substrate/frame/support/src/storage/weak_bounded_vec.rs b/substrate/frame/support/src/storage/weak_bounded_vec.rs index 9fa3602306..f60e4d87bd 100644 --- a/substrate/frame/support/src/storage/weak_bounded_vec.rs +++ b/substrate/frame/support/src/storage/weak_bounded_vec.rs @@ -270,8 +270,8 @@ impl codec::DecodeLength for WeakBoundedVec { } // NOTE: we could also implement this as: -// impl, S2: Get> PartialEq> for WeakBoundedVec -// to allow comparison of bounded vectors with different bounds. +// impl, S2: Get> PartialEq> for WeakBoundedVec to allow comparison of bounded vectors with different bounds. impl PartialEq for WeakBoundedVec where T: PartialEq, diff --git a/substrate/frame/support/src/traits/members.rs b/substrate/frame/support/src/traits/members.rs index 1d7c1c7320..35405e4473 100644 --- a/substrate/frame/support/src/traits/members.rs +++ b/substrate/frame/support/src/traits/members.rs @@ -185,8 +185,8 @@ pub trait ChangeMembers { sorted_new: &[AccountId], ); - /// Set the new members; they **must already be sorted**. This will compute the diff and use it to - /// call `change_members_sorted`. + /// Set the new members; they **must already be sorted**. This will compute the diff and use it + /// to call `change_members_sorted`. /// /// This resets any previous value of prime. fn set_members_sorted(new_members: &[AccountId], old_members: &[AccountId]) { diff --git a/substrate/frame/support/src/traits/misc.rs b/substrate/frame/support/src/traits/misc.rs index 382c5ebf57..1776e1ba32 100644 --- a/substrate/frame/support/src/traits/misc.rs +++ b/substrate/frame/support/src/traits/misc.rs @@ -277,7 +277,8 @@ pub trait IsSubType { pub trait ExecuteBlock { /// Execute the given `block`. /// - /// This will execute all extrinsics in the block and check that the resulting header is correct. + /// This will execute all extrinsics in the block and check that the resulting header is + /// correct. /// /// # Panic /// diff --git a/substrate/frame/support/src/traits/schedule.rs b/substrate/frame/support/src/traits/schedule.rs index 10a973a993..a4a4f9c03a 100644 --- a/substrate/frame/support/src/traits/schedule.rs +++ b/substrate/frame/support/src/traits/schedule.rs @@ -42,8 +42,8 @@ pub enum DispatchTime { /// The highest priority. We invert the value so that normal sorting will place the highest /// priority at the beginning of the list. pub const HIGHEST_PRIORITY: Priority = 0; -/// Anything of this value or lower will definitely be scheduled on the block that they ask for, even -/// if it breaches the `MaximumWeight` limitation. +/// Anything of this value or lower will definitely be scheduled on the block that they ask for, +/// even if it breaches the `MaximumWeight` limitation. pub const HARD_DEADLINE: Priority = 63; /// The lowest priority. Most stuff should be around here. pub const LOWEST_PRIORITY: Priority = 255; diff --git a/substrate/frame/support/src/traits/storage.rs b/substrate/frame/support/src/traits/storage.rs index c0cbfb3a90..9a88a3ed44 100644 --- a/substrate/frame/support/src/traits/storage.rs +++ b/substrate/frame/support/src/traits/storage.rs @@ -21,7 +21,8 @@ use sp_std::prelude::*; /// An instance of a pallet in the storage. /// -/// It is required that these instances are unique, to support multiple instances per pallet in the same runtime! +/// It is required that these instances are unique, to support multiple instances per pallet in the +/// same runtime! /// /// E.g. for module MyModule default instance will have prefix "MyModule" and other instances /// "InstanceNMyModule". diff --git a/substrate/frame/support/src/traits/tokens/currency.rs b/substrate/frame/support/src/traits/tokens/currency.rs index 6c73a1527b..bf07865847 100644 --- a/substrate/frame/support/src/traits/tokens/currency.rs +++ b/substrate/frame/support/src/traits/tokens/currency.rs @@ -56,8 +56,8 @@ pub trait Currency { /// The total amount of issuance in the system. fn total_issuance() -> Self::Balance; - /// The minimum balance any single account may have. This is equivalent to the `Balances` module's - /// `ExistentialDeposit`. + /// The minimum balance any single account may have. This is equivalent to the `Balances` + /// module's `ExistentialDeposit`. fn minimum_balance() -> Self::Balance; /// Reduce the total issuance by `amount` and return the according imbalance. The imbalance will @@ -192,8 +192,8 @@ pub trait Currency { /// Ensure an account's free balance equals some value; this will create the account /// if needed. /// - /// Returns a signed imbalance and status to indicate if the account was successfully updated or update - /// has led to killing of the account. + /// Returns a signed imbalance and status to indicate if the account was successfully updated or + /// update has led to killing of the account. fn make_free_balance_be( who: &AccountId, balance: Self::Balance, diff --git a/substrate/frame/support/src/traits/tokens/currency/reservable.rs b/substrate/frame/support/src/traits/tokens/currency/reservable.rs index 41220ca81c..0ca7a93dc7 100644 --- a/substrate/frame/support/src/traits/tokens/currency/reservable.rs +++ b/substrate/frame/support/src/traits/tokens/currency/reservable.rs @@ -193,8 +193,8 @@ pub trait NamedReservableCurrency: ReservableCurrency { Self::slash_reserved_named(id, who, value).0 } - /// Move all the named reserved balance of one account into the balance of another, according to `status`. - /// If `status` is `Reserved`, the balance will be reserved with given `id`. + /// Move all the named reserved balance of one account into the balance of another, according to + /// `status`. If `status` is `Reserved`, the balance will be reserved with given `id`. /// /// Is a no-op if: /// - the value to be moved is zero; or diff --git a/substrate/frame/support/src/traits/tokens/fungible/balanced.rs b/substrate/frame/support/src/traits/tokens/fungible/balanced.rs index a54b29a9d9..7b33a595a1 100644 --- a/substrate/frame/support/src/traits/tokens/fungible/balanced.rs +++ b/substrate/frame/support/src/traits/tokens/fungible/balanced.rs @@ -198,7 +198,8 @@ pub trait Unbalanced: Inspect { } let mut r = Self::set_balance(who, new_balance); if r.is_err() { - // Some error, probably because we tried to destroy an account which cannot be destroyed. + // Some error, probably because we tried to destroy an account which cannot be + // destroyed. if new_balance.is_zero() && amount >= minimum_balance { new_balance = minimum_balance; amount -= minimum_balance; diff --git a/substrate/frame/support/src/traits/tokens/fungible/imbalance.rs b/substrate/frame/support/src/traits/tokens/fungible/imbalance.rs index e6d3b5bed6..362e0c126d 100644 --- a/substrate/frame/support/src/traits/tokens/fungible/imbalance.rs +++ b/substrate/frame/support/src/traits/tokens/fungible/imbalance.rs @@ -142,7 +142,8 @@ pub type DebtOf = Imbalance< >::OnDropCredit, >; -/// Imbalance implying that the total_issuance value is greater than the sum of all account balances. +/// Imbalance implying that the total_issuance value is greater than the sum of all account +/// balances. pub type CreditOf = Imbalance< >::Balance, // This will generally be implemented by decreasing the total_issuance value. diff --git a/substrate/frame/support/src/traits/tokens/fungibles/balanced.rs b/substrate/frame/support/src/traits/tokens/fungibles/balanced.rs index 9c601c3e7c..40a65305b8 100644 --- a/substrate/frame/support/src/traits/tokens/fungibles/balanced.rs +++ b/substrate/frame/support/src/traits/tokens/fungibles/balanced.rs @@ -223,7 +223,8 @@ pub trait Unbalanced: Inspect { } let mut r = Self::set_balance(asset, who, new_balance); if r.is_err() { - // Some error, probably because we tried to destroy an account which cannot be destroyed. + // Some error, probably because we tried to destroy an account which cannot be + // destroyed. if new_balance.is_zero() && amount >= minimum_balance { new_balance = minimum_balance; amount -= minimum_balance; diff --git a/substrate/frame/support/src/traits/tokens/fungibles/imbalance.rs b/substrate/frame/support/src/traits/tokens/fungibles/imbalance.rs index 2195cacc42..c44c471646 100644 --- a/substrate/frame/support/src/traits/tokens/fungibles/imbalance.rs +++ b/substrate/frame/support/src/traits/tokens/fungibles/imbalance.rs @@ -168,7 +168,8 @@ pub type DebtOf = Imbalance< >::OnDropCredit, >; -/// Imbalance implying that the total_issuance value is greater than the sum of all account balances. +/// Imbalance implying that the total_issuance value is greater than the sum of all account +/// balances. pub type CreditOf = Imbalance< >::AssetId, >::Balance, diff --git a/substrate/frame/support/src/traits/tokens/misc.rs b/substrate/frame/support/src/traits/tokens/misc.rs index 8eda930380..bea6e664cf 100644 --- a/substrate/frame/support/src/traits/tokens/misc.rs +++ b/substrate/frame/support/src/traits/tokens/misc.rs @@ -51,8 +51,8 @@ pub enum WithdrawConsequence { } impl WithdrawConsequence { - /// Convert the type into a `Result` with `DispatchError` as the error or the additional `Balance` - /// by which the account will be reduced. + /// Convert the type into a `Result` with `DispatchError` as the error or the additional + /// `Balance` by which the account will be reduced. pub fn into_result(self) -> Result { use WithdrawConsequence::*; match self { diff --git a/substrate/frame/support/src/traits/validation.rs b/substrate/frame/support/src/traits/validation.rs index a473e332a8..f4107ef6e2 100644 --- a/substrate/frame/support/src/traits/validation.rs +++ b/substrate/frame/support/src/traits/validation.rs @@ -238,7 +238,8 @@ impl Lateness for () { } /// Implementors of this trait provide information about whether or not some validator has -/// been registered with them. The [Session module](../../pallet_session/index.html) is an implementor. +/// been registered with them. The [Session module](../../pallet_session/index.html) is an +/// implementor. pub trait ValidatorRegistration { /// Returns true if the provided validator ID has been registered with the implementing runtime /// module diff --git a/substrate/frame/support/src/weights.rs b/substrate/frame/support/src/weights.rs index 6b4f5e4046..7af6d440aa 100644 --- a/substrate/frame/support/src/weights.rs +++ b/substrate/frame/support/src/weights.rs @@ -229,8 +229,9 @@ pub enum DispatchClass { Operational, /// A mandatory dispatch. These kinds of dispatch are always included regardless of their /// weight, therefore it is critical that they are separately validated to ensure that a - /// malicious validator cannot craft a valid but impossibly heavy block. Usually this just means - /// ensuring that the extrinsic can only be included once and that it is always very light. + /// malicious validator cannot craft a valid but impossibly heavy block. Usually this just + /// means ensuring that the extrinsic can only be included once and that it is always very + /// light. /// /// Do *NOT* use it for extrinsics that can be heavy. /// @@ -528,12 +529,12 @@ impl PaysFee for (Weight, Pays) { /// A struct to represent a weight which is a function of the input arguments. The given items have /// the following types: /// -/// - `WD`: a raw `Weight` value or a closure that returns a `Weight` with the same +/// - `WD`: a raw `Weight` value or a closure that returns a `Weight` with the same argument list as +/// the dispatched, wrapped in a tuple. +/// - `CD`: a raw `DispatchClass` value or a closure that returns a `DispatchClass` with the same /// argument list as the dispatched, wrapped in a tuple. -/// - `CD`: a raw `DispatchClass` value or a closure that returns a `DispatchClass` -/// with the same argument list as the dispatched, wrapped in a tuple. -/// - `PF`: a `Pays` variant for whether this dispatch pays fee or not or a closure that -/// returns a `Pays` variant with the same argument list as the dispatched, wrapped in a tuple. +/// - `PF`: a `Pays` variant for whether this dispatch pays fee or not or a closure that returns a +/// `Pays` variant with the same argument list as the dispatched, wrapped in a tuple. #[deprecated = "Function arguments are available directly inside the annotation now."] pub struct FunctionOf(pub WD, pub CD, pub PF); diff --git a/substrate/frame/support/test/src/lib.rs b/substrate/frame/support/test/src/lib.rs index ffda500f96..78317a1a2f 100644 --- a/substrate/frame/support/test/src/lib.rs +++ b/substrate/frame/support/test/src/lib.rs @@ -51,7 +51,8 @@ impl frame_support::traits::PalletInfo for PanicPalletInfo { } } -/// Provides an implementation of [`frame_support::traits::Randomness`] that should only be used in tests! +/// Provides an implementation of [`frame_support::traits::Randomness`] that should only be used in +/// tests! pub struct TestRandomness(sp_std::marker::PhantomData); impl frame_support::traits::Randomness diff --git a/substrate/frame/system/src/extensions/check_weight.rs b/substrate/frame/system/src/extensions/check_weight.rs index fae973ac18..1e7ad9454b 100644 --- a/substrate/frame/system/src/extensions/check_weight.rs +++ b/substrate/frame/system/src/extensions/check_weight.rs @@ -456,7 +456,8 @@ mod tests { CheckWeight::::do_pre_dispatch(&dispatch_normal, len), InvalidTransaction::ExhaustsResources ); - // Thank goodness we can still do an operational transaction to possibly save the blockchain. + // Thank goodness we can still do an operational transaction to possibly save the + // blockchain. assert_ok!(CheckWeight::::do_pre_dispatch(&dispatch_operational, len)); // Not too much though assert_err!( diff --git a/substrate/frame/system/src/lib.rs b/substrate/frame/system/src/lib.rs index 6b967fd892..a8bf253c39 100644 --- a/substrate/frame/system/src/lib.rs +++ b/substrate/frame/system/src/lib.rs @@ -27,8 +27,8 @@ //! The System pallet defines the core data types used in a Substrate runtime. //! It also provides several utility functions (see [`Pallet`]) for other FRAME pallets. //! -//! In addition, it manages the storage items for extrinsics data, indexes, event records, and digest items, -//! among other things that support the execution of the current block. +//! In addition, it manages the storage items for extrinsics data, indexes, event records, and +//! digest items, among other things that support the execution of the current block. //! //! It also handles low-level tasks like depositing logs, basic set up and take down of //! temporary storage entries, and access to previous block hashes. @@ -54,10 +54,10 @@ //! - [`CheckEra`]: Checks the era of the transaction. Contains a single payload of type `Era`. //! - [`CheckGenesis`]: Checks the provided genesis hash of the transaction. Must be a part of the //! signed payload of the transaction. -//! - [`CheckSpecVersion`]: Checks that the runtime version is the same as the one used to sign the -//! transaction. -//! - [`CheckTxVersion`]: Checks that the transaction version is the same as the one used to sign the -//! transaction. +//! - [`CheckSpecVersion`]: Checks that the runtime version is the same as the one used to sign +//! the transaction. +//! - [`CheckTxVersion`]: Checks that the transaction version is the same as the one used to sign +//! the transaction. //! //! Lookup the runtime aggregator file (e.g. `node/runtime`) to see the full list of signed //! extensions included in a chain. @@ -180,8 +180,8 @@ pub mod pallet { /// The aggregated `Call` type. type Call: Dispatchable + Debug; - /// Account index (aka nonce) type. This stores the number of previous transactions associated - /// with a sender account. + /// Account index (aka nonce) type. This stores the number of previous transactions + /// associated with a sender account. type Index: Parameter + Member + MaybeSerializeDeserialize @@ -238,10 +238,10 @@ pub mod pallet { /// Converting trait to take a source type and convert to `AccountId`. /// - /// Used to define the type and conversion mechanism for referencing accounts in transactions. - /// It's perfectly reasonable for this to be an identity conversion (with the source type being - /// `AccountId`), but other pallets (e.g. Indices pallet) may provide more functional/efficient - /// alternatives. + /// Used to define the type and conversion mechanism for referencing accounts in + /// transactions. It's perfectly reasonable for this to be an identity conversion (with the + /// source type being `AccountId`), but other pallets (e.g. Indices pallet) may provide more + /// functional/efficient alternatives. type Lookup: StaticLookup; /// The block header. @@ -363,10 +363,11 @@ pub mod pallet { /// # /// - `O(C + S)` where `C` length of `code` and `S` complexity of `can_set_code` /// - 1 storage write (codec `O(C)`). - /// - 1 call to `can_set_code`: `O(S)` (calls `sp_io::misc::runtime_version` which is expensive). + /// - 1 call to `can_set_code`: `O(S)` (calls `sp_io::misc::runtime_version` which is + /// expensive). /// - 1 event. - /// The weight of this function is dependent on the runtime, but generally this is very expensive. - /// We will treat this as a full block. + /// The weight of this function is dependent on the runtime, but generally this is very + /// expensive. We will treat this as a full block. /// # #[pallet::weight((T::BlockWeights::get().max_block, DispatchClass::Operational))] pub fn set_code(origin: OriginFor, code: Vec) -> DispatchResultWithPostInfo { @@ -384,8 +385,8 @@ pub mod pallet { /// - `O(C)` where `C` length of `code` /// - 1 storage write (codec `O(C)`). /// - 1 event. - /// The weight of this function is dependent on the runtime. We will treat this as a full block. - /// # + /// The weight of this function is dependent on the runtime. We will treat this as a full + /// block. # #[pallet::weight((T::BlockWeights::get().max_block, DispatchClass::Operational))] pub fn set_code_without_checks( origin: OriginFor, diff --git a/substrate/frame/timestamp/src/lib.rs b/substrate/frame/timestamp/src/lib.rs index a5a3b319b0..a1ff8d37ff 100644 --- a/substrate/frame/timestamp/src/lib.rs +++ b/substrate/frame/timestamp/src/lib.rs @@ -27,13 +27,14 @@ //! //! The Timestamp pallet allows the validators to set and validate a timestamp with each block. //! -//! It uses inherents for timestamp data, which is provided by the block author and validated/verified -//! by other validators. The timestamp can be set only once per block and must be set each block. -//! There could be a constraint on how much time must pass before setting the new timestamp. +//! It uses inherents for timestamp data, which is provided by the block author and +//! validated/verified by other validators. The timestamp can be set only once per block and must be +//! set each block. There could be a constraint on how much time must pass before setting the new +//! timestamp. //! -//! **NOTE:** The Timestamp pallet is the recommended way to query the on-chain time instead of using -//! an approach based on block numbers. The block number based time measurement can cause issues -//! because of cumulative calculation errors and hence should be avoided. +//! **NOTE:** The Timestamp pallet is the recommended way to query the on-chain time instead of +//! using an approach based on block numbers. The block number based time measurement can cause +//! issues because of cumulative calculation errors and hence should be avoided. //! //! ## Interface //! @@ -52,7 +53,8 @@ //! //! ## Usage //! -//! The following example shows how to use the Timestamp pallet in your custom pallet to query the current timestamp. +//! The following example shows how to use the Timestamp pallet in your custom pallet to query the +//! current timestamp. //! //! ### Prerequisites //! @@ -120,13 +122,14 @@ pub mod pallet { + Copy + MaxEncodedLen; - /// Something which can be notified when the timestamp is set. Set this to `()` if not needed. + /// Something which can be notified when the timestamp is set. Set this to `()` if not + /// needed. type OnTimestampSet: OnTimestampSet; - /// The minimum period between blocks. Beware that this is different to the *expected* period - /// that the block production apparatus provides. Your chosen consensus system will generally - /// work with this to determine a sensible block time. e.g. For Aura, it will be double this - /// period on default settings. + /// The minimum period between blocks. Beware that this is different to the *expected* + /// period that the block production apparatus provides. Your chosen consensus system will + /// generally work with this to determine a sensible block time. e.g. For Aura, it will be + /// double this period on default settings. #[pallet::constant] type MinimumPeriod: Get; @@ -179,7 +182,8 @@ pub mod pallet { /// /// # /// - `O(1)` (Note that implementations of `OnTimestampSet` must also be `O(1)`) - /// - 1 storage read and 1 storage mutation (codec `O(1)`). (because of `DidUpdate::take` in `on_finalize`) + /// - 1 storage read and 1 storage mutation (codec `O(1)`). (because of `DidUpdate::take` in + /// `on_finalize`) /// - 1 event handler `on_timestamp_set`. Must be `O(1)`. /// # #[pallet::weight(( diff --git a/substrate/frame/tips/src/lib.rs b/substrate/frame/tips/src/lib.rs index e8b5544bd6..ca327f6c87 100644 --- a/substrate/frame/tips/src/lib.rs +++ b/substrate/frame/tips/src/lib.rs @@ -22,11 +22,11 @@ //! A subsystem to allow for an agile "tipping" process, whereby a reward may be given without first //! having a pre-determined stakeholder group come to consensus on how much should be paid. //! -//! A group of `Tippers` is determined through the config `Config`. After half of these have declared -//! some amount that they believe a particular reported reason deserves, then a countdown period is -//! entered where any remaining members can declare their tip amounts also. After the close of the -//! countdown period, the median of all declared tips is paid to the reported beneficiary, along -//! with any finders fee, in case of a public (and bonded) original report. +//! A group of `Tippers` is determined through the config `Config`. After half of these have +//! declared some amount that they believe a particular reported reason deserves, then a countdown +//! period is entered where any remaining members can declare their tip amounts also. After the +//! close of the countdown period, the median of all declared tips is paid to the reported +//! beneficiary, along with any finders fee, in case of a public (and bonded) original report. //! //! //! ### Terminology @@ -114,8 +114,8 @@ pub struct OpenTip< BlockNumber: Parameter, Hash: Parameter, > { - /// The hash of the reason for the tip. The reason should be a human-readable UTF-8 encoded string. A URL would be - /// sensible. + /// The hash of the reason for the tip. The reason should be a human-readable UTF-8 encoded + /// string. A URL would be sensible. reason: Hash, /// The account to be tipped. who: AccountId, @@ -530,8 +530,8 @@ impl Module { } pub fn migrate_retract_tip_for_tip_new() { - /// An open tipping "motion". Retains all details of a tip including information on the finder - /// and the members who have voted. + /// An open tipping "motion". Retains all details of a tip including information on the + /// finder and the members who have voted. #[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug)] pub struct OldOpenTip< AccountId: Parameter, @@ -539,15 +539,15 @@ impl Module { BlockNumber: Parameter, Hash: Parameter, > { - /// The hash of the reason for the tip. The reason should be a human-readable UTF-8 encoded string. A URL would be - /// sensible. + /// The hash of the reason for the tip. The reason should be a human-readable UTF-8 + /// encoded string. A URL would be sensible. reason: Hash, /// The account to be tipped. who: AccountId, /// The account who began this tip and the amount held on deposit. finder: Option<(AccountId, Balance)>, - /// The block number at which this tip will close if `Some`. If `None`, then no closing is - /// scheduled. + /// The block number at which this tip will close if `Some`. If `None`, then no closing + /// is scheduled. closes: Option, /// The members who have voted for this tip. Sorted by AccountId. tips: Vec<(AccountId, Balance)>, diff --git a/substrate/frame/tips/src/tests.rs b/substrate/frame/tips/src/tests.rs index c357942c54..8611320563 100644 --- a/substrate/frame/tips/src/tests.rs +++ b/substrate/frame/tips/src/tests.rs @@ -412,8 +412,8 @@ fn test_last_reward_migration() { BlockNumber: Parameter, Hash: Parameter, > { - /// The hash of the reason for the tip. The reason should be a human-readable UTF-8 encoded string. A URL would be - /// sensible. + /// The hash of the reason for the tip. The reason should be a human-readable UTF-8 encoded + /// string. A URL would be sensible. reason: Hash, /// The account to be tipped. who: AccountId, diff --git a/substrate/frame/transaction-payment/src/lib.rs b/substrate/frame/transaction-payment/src/lib.rs index 36bfd31a67..9e8dbf6cb5 100644 --- a/substrate/frame/transaction-payment/src/lib.rs +++ b/substrate/frame/transaction-payment/src/lib.rs @@ -117,8 +117,8 @@ type BalanceOf = <::OnChargeTransaction as OnChargeTransaction= v * k * (1 - s')`. /// - in an empty chain: `p >= v * k * (-s')`. /// -/// For example, when all blocks are full and there are 28800 blocks per day (default in `substrate-node`) -/// and v == 0.00001, s' == 0.1875, we'd have: +/// For example, when all blocks are full and there are 28800 blocks per day (default in +/// `substrate-node`) and v == 0.00001, s' == 0.1875, we'd have: /// /// p >= 0.00001 * 28800 * 0.8125 /// p >= 0.234 diff --git a/substrate/frame/transaction-payment/src/types.rs b/substrate/frame/transaction-payment/src/types.rs index 345bd39718..3ce5bcf890 100644 --- a/substrate/frame/transaction-payment/src/types.rs +++ b/substrate/frame/transaction-payment/src/types.rs @@ -36,8 +36,9 @@ pub struct InclusionFee { pub base_fee: Balance, /// The length fee, the amount paid for the encoded length (in bytes) of the transaction. pub len_fee: Balance, - /// - `targeted_fee_adjustment`: This is a multiplier that can tune the final fee based on - /// the congestion of the network. + /// + /// - `targeted_fee_adjustment`: This is a multiplier that can tune the final fee based on the + /// congestion of the network. /// - `weight_fee`: This amount is computed based on the weight of the transaction. Weight /// accounts for the execution time of a transaction. /// @@ -60,8 +61,8 @@ impl InclusionFee { /// The `FeeDetails` is composed of: /// - (Optional) `inclusion_fee`: Only the `Pays::Yes` transaction can have the inclusion fee. -/// - `tip`: If included in the transaction, the tip will be added on top. Only -/// signed transactions can have a tip. +/// - `tip`: If included in the transaction, the tip will be added on top. Only signed +/// transactions can have a tip. #[derive(Encode, Decode, Clone, Eq, PartialEq)] #[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize))] #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] @@ -88,7 +89,8 @@ impl FeeDetails { } } -/// Information related to a dispatchable's class, weight, and fee that can be queried from the runtime. +/// Information related to a dispatchable's class, weight, and fee that can be queried from the +/// runtime. #[derive(Eq, PartialEq, Encode, Decode, Default)] #[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize))] #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] diff --git a/substrate/frame/transaction-storage/src/lib.rs b/substrate/frame/transaction-storage/src/lib.rs index 3964f42998..1b751f3b21 100644 --- a/substrate/frame/transaction-storage/src/lib.rs +++ b/substrate/frame/transaction-storage/src/lib.rs @@ -169,9 +169,9 @@ pub mod pallet { #[pallet::call] impl Pallet { - /// Index and store data on chain. Minimum data size is 1 bytes, maximum is `MaxTransactionSize`. - /// Data will be removed after `STORAGE_PERIOD` blocks, unless `renew` is called. - /// # + /// Index and store data on chain. Minimum data size is 1 bytes, maximum is + /// `MaxTransactionSize`. Data will be removed after `STORAGE_PERIOD` blocks, unless `renew` + /// is called. # /// - n*log(n) of data size, as all data is pushed to an in-memory trie. /// Additionally contains a DB write. /// # @@ -258,7 +258,8 @@ pub mod pallet { /// Check storage proof for block number `block_number() - StoragePeriod`. /// If such block does not exist the proof is expected to be `None`. /// # - /// - Linear w.r.t the number of indexed transactions in the proved block for random probing. + /// - Linear w.r.t the number of indexed transactions in the proved block for random + /// probing. /// There's a DB read for each transaction. /// Here we assume a maximum of 100 probed transactions. /// # diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index 207d51905a..965f06731c 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -95,15 +95,14 @@ pub type NegativeImbalanceOf = <>::Currency as Currenc /// A trait to allow the Treasury Pallet to spend it's funds for other purposes. /// There is an expectation that the implementer of this trait will correctly manage /// the mutable variables passed to it: -/// * `budget_remaining`: How much available funds that can be spent by the treasury. -/// As funds are spent, you must correctly deduct from this value. -/// * `imbalance`: Any imbalances that you create should be subsumed in here to -/// maximize efficiency of updating the total issuance. (i.e. `deposit_creating`) -/// * `total_weight`: Track any weight that your `spend_fund` implementation uses by -/// updating this value. -/// * `missed_any`: If there were items that you want to spend on, but there were -/// not enough funds, mark this value as `true`. This will prevent the treasury -/// from burning the excess funds. +/// * `budget_remaining`: How much available funds that can be spent by the treasury. As funds are +/// spent, you must correctly deduct from this value. +/// * `imbalance`: Any imbalances that you create should be subsumed in here to maximize efficiency +/// of updating the total issuance. (i.e. `deposit_creating`) +/// * `total_weight`: Track any weight that your `spend_fund` implementation uses by updating this +/// value. +/// * `missed_any`: If there were items that you want to spend on, but there were not enough funds, +/// mark this value as `true`. This will prevent the treasury from burning the excess funds. #[impl_trait_for_tuples::impl_for_tuples(30)] pub trait SpendFunds, I: 'static = ()> { fn spend_funds( @@ -293,8 +292,8 @@ pub mod pallet { /// # /// - Complexity: `O(A)` where `A` is the number of approvals /// - Db reads and writes: `Approvals`, `pot account data` - /// - Db reads and writes per approval: - /// `Proposals`, `proposer account data`, `beneficiary account data` + /// - Db reads and writes per approval: `Proposals`, `proposer account data`, `beneficiary + /// account data` /// - The weight is overestimated if some approvals got missed. /// # fn on_initialize(n: T::BlockNumber) -> Weight { diff --git a/substrate/frame/uniques/src/lib.rs b/substrate/frame/uniques/src/lib.rs index ee052486b0..37855253ff 100644 --- a/substrate/frame/uniques/src/lib.rs +++ b/substrate/frame/uniques/src/lib.rs @@ -413,7 +413,8 @@ pub mod pallet { Self::deposit_event(Event::Destroyed(class)); - // NOTE: could use postinfo to reflect the actual number of accounts/sufficient/approvals + // NOTE: could use postinfo to reflect the actual number of + // accounts/sufficient/approvals Ok(()) }) } diff --git a/substrate/frame/utility/src/lib.rs b/substrate/frame/utility/src/lib.rs index 7c47e81368..2e34502494 100644 --- a/substrate/frame/utility/src/lib.rs +++ b/substrate/frame/utility/src/lib.rs @@ -32,9 +32,9 @@ //! an alternative signed origin. Each account has 2 * 2**16 possible "pseudonyms" (alternative //! account IDs) and these can be stacked. This can be useful as a key management tool, where you //! need multiple distinct accounts (e.g. as controllers for many staking accounts), but where -//! it's perfectly fine to have each of them controlled by the same underlying keypair. -//! Derivative accounts are, for the purposes of proxy filtering considered exactly the same as -//! the origin and are thus hampered with the origin's filters. +//! it's perfectly fine to have each of them controlled by the same underlying keypair. Derivative +//! accounts are, for the purposes of proxy filtering considered exactly the same as the origin +//! and are thus hampered with the origin's filters. //! //! Since proxy filters are respected in all dispatches of this pallet, it should never need to be //! filtered by any proxy. diff --git a/substrate/frame/utility/src/tests.rs b/substrate/frame/utility/src/tests.rs index 7679df944e..2731b6ca0b 100644 --- a/substrate/frame/utility/src/tests.rs +++ b/substrate/frame/utility/src/tests.rs @@ -579,7 +579,8 @@ fn batch_all_does_not_nest() { ); // And for those who want to get a little fancy, we check that the filter persists across - // other kinds of dispatch wrapping functions... in this case `batch_all(batch(batch_all(..)))` + // other kinds of dispatch wrapping functions... in this case + // `batch_all(batch(batch_all(..)))` let batch_nested = Call::Utility(UtilityCall::batch(vec![batch_all])); // Batch will end with `Ok`, but does not actually execute as we can see from the event // and balances. diff --git a/substrate/primitives/api/src/lib.rs b/substrate/primitives/api/src/lib.rs index 0ec1c5aead..82954d193e 100644 --- a/substrate/primitives/api/src/lib.rs +++ b/substrate/primitives/api/src/lib.rs @@ -60,9 +60,10 @@ //! `${TRAIT_NAME}_${FUNCTION_NAME}`. Such a function has the following signature //! `(ptr: *u8, length: u32) -> u64`. It takes a pointer to an `u8` array and its length as an //! argument. This `u8` array is expected to be the SCALE encoded parameters of the function as -//! defined in the trait. The return value is an `u64` that represents `length << 32 | pointer` of an -//! `u8` array. This return value `u8` array contains the SCALE encoded return value as defined by -//! the trait function. The macros take care to encode the parameters and to decode the return value. +//! defined in the trait. The return value is an `u64` that represents `length << 32 | pointer` of +//! an `u8` array. This return value `u8` array contains the SCALE encoded return value as defined +//! by the trait function. The macros take care to encode the parameters and to decode the return +//! value. #![cfg_attr(not(feature = "std"), no_std)] @@ -116,8 +117,9 @@ pub const MAX_EXTRINSIC_DEPTH: u32 = 256; /// on the runtime side. The declaration for the runtime side is hidden in its own module. /// The client side declaration gets two extra parameters per function, /// `&self` and `at: &BlockId`. The runtime side declaration will match the given trait -/// declaration. Besides one exception, the macro adds an extra generic parameter `Block: BlockT` -/// to the client side and the runtime side. This generic parameter is usable by the user. +/// declaration. Besides one exception, the macro adds an extra generic parameter `Block: +/// BlockT` to the client side and the runtime side. This generic parameter is usable by the +/// user. /// /// For implementing these macros you should use the /// [`impl_runtime_apis!`] macro. @@ -149,14 +151,14 @@ pub const MAX_EXTRINSIC_DEPTH: u32 = 256; /// # Runtime api trait versioning /// /// To support versioning of the traits, the macro supports the attribute `#[api_version(1)]`. -/// The attribute supports any `u32` as version. By default, each trait is at version `1`, if no -/// version is provided. We also support changing the signature of a method. This signature -/// change is highlighted with the `#[changed_in(2)]` attribute above a method. A method that is -/// tagged with this attribute is callable by the name `METHOD_before_version_VERSION`. This -/// method will only support calling into wasm, trying to call into native will fail (change the -/// spec version!). Such a method also does not need to be implemented in the runtime. It is -/// required that there exist the "default" of the method without the `#[changed_in(_)]` attribute, -/// this method will be used to call the current default implementation. +/// The attribute supports any `u32` as version. By default, each trait is at version `1`, if +/// no version is provided. We also support changing the signature of a method. This signature +/// change is highlighted with the `#[changed_in(2)]` attribute above a method. A method that +/// is tagged with this attribute is callable by the name `METHOD_before_version_VERSION`. This +/// method will only support calling into wasm, trying to call into native will fail (change +/// the spec version!). Such a method also does not need to be implemented in the runtime. It +/// is required that there exist the "default" of the method without the `#[changed_in(_)]` +/// attribute, this method will be used to call the current default implementation. /// /// ```rust /// sp_api::decl_runtime_apis! { @@ -181,22 +183,23 @@ pub const MAX_EXTRINSIC_DEPTH: u32 = 256; /// ``` /// /// To check if a given runtime implements a runtime api trait, the `RuntimeVersion` has the -/// function `has_api()`. Also the `ApiExt` provides a function `has_api(at: &BlockId)` to -/// check if the runtime at the given block id implements the requested runtime api trait. +/// function `has_api()`. Also the `ApiExt` provides a function `has_api(at: &BlockId)` +/// to check if the runtime at the given block id implements the requested runtime api trait. pub use sp_api_proc_macro::decl_runtime_apis; /// Tags given trait implementations as runtime apis. /// /// All traits given to this macro, need to be declared with the /// [`decl_runtime_apis!`](macro.decl_runtime_apis.html) macro. The implementation of the trait -/// should follow the declaration given to the [`decl_runtime_apis!`](macro.decl_runtime_apis.html) -/// macro, besides the `Block` type that is required as first generic parameter for each runtime -/// api trait. When implementing a runtime api trait, it is required that the trait is referenced -/// by a path, e.g. `impl my_trait::MyTrait for Runtime`. The macro will use this path to access -/// the declaration of the trait for the runtime side. +/// should follow the declaration given to the +/// [`decl_runtime_apis!`](macro.decl_runtime_apis.html) macro, besides the `Block` type that +/// is required as first generic parameter for each runtime api trait. When implementing a +/// runtime api trait, it is required that the trait is referenced by a path, e.g. `impl +/// my_trait::MyTrait for Runtime`. The macro will use this path to access the declaration of +/// the trait for the runtime side. /// -/// The macro also generates the api implementations for the client side and provides it through -/// the `RuntimeApi` type. The `RuntimeApi` is hidden behind a `feature` called `std`. +/// The macro also generates the api implementations for the client side and provides it +/// through the `RuntimeApi` type. The `RuntimeApi` is hidden behind a `feature` called `std`. /// /// To expose version information about all implemented api traits, the constant /// `RUNTIME_API_VERSIONS` is generated. This constant should be used to instantiate the `apis` @@ -275,13 +278,13 @@ pub use sp_api_proc_macro::impl_runtime_apis; /// Mocks given trait implementations as runtime apis. /// /// Accepts similar syntax as [`impl_runtime_apis!`] and generates -/// simplified mock implementations of the given runtime apis. The difference in syntax is that the -/// trait does not need to be referenced by a qualified path, methods accept the `&self` parameter -/// and the error type can be specified as associated type. If no error type is specified [`String`] -/// is used as error type. +/// simplified mock implementations of the given runtime apis. The difference in syntax is that +/// the trait does not need to be referenced by a qualified path, methods accept the `&self` +/// parameter and the error type can be specified as associated type. If no error type is +/// specified [`String`] is used as error type. /// -/// Besides implementing the given traits, the [`Core`](sp_api::Core) and [`ApiExt`](sp_api::ApiExt) -/// are implemented automatically. +/// Besides implementing the given traits, the [`Core`](sp_api::Core) and +/// [`ApiExt`](sp_api::ApiExt) are implemented automatically. /// /// # Example /// @@ -329,14 +332,15 @@ pub use sp_api_proc_macro::impl_runtime_apis; /// /// # `advanced` attribute /// -/// This attribute can be placed above individual function in the mock implementation to request -/// more control over the function declaration. From the client side each runtime api function is -/// called with the `at` parameter that is a [`BlockId`](sp_api::BlockId). When using the `advanced` -/// attribute, the macro expects that the first parameter of the function is this `at` parameter. -/// Besides that the macro also doesn't do the automatic return value rewrite, which means that full -/// return value must be specified. The full return value is constructed like -/// [`Result`]`<`[`NativeOrEncoded`](sp_api::NativeOrEncoded)`, Error>` while -/// `ReturnValue` being the return value that is specified in the trait declaration. +/// This attribute can be placed above individual function in the mock implementation to +/// request more control over the function declaration. From the client side each runtime api +/// function is called with the `at` parameter that is a [`BlockId`](sp_api::BlockId). When +/// using the `advanced` attribute, the macro expects that the first parameter of the function +/// is this `at` parameter. Besides that the macro also doesn't do the automatic return value +/// rewrite, which means that full return value must be specified. The full return value is +/// constructed like [`Result`]`<`[`NativeOrEncoded`](sp_api::NativeOrEncoded)`, +/// Error>` while `ReturnValue` being the return value that is specified in the trait +/// declaration. /// /// ## Example /// ```rust diff --git a/substrate/primitives/arithmetic/fuzzer/src/multiply_by_rational.rs b/substrate/primitives/arithmetic/fuzzer/src/multiply_by_rational.rs index d829a93ad4..3089d4b092 100644 --- a/substrate/primitives/arithmetic/fuzzer/src/multiply_by_rational.rs +++ b/substrate/primitives/arithmetic/fuzzer/src/multiply_by_rational.rs @@ -16,8 +16,8 @@ // limitations under the License. //! # Running -//! Running this fuzzer can be done with `cargo hfuzz run multiply_by_rational`. `honggfuzz` CLI options can -//! be used by setting `HFUZZ_RUN_ARGS`, such as `-n 4` to use 4 threads. +//! Running this fuzzer can be done with `cargo hfuzz run multiply_by_rational`. `honggfuzz` CLI +//! options can be used by setting `HFUZZ_RUN_ARGS`, such as `-n 4` to use 4 threads. //! //! # Debugging a panic //! Once a panic is found, it can be debugged with diff --git a/substrate/primitives/arithmetic/fuzzer/src/per_thing_rational.rs b/substrate/primitives/arithmetic/fuzzer/src/per_thing_rational.rs index c7f6a14c5f..7b90faa940 100644 --- a/substrate/primitives/arithmetic/fuzzer/src/per_thing_rational.rs +++ b/substrate/primitives/arithmetic/fuzzer/src/per_thing_rational.rs @@ -16,8 +16,8 @@ // limitations under the License. //! # Running -//! Running this fuzzer can be done with `cargo hfuzz run per_thing_rational`. `honggfuzz` CLI options can -//! be used by setting `HFUZZ_RUN_ARGS`, such as `-n 4` to use 4 threads. +//! Running this fuzzer can be done with `cargo hfuzz run per_thing_rational`. `honggfuzz` CLI +//! options can be used by setting `HFUZZ_RUN_ARGS`, such as `-n 4` to use 4 threads. //! //! # Debugging a panic //! Once a panic is found, it can be debugged with diff --git a/substrate/primitives/arithmetic/src/helpers_128bit.rs b/substrate/primitives/arithmetic/src/helpers_128bit.rs index 8784136c80..bbf69ea359 100644 --- a/substrate/primitives/arithmetic/src/helpers_128bit.rs +++ b/substrate/primitives/arithmetic/src/helpers_128bit.rs @@ -62,8 +62,8 @@ pub fn to_big_uint(x: u128) -> biguint::BigUint { /// Safely and accurately compute `a * b / c`. The approach is: /// - Simply try `a * b / c`. -/// - Else, convert them both into big numbers and re-try. `Err` is returned if the result -/// cannot be safely casted back to u128. +/// - Else, convert them both into big numbers and re-try. `Err` is returned if the result cannot +/// be safely casted back to u128. /// /// Invariant: c must be greater than or equal to 1. pub fn multiply_by_rational(mut a: u128, mut b: u128, mut c: u128) -> Result { diff --git a/substrate/primitives/blockchain/src/backend.rs b/substrate/primitives/blockchain/src/backend.rs index fb0ef5b4d7..bb34a0449b 100644 --- a/substrate/primitives/blockchain/src/backend.rs +++ b/substrate/primitives/blockchain/src/backend.rs @@ -69,14 +69,16 @@ pub trait HeaderBackend: Send + Sync { .ok_or_else(|| Error::UnknownBlock(format!("Expect header: {}", id))) } - /// Convert an arbitrary block ID into a block number. Returns `UnknownBlock` error if block is not found. + /// Convert an arbitrary block ID into a block number. Returns `UnknownBlock` error if block is + /// not found. fn expect_block_number_from_id(&self, id: &BlockId) -> Result> { self.block_number_from_id(id).and_then(|n| { n.ok_or_else(|| Error::UnknownBlock(format!("Expect block number from id: {}", id))) }) } - /// Convert an arbitrary block ID into a block hash. Returns `UnknownBlock` error if block is not found. + /// Convert an arbitrary block ID into a block hash. Returns `UnknownBlock` error if block is + /// not found. fn expect_block_hash_from_id(&self, id: &BlockId) -> Result { self.block_hash_from_id(id).and_then(|n| { n.ok_or_else(|| Error::UnknownBlock(format!("Expect block hash from id: {}", id))) diff --git a/substrate/primitives/consensus/common/src/block_validation.rs b/substrate/primitives/consensus/common/src/block_validation.rs index 9a9f21394f..54a70a402b 100644 --- a/substrate/primitives/consensus/common/src/block_validation.rs +++ b/substrate/primitives/consensus/common/src/block_validation.rs @@ -60,9 +60,9 @@ pub trait BlockAnnounceValidator { /// Returning [`Validation::Failure`] will lead to a decrease of the /// peers reputation as it sent us invalid data. /// - /// The returned future should only resolve to an error iff there was an internal error validating - /// the block announcement. If the block announcement itself is invalid, this should *always* - /// return [`Validation::Failure`]. + /// The returned future should only resolve to an error iff there was an internal error + /// validating the block announcement. If the block announcement itself is invalid, this should + /// *always* return [`Validation::Failure`]. fn validate( &mut self, header: &B::Header, diff --git a/substrate/primitives/core/src/crypto.rs b/substrate/primitives/core/src/crypto.rs index a9f4195684..5346ea66fe 100644 --- a/substrate/primitives/core/src/crypto.rs +++ b/substrate/primitives/core/src/crypto.rs @@ -255,8 +255,8 @@ pub trait Ss58Codec: Sized + AsMut<[u8]> + AsRef<[u8]> + Default { let (prefix_len, ident) = match data[0] { 0..=63 => (1, data[0] as u16), 64..=127 => { - // weird bit manipulation owing to the combination of LE encoding and missing two bits - // from the left. + // weird bit manipulation owing to the combination of LE encoding and missing two + // bits from the left. // d[0] d[1] are: 01aaaaaa bbcccccc // they make the LE-encoded 16-bit value: aaaaaabb 00cccccc // so the lower byte is formed of aaaaaabb and the higher byte is 00cccccc @@ -1029,9 +1029,9 @@ pub trait Pair: CryptoType + Sized + Clone + Send + Sync + 'static { /// Get the public key. fn public(&self) -> Self::Public; - /// Interprets the string `s` in order to generate a key Pair. Returns both the pair and an optional seed, in the - /// case that the pair can be expressed as a direct derivation from a seed (some cases, such as Sr25519 derivations - /// with path components, cannot). + /// Interprets the string `s` in order to generate a key Pair. Returns both the pair and an + /// optional seed, in the case that the pair can be expressed as a direct derivation from a seed + /// (some cases, such as Sr25519 derivations with path components, cannot). /// /// This takes a helper function to do the key generation from a phrase, password and /// junction iterator. @@ -1043,7 +1043,8 @@ pub trait Pair: CryptoType + Sized + Clone + Send + Sync + 'static { /// - the phrase may be followed by one or more items delimited by `/` characters. /// - the path may be followed by `///`, in which case everything after the `///` is treated /// as a password. - /// - If `s` begins with a `/` character it is prefixed with the Substrate public `DEV_PHRASE` and + /// - If `s` begins with a `/` character it is prefixed with the Substrate public `DEV_PHRASE` + /// and /// interpreted as above. /// /// In this case they are interpreted as HDKD junctions; purely numeric items are interpreted as @@ -1053,8 +1054,8 @@ pub trait Pair: CryptoType + Sized + Clone + Send + Sync + 'static { /// There is no correspondence mapping between SURI strings and the keys they represent. /// Two different non-identical strings can actually lead to the same secret being derived. /// Notably, integer junction indices may be legally prefixed with arbitrary number of zeros. - /// Similarly an empty password (ending the SURI with `///`) is perfectly valid and will generally - /// be equivalent to no password at all. + /// Similarly an empty password (ending the SURI with `///`) is perfectly valid and will + /// generally be equivalent to no password at all. /// /// `None` is returned if no matches are found. #[cfg(feature = "std")] diff --git a/substrate/primitives/core/src/lib.rs b/substrate/primitives/core/src/lib.rs index 83a7518358..0a61c90d71 100644 --- a/substrate/primitives/core/src/lib.rs +++ b/substrate/primitives/core/src/lib.rs @@ -118,7 +118,8 @@ impl ExecutionContext { match self { Importing | Syncing | BlockConstruction => offchain::Capabilities::none(), - // Enable keystore, transaction pool and Offchain DB reads by default for offchain calls. + // Enable keystore, transaction pool and Offchain DB reads by default for offchain + // calls. OffchainCall(None) => [ offchain::Capability::Keystore, offchain::Capability::OffchainDbRead, diff --git a/substrate/primitives/core/src/offchain/mod.rs b/substrate/primitives/core/src/offchain/mod.rs index d4e27fc643..59c92f540b 100644 --- a/substrate/primitives/core/src/offchain/mod.rs +++ b/substrate/primitives/core/src/offchain/mod.rs @@ -344,8 +344,8 @@ pub trait Externalities: Send { /// Initiates a http request given HTTP verb and the URL. /// - /// Meta is a future-reserved field containing additional, parity-scale-codec encoded parameters. - /// Returns the id of newly started request. + /// Meta is a future-reserved field containing additional, parity-scale-codec encoded + /// parameters. Returns the id of newly started request. /// /// Returns an error if: /// - No new request identifier could be allocated. @@ -388,8 +388,8 @@ pub trait Externalities: Send { /// - The request identifier is invalid. /// - `http_response_wait` has already been called on this request. /// - The deadline is reached. - /// - An I/O error has happened, for example the remote has closed our - /// request. The request is then considered invalid. + /// - An I/O error has happened, for example the remote has closed our request. The request is + /// then considered invalid. fn http_request_write_body( &mut self, request_id: HttpRequestId, @@ -440,8 +440,8 @@ pub trait Externalities: Send { /// Returns an error if: /// - The request identifier is invalid. /// - The deadline is reached. - /// - An I/O error has happened, for example the remote has closed our - /// request. The request is then considered invalid. + /// - An I/O error has happened, for example the remote has closed our request. The request is + /// then considered invalid. fn http_response_read_body( &mut self, request_id: HttpRequestId, diff --git a/substrate/primitives/core/src/offchain/testing.rs b/substrate/primitives/core/src/offchain/testing.rs index 3015091831..5a9996af9a 100644 --- a/substrate/primitives/core/src/offchain/testing.rs +++ b/substrate/primitives/core/src/offchain/testing.rs @@ -168,8 +168,8 @@ impl OffchainState { /// Add expected HTTP request. /// /// This method can be used to initialize expected HTTP requests and their responses - /// before running the actual code that utilizes them (for instance before calling into runtime). - /// Expected request has to be fulfilled before this struct is dropped, + /// before running the actual code that utilizes them (for instance before calling into + /// runtime). Expected request has to be fulfilled before this struct is dropped, /// the `response` and `response_headers` fields will be used to return results to the callers. /// Requests are expected to be performed in the insertion order. pub fn expect_request(&mut self, expected: PendingRequest) { diff --git a/substrate/primitives/core/src/sr25519.rs b/substrate/primitives/core/src/sr25519.rs index 7e98bee96d..4c5122162d 100644 --- a/substrate/primitives/core/src/sr25519.rs +++ b/substrate/primitives/core/src/sr25519.rs @@ -870,7 +870,8 @@ mod test { #[test] fn verify_from_old_wasm_works() { - // The values in this test case are compared to the output of `node-test.js` in schnorrkel-js. + // The values in this test case are compared to the output of `node-test.js` in + // schnorrkel-js. // // This is to make sure that the wasm library is compatible. let pk = Pair::from_seed(&hex!( diff --git a/substrate/primitives/core/src/traits.rs b/substrate/primitives/core/src/traits.rs index dfa61f606c..47639f9d87 100644 --- a/substrate/primitives/core/src/traits.rs +++ b/substrate/primitives/core/src/traits.rs @@ -126,13 +126,13 @@ pub trait ReadRuntimeVersion: Send + Sync { /// The version information may be embedded into the wasm binary itself. If it is not present, /// then this function may fallback to the legacy way of reading the version. /// - /// The legacy mechanism involves instantiating the passed wasm runtime and calling `Core_version` - /// on it. This is a very expensive operation. + /// The legacy mechanism involves instantiating the passed wasm runtime and calling + /// `Core_version` on it. This is a very expensive operation. /// /// `ext` is only needed in case the calling into runtime happens. Otherwise it is ignored. /// - /// Compressed wasm blobs are supported and will be decompressed if needed. If uncompression fails, - /// the error is returned. + /// Compressed wasm blobs are supported and will be decompressed if needed. If uncompression + /// fails, the error is returned. /// /// # Errors /// diff --git a/substrate/primitives/externalities/src/extensions.rs b/substrate/primitives/externalities/src/extensions.rs index 55b69fde08..37086a707b 100644 --- a/substrate/primitives/externalities/src/extensions.rs +++ b/substrate/primitives/externalities/src/extensions.rs @@ -30,7 +30,8 @@ use sp_std::{ ops::DerefMut, }; -/// Marker trait for types that should be registered as [`Externalities`](crate::Externalities) extension. +/// Marker trait for types that should be registered as [`Externalities`](crate::Externalities) +/// extension. /// /// As extensions are stored as `Box`, this trait should give more confidence that the correct /// type is registered and requested. @@ -95,7 +96,8 @@ macro_rules! decl_extension { /// /// This is a super trait of the [`Externalities`](crate::Externalities). pub trait ExtensionStore { - /// Tries to find a registered extension by the given `type_id` and returns it as a `&mut dyn Any`. + /// Tries to find a registered extension by the given `type_id` and returns it as a `&mut dyn + /// Any`. /// /// It is advised to use [`ExternalitiesExt::extension`](crate::ExternalitiesExt::extension) /// instead of this function to get type system support and automatic type downcasting. diff --git a/substrate/primitives/externalities/src/lib.rs b/substrate/primitives/externalities/src/lib.rs index b0ec16213b..e6a8f8caa8 100644 --- a/substrate/primitives/externalities/src/lib.rs +++ b/substrate/primitives/externalities/src/lib.rs @@ -94,7 +94,8 @@ pub trait Externalities: ExtensionStore { self.place_storage(key.to_vec(), None); } - /// Clear a child storage entry (`key`) of current contract being called (effective immediately). + /// Clear a child storage entry (`key`) of current contract being called (effective + /// immediately). fn clear_child_storage(&mut self, child_info: &ChildInfo, key: &[u8]) { self.place_child_storage(child_info, key.to_vec(), None) } @@ -144,7 +145,8 @@ pub trait Externalities: ExtensionStore { limit: Option, ) -> (bool, u32); - /// Set or clear a storage entry (`key`) of current contract being called (effective immediately). + /// Set or clear a storage entry (`key`) of current contract being called (effective + /// immediately). fn place_storage(&mut self, key: Vec, value: Option>); /// Set or clear a child storage entry. @@ -167,7 +169,8 @@ pub trait Externalities: ExtensionStore { /// Append storage item. /// - /// This assumes specific format of the storage item. Also there is no way to undo this operation. + /// This assumes specific format of the storage item. Also there is no way to undo this + /// operation. fn storage_append(&mut self, key: Vec, value: Vec); /// Get the changes trie root of the current storage overlay at a block with given `parent`. diff --git a/substrate/primitives/externalities/src/scope_limited.rs b/substrate/primitives/externalities/src/scope_limited.rs index ab8be1f3fc..15a670a9ab 100644 --- a/substrate/primitives/externalities/src/scope_limited.rs +++ b/substrate/primitives/externalities/src/scope_limited.rs @@ -21,9 +21,9 @@ use crate::Externalities; environmental::environmental!(ext: trait Externalities); -/// Set the given externalities while executing the given closure. To get access to the externalities -/// while executing the given closure [`with_externalities`] grants access to them. The externalities -/// are only set for the same thread this function was called from. +/// Set the given externalities while executing the given closure. To get access to the +/// externalities while executing the given closure [`with_externalities`] grants access to them. +/// The externalities are only set for the same thread this function was called from. pub fn set_and_run_with_externalities(ext: &mut dyn Externalities, f: F) -> R where F: FnOnce() -> R, diff --git a/substrate/primitives/inherents/src/lib.rs b/substrate/primitives/inherents/src/lib.rs index a2b533641b..90f4e455a4 100644 --- a/substrate/primitives/inherents/src/lib.rs +++ b/substrate/primitives/inherents/src/lib.rs @@ -21,8 +21,8 @@ //! runtime implementation to require an inherent for each block or to make it optional. Inherents //! are mainly used to pass data from the block producer to the runtime. So, inherents require some //! part that is running on the client side and some part that is running on the runtime side. Any -//! data that is required by an inherent is passed as [`InherentData`] from the client to the runtime -//! when the inherents are constructed. +//! data that is required by an inherent is passed as [`InherentData`] from the client to the +//! runtime when the inherents are constructed. //! //! The process of constructing and applying inherents is the following: //! diff --git a/substrate/primitives/io/src/lib.rs b/substrate/primitives/io/src/lib.rs index 8ecbd17220..0b5c37af5f 100644 --- a/substrate/primitives/io/src/lib.rs +++ b/substrate/primitives/io/src/lib.rs @@ -258,8 +258,8 @@ pub trait Storage { pub trait DefaultChildStorage { /// Get a default child storage value for a given key. /// - /// Parameter `storage_key` is the unprefixed location of the root of the child trie in the parent trie. - /// Result is `None` if the value for `key` in the child storage can not be found. + /// Parameter `storage_key` is the unprefixed location of the root of the child trie in the + /// parent trie. Result is `None` if the value for `key` in the child storage can not be found. fn get(&self, storage_key: &[u8], key: &[u8]) -> Option> { let child_info = ChildInfo::new_default(storage_key); self.child_storage(&child_info, key).map(|s| s.to_vec()) @@ -435,11 +435,12 @@ pub trait Trie { } } -/// Interface that provides miscellaneous functions for communicating between the runtime and the node. +/// Interface that provides miscellaneous functions for communicating between the runtime and the +/// node. #[runtime_interface] pub trait Misc { - // NOTE: We use the target 'runtime' for messages produced by general printing functions, instead - // of LOG_TARGET. + // NOTE: We use the target 'runtime' for messages produced by general printing functions, + // instead of LOG_TARGET. /// Print a number. fn print_num(val: u64) { @@ -466,8 +467,8 @@ pub trait Misc { /// # Performance /// /// This function may be very expensive to call depending on the wasm binary. It may be - /// relatively cheap if the wasm binary contains version information. In that case, uncompression - /// of the wasm blob is the dominating factor. + /// relatively cheap if the wasm binary contains version information. In that case, + /// uncompression of the wasm blob is the dominating factor. /// /// If the wasm binary does not have the version information attached, then a legacy mechanism /// may be involved. This means that a runtime call will be performed to query the version. @@ -986,8 +987,8 @@ pub trait Offchain { /// Initiates a http request given HTTP verb and the URL. /// - /// Meta is a future-reserved field containing additional, parity-scale-codec encoded parameters. - /// Returns the id of newly started request. + /// Meta is a future-reserved field containing additional, parity-scale-codec encoded + /// parameters. Returns the id of newly started request. fn http_request_start( &mut self, method: &str, @@ -1149,13 +1150,14 @@ where #[runtime_interface(wasm_only, no_tracing)] pub trait WasmTracing { /// Whether the span described in `WasmMetadata` should be traced wasm-side - /// On the host converts into a static Metadata and checks against the global `tracing` dispatcher. + /// On the host converts into a static Metadata and checks against the global `tracing` + /// dispatcher. /// /// When returning false the calling code should skip any tracing-related execution. In general /// within the same block execution this is not expected to change and it doesn't have to be /// checked more than once per metadata. This exists for optimisation purposes but is still not - /// cheap as it will jump the wasm-native-barrier every time it is called. So an implementation might - /// chose to cache the result for the execution of the entire block. + /// cheap as it will jump the wasm-native-barrier every time it is called. So an implementation + /// might chose to cache the result for the execution of the entire block. fn enabled(&mut self, metadata: Crossing) -> bool { let metadata: &tracing_core::metadata::Metadata<'static> = (&metadata.into_inner()).into(); tracing::dispatcher::get_default(|d| d.enabled(metadata)) diff --git a/substrate/primitives/npos-elections/fuzzer/src/compact.rs b/substrate/primitives/npos-elections/fuzzer/src/compact.rs index b171765e78..4e78c94b82 100644 --- a/substrate/primitives/npos-elections/fuzzer/src/compact.rs +++ b/substrate/primitives/npos-elections/fuzzer/src/compact.rs @@ -12,18 +12,20 @@ fn main() { fuzz!(|fuzzer_data: &[u8]| { let result_decoded: Result = ::decode(&mut &fuzzer_data[..]); - // Ignore errors as not every random sequence of bytes can be decoded as InnerTestSolutionCompact + // Ignore errors as not every random sequence of bytes can be decoded as + // InnerTestSolutionCompact if let Ok(decoded) = result_decoded { // Decoding works, let's re-encode it and compare results. let reencoded: std::vec::Vec = decoded.encode(); - // The reencoded value may or may not be equal to the original fuzzer output. However, the - // original decoder should be optimal (in the sense that there is no shorter encoding of - // the same object). So let's see if the fuzzer can find something shorter: + // The reencoded value may or may not be equal to the original fuzzer output. + // However, the original decoder should be optimal (in the sense that there is no + // shorter encoding of the same object). So let's see if the fuzzer can find + // something shorter: if fuzzer_data.len() < reencoded.len() { panic!("fuzzer_data.len() < reencoded.len()"); } - // The reencoded value should definitely be decodable (if unwrap() fails that is a valid - // panic/finding for the fuzzer): + // The reencoded value should definitely be decodable (if unwrap() fails that is a + // valid panic/finding for the fuzzer): let decoded2: InnerTestSolutionCompact = ::decode(&mut reencoded.as_slice()) .unwrap(); diff --git a/substrate/primitives/npos-elections/fuzzer/src/phragmen_balancing.rs b/substrate/primitives/npos-elections/fuzzer/src/phragmen_balancing.rs index 04ff60683f..5da57ccfd9 100644 --- a/substrate/primitives/npos-elections/fuzzer/src/phragmen_balancing.rs +++ b/substrate/primitives/npos-elections/fuzzer/src/phragmen_balancing.rs @@ -94,8 +94,8 @@ fn main() { iterations, unbalanced_score, balanced_score, enhance, ); - // The only guarantee of balancing is such that the first and third element of the score - // cannot decrease. + // The only guarantee of balancing is such that the first and third element of the + // score cannot decrease. assert!( balanced_score[0] >= unbalanced_score[0] && balanced_score[1] == unbalanced_score[1] && diff --git a/substrate/primitives/npos-elections/fuzzer/src/phragmen_pjr.rs b/substrate/primitives/npos-elections/fuzzer/src/phragmen_pjr.rs index 6efc17f24f..f1110da8ef 100644 --- a/substrate/primitives/npos-elections/fuzzer/src/phragmen_pjr.rs +++ b/substrate/primitives/npos-elections/fuzzer/src/phragmen_pjr.rs @@ -21,17 +21,17 @@ //! ## Running a single iteration //! //! Honggfuzz shuts down each individual loop iteration after a configurable time limit. -//! It can be helpful to run a single iteration on your hardware to help benchmark how long that time -//! limit should reasonably be. Simply run the program without the `fuzzing` configuration to run a -//! single iteration: `cargo run --bin phragmen_pjr`. +//! It can be helpful to run a single iteration on your hardware to help benchmark how long that +//! time limit should reasonably be. Simply run the program without the `fuzzing` configuration to +//! run a single iteration: `cargo run --bin phragmen_pjr`. //! //! ## Running //! //! Run with `HFUZZ_RUN_ARGS="-t 10" cargo hfuzz run phragmen_pjr`. //! -//! Note the environment variable: by default, `cargo hfuzz` shuts down each iteration after 1 second -//! of runtime. We significantly increase that to ensure that the fuzzing gets a chance to complete. -//! Running a single iteration can help determine an appropriate value for this parameter. +//! Note the environment variable: by default, `cargo hfuzz` shuts down each iteration after 1 +//! second of runtime. We significantly increase that to ensure that the fuzzing gets a chance to +//! complete. Running a single iteration can help determine an appropriate value for this parameter. //! //! ## Debugging a panic //! diff --git a/substrate/primitives/npos-elections/src/mock.rs b/substrate/primitives/npos-elections/src/mock.rs index 1be591e4ea..8de0c09959 100644 --- a/substrate/primitives/npos-elections/src/mock.rs +++ b/substrate/primitives/npos-elections/src/mock.rs @@ -406,7 +406,8 @@ pub(crate) fn build_support_map_float( supports } -/// Generate voter and assignment lists. Makes no attempt to be realistic about winner or assignment fairness. +/// Generate voter and assignment lists. Makes no attempt to be realistic about winner or assignment +/// fairness. /// /// Maintains these invariants: /// diff --git a/substrate/primitives/npos-elections/src/phragmms.rs b/substrate/primitives/npos-elections/src/phragmms.rs index 95551d9761..4e7316d577 100644 --- a/substrate/primitives/npos-elections/src/phragmms.rs +++ b/substrate/primitives/npos-elections/src/phragmms.rs @@ -237,7 +237,8 @@ mod tests { #[test] fn basic_election_manual_works() { //! Manually run the internal steps of phragmms. In each round we select a new winner by - //! `max_score`, then apply this change by `apply_elected`, and finally do a `balance` round. + //! `max_score`, then apply this change by `apply_elected`, and finally do a `balance` + //! round. let candidates = vec![1, 2, 3]; let voters = vec![(10, 10, vec![1, 2]), (20, 20, vec![1, 3]), (30, 30, vec![2, 3])]; diff --git a/substrate/primitives/npos-elections/src/pjr.rs b/substrate/primitives/npos-elections/src/pjr.rs index 3cc99b33aa..e27acf1408 100644 --- a/substrate/primitives/npos-elections/src/pjr.rs +++ b/substrate/primitives/npos-elections/src/pjr.rs @@ -35,9 +35,9 @@ type Threshold = ExtendedBalance; /// Compute the threshold corresponding to the standard PJR property /// -/// `t-PJR` checks can check PJR according to an arbitrary threshold. The threshold can be any value, -/// but the property gets stronger as the threshold gets smaller. The strongest possible `t-PJR` property -/// corresponds to `t == 0`. +/// `t-PJR` checks can check PJR according to an arbitrary threshold. The threshold can be any +/// value, but the property gets stronger as the threshold gets smaller. The strongest possible +/// `t-PJR` property corresponds to `t == 0`. /// /// However, standard PJR is less stringent than that. This function returns the threshold whose /// strength corresponds to the standard PJR property. @@ -74,13 +74,13 @@ pub fn pjr_check( /// /// ### Semantics /// -/// The t-PJR property is defined in the paper ["Validator Election in Nominated Proof-of-Stake"][NPoS], -/// section 5, definition 1. +/// The t-PJR property is defined in the paper ["Validator Election in Nominated +/// Proof-of-Stake"][NPoS], section 5, definition 1. /// /// In plain language, the t-PJR condition is: if there is a group of `N` voters /// who have `r` common candidates and can afford to support each of them with backing stake `t` -/// (i.e `sum(stake(v) for v in voters) == r * t`), then this committee needs to be represented by at -/// least `r` elected candidates. +/// (i.e `sum(stake(v) for v in voters) == r * t`), then this committee needs to be represented by +/// at least `r` elected candidates. /// /// Section 5 of the NPoS paper shows that this property can be tested by: for a feasible solution, /// if `Max {score(c)} < t` where c is every unelected candidate, then this solution is t-PJR. There @@ -120,8 +120,8 @@ pub fn t_pjr_check( /// /// [`pjr_check`] or [`t_pjr_check`] are typically easier to work with. /// -/// This function returns an `AccountId` in the `Err` case. This is the counter_example: the ID of the -/// unelected candidate with the highest prescore, such that `pre_score(counter_example) >= t`. +/// This function returns an `AccountId` in the `Err` case. This is the counter_example: the ID of +/// the unelected candidate with the highest prescore, such that `pre_score(counter_example) >= t`. pub fn pjr_check_core( candidates: &[CandidatePtr], voters: &[Voter], @@ -141,8 +141,8 @@ pub fn pjr_check_core( /// Validate a challenge to an election result. /// /// A challenge to an election result is valid if there exists some counter_example for which -/// `pre_score(counter_example) >= threshold`. Validating an existing counter_example is computationally -/// cheaper than re-running the PJR check. +/// `pre_score(counter_example) >= threshold`. Validating an existing counter_example is +/// computationally cheaper than re-running the PJR check. /// /// This function uses the standard threshold. /// @@ -164,8 +164,8 @@ pub fn validate_pjr_challenge( /// Validate a challenge to an election result. /// /// A challenge to an election result is valid if there exists some counter_example for which -/// `pre_score(counter_example) >= threshold`. Validating an existing counter_example is computationally -/// cheaper than re-running the PJR check. +/// `pre_score(counter_example) >= threshold`. Validating an existing counter_example is +/// computationally cheaper than re-running the PJR check. /// /// This function uses a supplied threshold. /// @@ -185,8 +185,8 @@ pub fn validate_t_pjr_challenge( /// Validate a challenge to an election result. /// /// A challenge to an election result is valid if there exists some counter_example for which -/// `pre_score(counter_example) >= threshold`. Validating an existing counter_example is computationally -/// cheaper than re-running the PJR check. +/// `pre_score(counter_example) >= threshold`. Validating an existing counter_example is +/// computationally cheaper than re-running the PJR check. /// /// Returns `true` if the challenge is valid: the proposed solution does not satisfy PJR. /// Returns `false` if the challenge is invalid: the proposed solution does in fact satisfy PJR. @@ -222,8 +222,8 @@ fn validate_pjr_challenge_core( /// /// The ultimate goal, in any case, is to convert the election data into [`Candidate`] and [`Voter`] /// types defined by this crate, whilst setting correct value for some of their fields, namely: -/// 1. Candidate [`backing_stake`](Candidate::backing_stake) and [`elected`](Candidate::elected) if they are a winner. -/// 2. Voter edge [`weight`](Edge::weight) if they are backing a winner. +/// 1. Candidate [`backing_stake`](Candidate::backing_stake) and [`elected`](Candidate::elected) if +/// they are a winner. 2. Voter edge [`weight`](Edge::weight) if they are backing a winner. /// 3. Voter [`budget`](Voter::budget). /// /// None of the `load` or `score` values are used and can be ignored. This is similar to @@ -487,9 +487,9 @@ mod tests { assert_core_failure(&candidates, &voters, 20); } - // These next tests ensure that the threshold phase change property holds for us, but that's not their real purpose. - // They were written to help develop an intuition about what the threshold value actually means - // in layman's terms. + // These next tests ensure that the threshold phase change property holds for us, but that's not + // their real purpose. They were written to help develop an intuition about what the threshold + // value actually means in layman's terms. // // The results tend to support the intuition that the threshold is the voting power at and below // which a voter's preferences can simply be ignored. diff --git a/substrate/primitives/npos-elections/src/reduce.rs b/substrate/primitives/npos-elections/src/reduce.rs index 4290743832..8b90796af8 100644 --- a/substrate/primitives/npos-elections/src/reduce.rs +++ b/substrate/primitives/npos-elections/src/reduce.rs @@ -506,8 +506,8 @@ fn reduce_all(assignments: &mut Vec>) -> u32 }; if next_value.is_zero() { - // if the removed edge is from the current assignment, dis_index - // should NOT be increased. + // if the removed edge is from the current assignment, + // index should NOT be increased. if target_ass_index == assignment_index { should_inc_counter = false } @@ -551,8 +551,8 @@ fn reduce_all(assignments: &mut Vec>) -> u32 }; if next_value.is_zero() { - // if the removed edge is from the current assignment, dis_index - // should NOT be increased. + // if the removed edge is from the current assignment, + // index should NOT be increased. if target_ass_index == assignment_index { should_inc_counter = false } diff --git a/substrate/primitives/panic-handler/src/lib.rs b/substrate/primitives/panic-handler/src/lib.rs index 1c72f22407..75b057cebf 100644 --- a/substrate/primitives/panic-handler/src/lib.rs +++ b/substrate/primitives/panic-handler/src/lib.rs @@ -112,7 +112,8 @@ impl AbortGuard { } /// Create a new guard. While the guard is alive, panics that happen in the current thread will - /// **never** abort the process (even if `AbortGuard::force_abort()` guard will be created afterwards). + /// **never** abort the process (even if `AbortGuard::force_abort()` guard will be created + /// afterwards). pub fn never_abort() -> AbortGuard { AbortGuard { previous_val: set_abort(OnPanic::NeverAbort), _not_send: PhantomData } } diff --git a/substrate/primitives/runtime-interface/proc-macro/src/lib.rs b/substrate/primitives/runtime-interface/proc-macro/src/lib.rs index 502130f1b4..6b0669a298 100644 --- a/substrate/primitives/runtime-interface/proc-macro/src/lib.rs +++ b/substrate/primitives/runtime-interface/proc-macro/src/lib.rs @@ -22,9 +22,10 @@ //! //! 1. The [`#[runtime_interface]`](attr.runtime_interface.html) attribute macro for generating the //! runtime interfaces. -//! 2. The [`PassByCodec`](derive.PassByCodec.html) derive macro for implementing `PassBy` with `Codec`. -//! 3. The [`PassByEnum`](derive.PassByInner.html) derive macro for implementing `PassBy` with `Enum`. -//! 4. The [`PassByInner`](derive.PassByInner.html) derive macro for implementing `PassBy` with `Inner`. +//! 2. The [`PassByCodec`](derive.PassByCodec.html) derive macro for implementing `PassBy` with +//! `Codec`. 3. The [`PassByEnum`](derive.PassByInner.html) derive macro for implementing `PassBy` +//! with `Enum`. 4. The [`PassByInner`](derive.PassByInner.html) derive macro for implementing +//! `PassBy` with `Inner`. use syn::{ parse::{Parse, ParseStream}, diff --git a/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/host_function_interface.rs b/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/host_function_interface.rs index ab84c04e3a..75498c09c1 100644 --- a/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/host_function_interface.rs +++ b/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/host_function_interface.rs @@ -184,8 +184,8 @@ fn generate_host_functions_struct( }) } -/// Generates the host function struct that implements `wasm_interface::Function` and returns a static -/// reference to this struct. +/// Generates the host function struct that implements `wasm_interface::Function` and returns a +/// static reference to this struct. /// /// When calling from wasm into the host, we will call the `execute` function that calls the native /// implementation of the function. diff --git a/substrate/primitives/runtime-interface/src/lib.rs b/substrate/primitives/runtime-interface/src/lib.rs index 53b4270fe8..27c4422ed9 100644 --- a/substrate/primitives/runtime-interface/src/lib.rs +++ b/substrate/primitives/runtime-interface/src/lib.rs @@ -26,11 +26,12 @@ //! # Using a type in a runtime interface //! //! Any type that should be used in a runtime interface as argument or return value needs to -//! implement [`RIType`]. The associated type [`FFIType`](./trait.RIType.html#associatedtype.FFIType) -//! is the type that is used in the FFI function to represent the actual type. For example `[T]` is -//! represented by an `u64`. The slice pointer and the length will be mapped to an `u64` value. -//! For more information see this [table](#ffi-type-and-conversion). -//! The FFI function definition is used when calling from the wasm runtime into the node. +//! implement [`RIType`]. The associated type +//! [`FFIType`](./trait.RIType.html#associatedtype.FFIType) is the type that is used in the FFI +//! function to represent the actual type. For example `[T]` is represented by an `u64`. The slice +//! pointer and the length will be mapped to an `u64` value. For more information see this +//! [table](#ffi-type-and-conversion). The FFI function definition is used when calling from the +//! wasm runtime into the node. //! //! Traits are used to convert from a type to the corresponding //! [`RIType::FFIType`](./trait.RIType.html#associatedtype.FFIType). @@ -93,13 +94,14 @@ //! | `&str` | `u64` | v.len() 32bit << 32 | v.as_ptr() 32bit | //! | `&[u8]` | `u64` | v.len() 32bit << 32 | v.as_ptr() 32bit | //! | `Vec` | `u64` | v.len() 32bit << 32 | v.as_ptr() 32bit | -//! | `Vec where T: Encode` | `u64` | `let e = v.encode();`

e.len() 32bit << 32 | e.as_ptr() 32bit | -//! | `&[T] where T: Encode` | `u64` | `let e = v.encode();`

e.len() 32bit << 32 | e.as_ptr() 32bit | -//! | `[u8; N]` | `u32` | `v.as_ptr()` | -//! | `*const T` | `u32` | `Identity` | -//! | `Option` | `u64` | `let e = v.encode();`

e.len() 32bit << 32 | e.as_ptr() 32bit | -//! | [`T where T: PassBy`](./pass_by#Inner) | Depends on inner | Depends on inner | -//! | [`T where T: PassBy`](./pass_by#Codec)|`u64`|v.len() 32bit << 32 |v.as_ptr() 32bit| +//! | `Vec where T: Encode` | `u64` | `let e = v.encode();`

e.len() 32bit << 32 +//! | e.as_ptr() 32bit | | `&[T] where T: Encode` | `u64` | `let e = +//! v.encode();`

e.len() 32bit << 32 | e.as_ptr() 32bit | | `[u8; N]` | +//! `u32` | `v.as_ptr()` | | `*const T` | `u32` | `Identity` | +//! | `Option` | `u64` | `let e = v.encode();`

e.len() 32bit << 32 | e.as_ptr() +//! 32bit | | [`T where T: PassBy`](./pass_by#Inner) | Depends on inner | +//! Depends on inner | | [`T where T: PassBy`](./pass_by#Codec)|`u64`|v.len() +//! 32bit << 32 |v.as_ptr() 32bit| //! //! `Identity` means that the value is converted directly into the corresponding FFI type. @@ -119,10 +121,10 @@ pub use sp_std; /// Attribute macro for transforming a trait declaration into a runtime interface. /// -/// A runtime interface is a fixed interface between a Substrate compatible runtime and the native -/// node. This interface is callable from a native and a wasm runtime. The macro will generate the -/// corresponding code for the native implementation and the code for calling from the wasm -/// side to the native implementation. +/// A runtime interface is a fixed interface between a Substrate compatible runtime and the +/// native node. This interface is callable from a native and a wasm runtime. The macro will +/// generate the corresponding code for the native implementation and the code for calling from +/// the wasm side to the native implementation. /// /// The macro expects the runtime interface declaration as trait declaration: /// @@ -273,25 +275,25 @@ pub use sp_std; /// The macro supports any kind of argument type, as long as it implements [`RIType`] and the /// required `FromFFIValue`/`IntoFFIValue`. The macro will convert each /// argument to the corresponding FFI representation and will call into the host using this FFI -/// representation. On the host each argument is converted back to the native representation and -/// the native implementation is called. Any return value is handled in the same way. +/// representation. On the host each argument is converted back to the native representation +/// and the native implementation is called. Any return value is handled in the same way. /// /// # Wasm only interfaces /// -/// Some interfaces are only required from within the wasm runtime e.g. the allocator interface. -/// To support this, the macro can be called like `#[runtime_interface(wasm_only)]`. This instructs -/// the macro to make two significant changes to the generated code: +/// Some interfaces are only required from within the wasm runtime e.g. the allocator +/// interface. To support this, the macro can be called like `#[runtime_interface(wasm_only)]`. +/// This instructs the macro to make two significant changes to the generated code: /// /// 1. The generated functions are not callable from the native side. -/// 2. The trait as shown above is not implemented for `Externalities` and is instead implemented -/// for `FunctionExecutor` (from `sp-wasm-interface`). +/// 2. The trait as shown above is not implemented for `Externalities` and is instead +/// implemented for `FunctionExecutor` (from `sp-wasm-interface`). /// /// # Disable tracing /// By addding `no_tracing` to the list of options you can prevent the wasm-side interface from -/// generating the default `sp-tracing`-calls. Note that this is rarely needed but only meant for -/// the case when that would create a circular dependency. You usually _do not_ want to add this -/// flag, as tracing doesn't cost you anything by default anyways (it is added as a no-op) but is -/// super useful for debugging later. +/// generating the default `sp-tracing`-calls. Note that this is rarely needed but only meant +/// for the case when that would create a circular dependency. You usually _do not_ want to add +/// this flag, as tracing doesn't cost you anything by default anyways (it is added as a no-op) +/// but is super useful for debugging later. pub use sp_runtime_interface_proc_macro::runtime_interface; #[doc(hidden)] diff --git a/substrate/primitives/runtime-interface/src/pass_by.rs b/substrate/primitives/runtime-interface/src/pass_by.rs index 0535d1ca8d..7324e93638 100644 --- a/substrate/primitives/runtime-interface/src/pass_by.rs +++ b/substrate/primitives/runtime-interface/src/pass_by.rs @@ -40,8 +40,8 @@ use sp_std::vec::Vec; /// Derive macro for implementing [`PassBy`] with the [`Codec`] strategy. /// -/// This requires that the type implements [`Encode`](codec::Encode) and [`Decode`](codec::Decode) -/// from `parity-scale-codec`. +/// This requires that the type implements [`Encode`](codec::Encode) and +/// [`Decode`](codec::Decode) from `parity-scale-codec`. /// /// # Example /// @@ -58,11 +58,12 @@ pub use sp_runtime_interface_proc_macro::PassByCodec; /// Derive macro for implementing [`PassBy`] with the [`Inner`] strategy. /// -/// Besides implementing [`PassBy`], this derive also implements the helper trait [`PassByInner`]. +/// Besides implementing [`PassBy`], this derive also implements the helper trait +/// [`PassByInner`]. /// /// The type is required to be a struct with just one field. The field type needs to implement -/// the required traits to pass it between the wasm and the native side. (See the runtime interface -/// crate for more information about these traits.) +/// the required traits to pass it between the wasm and the native side. (See the runtime +/// interface crate for more information about these traits.) /// /// # Example /// @@ -86,8 +87,8 @@ pub use sp_runtime_interface_proc_macro::PassByInner; /// Besides implementing [`PassBy`], this derive also implements `TryFrom` and /// `From for u8` for the type. /// -/// The type is required to be an enum with only unit variants and at maximum `256` variants. Also -/// it is required that the type implements `Copy`. +/// The type is required to be an enum with only unit variants and at maximum `256` variants. +/// Also it is required that the type implements `Copy`. /// /// # Example /// diff --git a/substrate/primitives/runtime-interface/src/util.rs b/substrate/primitives/runtime-interface/src/util.rs index 5b3aa07e60..31045c83c9 100644 --- a/substrate/primitives/runtime-interface/src/util.rs +++ b/substrate/primitives/runtime-interface/src/util.rs @@ -29,8 +29,8 @@ pub fn pack_ptr_and_len(ptr: u32, len: u32) -> u64 { /// Unpacks an `u64` into the pointer and length. /// /// Runtime API functions return a 64-bit value which encodes a pointer in the least-significant -/// 32-bits and a length in the most-significant 32 bits. This interprets the returned value as a pointer, -/// length tuple. +/// 32-bits and a length in the most-significant 32 bits. This interprets the returned value as a +/// pointer, length tuple. pub fn unpack_ptr_and_len(val: u64) -> (u32, u32) { // The static assertions from above are changed into a runtime check. #[cfg(all(not(feature = "std"), feature = "disable_target_static_assertions"))] diff --git a/substrate/primitives/runtime/src/generic/digest.rs b/substrate/primitives/runtime/src/generic/digest.rs index 195bf1cbe5..390acb87f6 100644 --- a/substrate/primitives/runtime/src/generic/digest.rs +++ b/substrate/primitives/runtime/src/generic/digest.rs @@ -128,12 +128,11 @@ pub enum ChangesTrieSignal { /// /// The block that emits this signal will contain changes trie (CT) that covers /// blocks range [BEGIN; current block], where BEGIN is (order matters): - /// - LAST_TOP_LEVEL_DIGEST_BLOCK+1 if top level digest CT has ever been created - /// using current configuration AND the last top level digest CT has been created - /// at block LAST_TOP_LEVEL_DIGEST_BLOCK; - /// - LAST_CONFIGURATION_CHANGE_BLOCK+1 if there has been CT configuration change - /// before and the last configuration change happened at block - /// LAST_CONFIGURATION_CHANGE_BLOCK; + /// - LAST_TOP_LEVEL_DIGEST_BLOCK+1 if top level digest CT has ever been created using current + /// configuration AND the last top level digest CT has been created at block + /// LAST_TOP_LEVEL_DIGEST_BLOCK; + /// - LAST_CONFIGURATION_CHANGE_BLOCK+1 if there has been CT configuration change before and + /// the last configuration change happened at block LAST_CONFIGURATION_CHANGE_BLOCK; /// - 1 otherwise. NewConfiguration(Option), } diff --git a/substrate/primitives/runtime/src/generic/era.rs b/substrate/primitives/runtime/src/generic/era.rs index 80ac46125b..1a7239ab6e 100644 --- a/substrate/primitives/runtime/src/generic/era.rs +++ b/substrate/primitives/runtime/src/generic/era.rs @@ -55,8 +55,9 @@ pub enum Era { // phase = 1 // n = Q(current - phase, period) + phase impl Era { - /// Create a new era based on a period (which should be a power of two between 4 and 65536 inclusive) - /// and a block number on which it should start (or, for long periods, be shortly after the start). + /// Create a new era based on a period (which should be a power of two between 4 and 65536 + /// inclusive) and a block number on which it should start (or, for long periods, be shortly + /// after the start). /// /// If using `Era` in the context of `FRAME` runtime, make sure that `period` /// does not exceed `BlockHashCount` parameter passed to `system` module, since that diff --git a/substrate/primitives/runtime/src/lib.rs b/substrate/primitives/runtime/src/lib.rs index ce24848792..4a9c6087fa 100644 --- a/substrate/primitives/runtime/src/lib.rs +++ b/substrate/primitives/runtime/src/lib.rs @@ -728,10 +728,10 @@ pub type DispatchOutcome = Result<(), DispatchError>; /// /// Examples of reasons preventing inclusion in a block: /// - More block weight is required to process the extrinsic than is left in the block being built. -/// This doesn't necessarily mean that the extrinsic is invalid, since it can still be -/// included in the next block if it has enough spare weight available. -/// - The sender doesn't have enough funds to pay the transaction inclusion fee. Including such -/// a transaction in the block doesn't make sense. +/// This doesn't necessarily mean that the extrinsic is invalid, since it can still be included in +/// the next block if it has enough spare weight available. +/// - The sender doesn't have enough funds to pay the transaction inclusion fee. Including such a +/// transaction in the block doesn't make sense. /// - The extrinsic supplied a bad signature. This transaction won't become valid ever. pub type ApplyExtrinsicResult = Result; diff --git a/substrate/primitives/runtime/src/offchain/http.rs b/substrate/primitives/runtime/src/offchain/http.rs index 7b305ebd9c..469f2fb5af 100644 --- a/substrate/primitives/runtime/src/offchain/http.rs +++ b/substrate/primitives/runtime/src/offchain/http.rs @@ -288,7 +288,8 @@ impl PendingRequest { /// Attempt to wait for all provided requests, but up to given deadline. /// - /// Requests that are complete will resolve to an `Ok` others will return a `DeadlineReached` error. + /// Requests that are complete will resolve to an `Ok` others will return a `DeadlineReached` + /// error. pub fn try_wait_all( requests: Vec, deadline: impl Into>, diff --git a/substrate/primitives/runtime/src/traits.rs b/substrate/primitives/runtime/src/traits.rs index 3baf7c6655..15ca897e61 100644 --- a/substrate/primitives/runtime/src/traits.rs +++ b/substrate/primitives/runtime/src/traits.rs @@ -738,8 +738,8 @@ pub trait Extrinsic: Sized + MaybeMallocSizeOf { /// /// Extrinsics can be split into: /// 1. Inherents (no signature; created by validators during block production) - /// 2. Unsigned Transactions (no signature; represent "system calls" or other special kinds of calls) - /// 3. Signed Transactions (with signature; a regular transactions with known origin) + /// 2. Unsigned Transactions (no signature; represent "system calls" or other special kinds of + /// calls) 3. Signed Transactions (with signature; a regular transactions with known origin) fn new(_call: Self::Call, _signed_data: Option) -> Option { None } @@ -765,8 +765,8 @@ pub type DigestItemFor = DigestItem<<::Header as Header>::Hash>; /// A "checkable" piece of information, used by the standard Substrate Executive in order to /// check the validity of a piece of extrinsic information, usually by verifying the signature. -/// Implement for pieces of information that require some additional context `Context` in order to be -/// checked. +/// Implement for pieces of information that require some additional context `Context` in order to +/// be checked. pub trait Checkable: Sized { /// Returned if `check` succeeds. type Checked; diff --git a/substrate/primitives/runtime/src/transaction_validity.rs b/substrate/primitives/runtime/src/transaction_validity.rs index 939452384f..e114bb5985 100644 --- a/substrate/primitives/runtime/src/transaction_validity.rs +++ b/substrate/primitives/runtime/src/transaction_validity.rs @@ -60,7 +60,8 @@ pub enum InvalidTransaction { /// # Possible causes /// /// For `FRAME`-based runtimes this would be caused by `current block number - /// - Era::birth block number > BlockHashCount`. (e.g. in Polkadot `BlockHashCount` = 2400, so a + /// - Era::birth block number > BlockHashCount`. (e.g. in Polkadot `BlockHashCount` = 2400, so + /// a /// transaction with birth block number 1337 would be valid up until block number 1337 + 2400, /// after which point the transaction would be considered to have an ancient birth block.) AncientBirthBlock, @@ -72,8 +73,8 @@ pub enum InvalidTransaction { /// Any other custom invalid validity that is not covered by this enum. Custom(u8), /// An extrinsic with a Mandatory dispatch resulted in Error. This is indicative of either a - /// malicious validator or a buggy `provide_inherent`. In any case, it can result in dangerously - /// overweight blocks and therefore if found, invalidates the block. + /// malicious validator or a buggy `provide_inherent`. In any case, it can result in + /// dangerously overweight blocks and therefore if found, invalidates the block. BadMandatory, /// A transaction with a mandatory dispatch. This is invalid; only inherent extrinsics are /// allowed to have mandatory dispatches. diff --git a/substrate/primitives/sandbox/src/lib.rs b/substrate/primitives/sandbox/src/lib.rs index a433d57c3b..94cb676b51 100755 --- a/substrate/primitives/sandbox/src/lib.rs +++ b/substrate/primitives/sandbox/src/lib.rs @@ -23,9 +23,9 @@ //! and without the performance penalty of full wasm emulation inside wasm. //! //! This is achieved by using bindings to the wasm VM, which are published by the host API. -//! This API is thin and consists of only a handful functions. It contains functions for instantiating -//! modules and executing them, but doesn't contain functions for inspecting the module -//! structure. The user of this library is supposed to read the wasm module. +//! This API is thin and consists of only a handful functions. It contains functions for +//! instantiating modules and executing them, but doesn't contain functions for inspecting the +//! module structure. The user of this library is supposed to read the wasm module. //! //! When this crate is used in the `std` environment all these functions are implemented by directly //! calling the wasm VM. @@ -168,8 +168,8 @@ impl Instance { /// run the `start` function (if it is present in the module) with the given `state`. /// /// Returns `Err(Error::Module)` if this module can't be instantiated with the given - /// environment. If execution of `start` function generated a trap, then `Err(Error::Execution)` will - /// be returned. + /// environment. If execution of `start` function generated a trap, then `Err(Error::Execution)` + /// will be returned. /// /// [`EnvironmentDefinitionBuilder`]: struct.EnvironmentDefinitionBuilder.html pub fn new( @@ -188,8 +188,8 @@ impl Instance { /// /// - An export function name isn't a proper utf8 byte sequence, /// - This module doesn't have an exported function with the given name, - /// - If types of the arguments passed to the function doesn't match function signature - /// then trap occurs (as if the exported function was called via call_indirect), + /// - If types of the arguments passed to the function doesn't match function signature then + /// trap occurs (as if the exported function was called via call_indirect), /// - Trap occurred at the execution time. pub fn invoke( &mut self, diff --git a/substrate/primitives/state-machine/src/changes_trie/build.rs b/substrate/primitives/state-machine/src/changes_trie/build.rs index 2c75ac236b..d3c6c12122 100644 --- a/substrate/primitives/state-machine/src/changes_trie/build.rs +++ b/substrate/primitives/state-machine/src/changes_trie/build.rs @@ -147,8 +147,8 @@ where |mut map: BTreeMap<&[u8], (ExtrinsicIndex, Vec)>, (k, extrinsics)| { match map.entry(k) { Entry::Vacant(entry) => { - // ignore temporary values (values that have null value at the end of operation - // AND are not in storage at the beginning of operation + // ignore temporary values (values that have null value at the end of + // operation AND are not in storage at the beginning of operation if let Some(child_info) = child_info.as_ref() { if !overlay .child_storage(child_info, k) @@ -177,8 +177,8 @@ where )); }, Entry::Occupied(mut entry) => { - // we do not need to check for temporary values here, because entry is Occupied - // AND we are checking it before insertion + // we do not need to check for temporary values here, because entry is + // Occupied AND we are checking it before insertion let entry_extrinsics = &mut entry.get_mut().1; entry_extrinsics.extend(extrinsics.into_iter()); entry_extrinsics.sort(); @@ -246,11 +246,12 @@ where )); }, Entry::Occupied(mut entry) => { - // DigestIndexValue must be sorted. Here we are relying on the fact that digest_build_iterator() - // returns blocks in ascending order => we only need to check for duplicates + // DigestIndexValue must be sorted. Here we are relying on the fact that + // digest_build_iterator() returns blocks in ascending order => we only + // need to check for duplicates // - // is_dup_block could be true when key has been changed in both digest block - // AND other blocks that it covers + // is_dup_block could be true when key has been changed in both digest + // block AND other blocks that it covers let is_dup_block = entry.get().1.last() == Some(&digest_build_block); if !is_dup_block { entry.get_mut().1.push(digest_build_block.clone()); diff --git a/substrate/primitives/state-machine/src/changes_trie/build_cache.rs b/substrate/primitives/state-machine/src/changes_trie/build_cache.rs index 67098d4d72..04820242d9 100644 --- a/substrate/primitives/state-machine/src/changes_trie/build_cache.rs +++ b/substrate/primitives/state-machine/src/changes_trie/build_cache.rs @@ -39,7 +39,8 @@ pub struct BuildCache { /// Map of changes trie root => set of storage keys that are in this trie. /// The `Option>` in inner `HashMap` stands for the child storage key. /// If it is `None`, then the `HashSet` contains keys changed in top-level storage. - /// If it is `Some`, then the `HashSet` contains keys changed in child storage, identified by the key. + /// If it is `Some`, then the `HashSet` contains keys changed in child storage, identified by + /// the key. changed_keys: HashMap, HashSet>>, } diff --git a/substrate/primitives/state-machine/src/changes_trie/build_iterator.rs b/substrate/primitives/state-machine/src/changes_trie/build_iterator.rs index d4adc99d10..62bb00a2f8 100644 --- a/substrate/primitives/state-machine/src/changes_trie/build_iterator.rs +++ b/substrate/primitives/state-machine/src/changes_trie/build_iterator.rs @@ -50,11 +50,12 @@ pub fn digest_build_iterator<'a, Number: BlockNumber>( /// required for inclusion into changes trie of given block. #[derive(Debug)] pub struct DigestBuildIterator { - /// Block we're building changes trie for. It could (logically) be a post-end block if we are creating - /// skewed digest. + /// Block we're building changes trie for. It could (logically) be a post-end block if we are + /// creating skewed digest. block: Number, - /// Block that is a last block where current configuration is active. We have never yet created anything - /// after this block => digest that we're creating can't reference any blocks that are >= end. + /// Block that is a last block where current configuration is active. We have never yet created + /// anything after this block => digest that we're creating can't reference any blocks that are + /// >= end. end: Number, /// Interval of L1 digest blocks. digest_interval: u32, @@ -445,7 +446,8 @@ mod tests { 256, 512, 768, 1024, 1280, // level3 MUST point to previous 16-1 level1 digests, BUT there are only 3: 1296, 1312, 1328, - // level3 MUST be a level1 digest of 16-1 previous blocks, BUT there are only 9: + // level3 MUST be a level1 digest of 16-1 previous blocks, BUT there are only + // 9: 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, ] .iter() @@ -467,8 +469,9 @@ mod tests { [ // level3 MUST point to previous 16-1 level2 digests, BUT there are only 5: 256, 512, 768, 1024, 1280, - // level3 MUST point to previous 16-1 level1 digests, BUT there are NO ANY L1-digests: - // level3 MUST be a level1 digest of 16-1 previous blocks, BUT there are only 3: + // level3 MUST point to previous 16-1 level1 digests, BUT there are NO ANY + // L1-digests: level3 MUST be a level1 digest of 16-1 previous blocks, BUT + // there are only 3: 1281, 1282, 1283, ] .iter() diff --git a/substrate/primitives/state-machine/src/changes_trie/changes_iterator.rs b/substrate/primitives/state-machine/src/changes_trie/changes_iterator.rs index 8b7d7c5781..9343a226a3 100644 --- a/substrate/primitives/state-machine/src/changes_trie/changes_iterator.rs +++ b/substrate/primitives/state-machine/src/changes_trie/changes_iterator.rs @@ -279,7 +279,8 @@ where if let Some(blocks) = blocks? { if let Ok(blocks) = >::decode(&mut &blocks[..]) { // filter level0 blocks here because we tend to use digest blocks, - // AND digest block changes could also include changes for out-of-range blocks + // AND digest block changes could also include changes for out-of-range + // blocks let begin = self.begin.clone(); let end = self.end.number.clone(); let config = self.config.clone(); diff --git a/substrate/primitives/state-machine/src/changes_trie/input.rs b/substrate/primitives/state-machine/src/changes_trie/input.rs index 4261042956..af0a423e57 100644 --- a/substrate/primitives/state-machine/src/changes_trie/input.rs +++ b/substrate/primitives/state-machine/src/changes_trie/input.rs @@ -63,9 +63,11 @@ pub type ChildIndexValue = Vec; pub enum InputPair { /// Element of { key => set of extrinsics where key has been changed } element mapping. ExtrinsicIndex(ExtrinsicIndex, ExtrinsicIndexValue), - /// Element of { key => set of blocks/digest blocks where key has been changed } element mapping. + /// Element of { key => set of blocks/digest blocks where key has been changed } element + /// mapping. DigestIndex(DigestIndex, DigestIndexValue), - /// Element of { childtrie key => Childchange trie } where key has been changed } element mapping. + /// Element of { childtrie key => Childchange trie } where key has been changed } element + /// mapping. ChildIndex(ChildIndex, ChildIndexValue), } diff --git a/substrate/primitives/state-machine/src/changes_trie/mod.rs b/substrate/primitives/state-machine/src/changes_trie/mod.rs index 7fedff1f1e..4014809524 100644 --- a/substrate/primitives/state-machine/src/changes_trie/mod.rs +++ b/substrate/primitives/state-machine/src/changes_trie/mod.rs @@ -153,8 +153,8 @@ pub struct State<'a, H, Number> { /// Configuration that is active at given block. pub config: Configuration, /// Configuration activation block number. Zero if it is the first configuration on the chain, - /// or number of the block that have emit NewConfiguration signal (thus activating configuration - /// starting from the **next** block). + /// or number of the block that have emit NewConfiguration signal (thus activating + /// configuration starting from the **next** block). pub zero: Number, /// Underlying changes tries storage reference. pub storage: &'a dyn Storage, @@ -276,8 +276,8 @@ where let parent = state.storage.build_anchor(parent_hash).map_err(|_| ())?; let block = parent.number.clone() + One::one(); - // prepare configuration range - we already know zero block. Current block may be the end block if configuration - // has been changed in this block + // prepare configuration range - we already know zero block. Current block may be the end block + // if configuration has been changed in this block let is_config_changed = match changes.storage(sp_core::storage::well_known_keys::CHANGES_TRIE_CONFIG) { Some(Some(new_config)) => new_config != &state.config.encode()[..], @@ -290,7 +290,8 @@ where end: if is_config_changed { Some(block.clone()) } else { None }, }; - // storage errors are considered fatal (similar to situations when runtime fetches values from storage) + // storage errors are considered fatal (similar to situations when runtime fetches values from + // storage) let (input_pairs, child_input_pairs, digest_input_blocks) = maybe_panic( prepare_input::( backend, diff --git a/substrate/primitives/state-machine/src/changes_trie/surface_iterator.rs b/substrate/primitives/state-machine/src/changes_trie/surface_iterator.rs index 509c02ee37..b3e5a490cd 100644 --- a/substrate/primitives/state-machine/src/changes_trie/surface_iterator.rs +++ b/substrate/primitives/state-machine/src/changes_trie/surface_iterator.rs @@ -15,11 +15,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! The best way to understand how this iterator works is to imagine some 2D terrain that have some mountains -//! (digest changes tries) and valleys (changes tries for regular blocks). There are gems (blocks) beneath the -//! terrain. Given the request to find all gems in the range [X1; X2] this iterator will return **minimal set** -//! of points at the terrain (mountains and valleys) inside this range that have to be drilled down to -//! search for gems. +//! The best way to understand how this iterator works is to imagine some 2D terrain that have some +//! mountains (digest changes tries) and valleys (changes tries for regular blocks). There are gems +//! (blocks) beneath the terrain. Given the request to find all gems in the range [X1; X2] this +//! iterator will return **minimal set** of points at the terrain (mountains and valleys) inside +//! this range that have to be drilled down to search for gems. use crate::changes_trie::{BlockNumber, ConfigurationRange}; use num_traits::One; @@ -50,9 +50,9 @@ pub fn surface_iterator<'a, Number: BlockNumber>( /// Surface iterator - only traverses top-level digests from given range and tries to find /// all valid digest changes. /// -/// Iterator item is the tuple of (last block of the current point + digest level of the current point). -/// Digest level is Some(0) when it is regular block, is Some(non-zero) when it is digest block and None -/// if it is skewed digest block. +/// Iterator item is the tuple of (last block of the current point + digest level of the current +/// point). Digest level is Some(0) when it is regular block, is Some(non-zero) when it is digest +/// block and None if it is skewed digest block. pub struct SurfaceIterator<'a, Number: BlockNumber> { config: ConfigurationRange<'a, Number>, begin: Number, diff --git a/substrate/primitives/state-machine/src/ext.rs b/substrate/primitives/state-machine/src/ext.rs index 5f22714d4d..c9693ca6a8 100644 --- a/substrate/primitives/state-machine/src/ext.rs +++ b/substrate/primitives/state-machine/src/ext.rs @@ -573,9 +573,9 @@ where if let Some((root, is_empty, _)) = root { let root = root.encode(); - // We store update in the overlay in order to be able to use 'self.storage_transaction' - // cache. This is brittle as it rely on Ext only querying the trie backend for - // storage root. + // We store update in the overlay in order to be able to use + // 'self.storage_transaction' cache. This is brittle as it rely on Ext only querying + // the trie backend for storage root. // A better design would be to manage 'child_storage_transaction' in a // similar way as 'storage_transaction' but for each child trie. if is_empty { diff --git a/substrate/primitives/state-machine/src/lib.rs b/substrate/primitives/state-machine/src/lib.rs index 1588a42f41..3c4acdccb1 100644 --- a/substrate/primitives/state-machine/src/lib.rs +++ b/substrate/primitives/state-machine/src/lib.rs @@ -206,7 +206,8 @@ mod execution { NativeWhenPossible, /// Use the given wasm module. AlwaysWasm, - /// Run with both the wasm and the native variant (if compatible). Report any discrepancy as an error. + /// Run with both the wasm and the native variant (if compatible). Report any discrepancy + /// as an error. Both, /// First native, then if that fails or is not possible, wasm. NativeElseWasm, @@ -230,10 +231,12 @@ mod execution { /// otherwise fall back to the wasm. NativeWhenPossible, /// Use the given wasm module. The backend on which code is executed code could be - /// trusted to provide all storage or not (i.e. the light client cannot be trusted to provide - /// for all storage queries since the storage entries it has come from an external node). + /// trusted to provide all storage or not (i.e. the light client cannot be trusted to + /// provide for all storage queries since the storage entries it has come from an external + /// node). AlwaysWasm(BackendTrustLevel), - /// Run with both the wasm and the native variant (if compatible). Call `F` in the case of any discrepancy. + /// Run with both the wasm and the native variant (if compatible). Call `F` in the case of + /// any discrepancy. Both(F), /// First native, then if that fails or is not possible, wasm. NativeElseWasm, @@ -278,12 +281,14 @@ mod execution { ExecutionManager::NativeElseWasm } - /// Evaluate to ExecutionManager::AlwaysWasm with trusted backend, without having to figure out the type. + /// Evaluate to ExecutionManager::AlwaysWasm with trusted backend, without having to figure out + /// the type. fn always_wasm() -> ExecutionManager> { ExecutionManager::AlwaysWasm(BackendTrustLevel::Trusted) } - /// Evaluate ExecutionManager::AlwaysWasm with untrusted backend, without having to figure out the type. + /// Evaluate ExecutionManager::AlwaysWasm with untrusted backend, without having to figure out + /// the type. fn always_untrusted_wasm() -> ExecutionManager> { ExecutionManager::AlwaysWasm(BackendTrustLevel::Untrusted) } @@ -390,8 +395,8 @@ mod execution { /// /// Returns the SCALE encoded result of the executed function. pub fn execute(&mut self, strategy: ExecutionStrategy) -> Result, Box> { - // We are not giving a native call and thus we are sure that the result can never be a native - // value. + // We are not giving a native call and thus we are sure that the result can never be a + // native value. self.execute_using_consensus_failure_handler::<_, NeverNativeValue, fn() -> _>( strategy.get_manager(), None, diff --git a/substrate/primitives/state-machine/src/overlayed_changes/offchain.rs b/substrate/primitives/state-machine/src/overlayed_changes/offchain.rs index 9603426fa5..ac67ca3303 100644 --- a/substrate/primitives/state-machine/src/overlayed_changes/offchain.rs +++ b/substrate/primitives/state-machine/src/overlayed_changes/offchain.rs @@ -21,7 +21,8 @@ use super::changeset::OverlayedMap; use sp_core::offchain::OffchainOverlayedChange; use sp_std::prelude::Vec; -/// In-memory storage for offchain workers recoding changes for the actual offchain storage implementation. +/// In-memory storage for offchain workers recoding changes for the actual offchain storage +/// implementation. #[derive(Debug, Clone, Default)] pub struct OffchainOverlayedChanges(OverlayedMap<(Vec, Vec), OffchainOverlayedChange>); diff --git a/substrate/primitives/timestamp/src/lib.rs b/substrate/primitives/timestamp/src/lib.rs index 892d359d8e..5de1b10e79 100644 --- a/substrate/primitives/timestamp/src/lib.rs +++ b/substrate/primitives/timestamp/src/lib.rs @@ -198,8 +198,8 @@ impl InherentDataProvider { /// By default the maximum drift is 60 seconds. /// /// The maximum drift is used when checking the inherents of a runtime. If the current timestamp - /// plus the maximum drift is smaller than the timestamp in the block, the block will be rejected - /// as being too far in the future. + /// plus the maximum drift is smaller than the timestamp in the block, the block will be + /// rejected as being too far in the future. pub fn with_max_drift(mut self, max_drift: std::time::Duration) -> Self { self.max_drift = max_drift.into(); self diff --git a/substrate/primitives/tracing/src/types.rs b/substrate/primitives/tracing/src/types.rs index 355e2fa451..377bd0f42c 100644 --- a/substrate/primitives/tracing/src/types.rs +++ b/substrate/primitives/tracing/src/types.rs @@ -465,9 +465,9 @@ mod std_features { // Implementation Note: // the original `tracing` crate generates these static metadata entries at every `span!` and - // `event!` location to allow for highly optimised filtering. For us to allow level-based emitting - // of wasm events we need these static metadata entries to inject into that system. We then provide - // generic `From`-implementations picking the right metadata to refer to. + // `event!` location to allow for highly optimised filtering. For us to allow level-based + // emitting of wasm events we need these static metadata entries to inject into that system. We + // then provide generic `From`-implementations picking the right metadata to refer to. static SPAN_ERROR_METADATA: tracing_core::Metadata<'static> = tracing::Metadata::new( WASM_TRACE_IDENTIFIER, diff --git a/substrate/primitives/trie/src/storage_proof.rs b/substrate/primitives/trie/src/storage_proof.rs index b4e4b393a7..410ad44e75 100644 --- a/substrate/primitives/trie/src/storage_proof.rs +++ b/substrate/primitives/trie/src/storage_proof.rs @@ -72,8 +72,8 @@ impl StorageProof { } /// Merges multiple storage proofs covering potentially different sets of keys into one proof - /// covering all keys. The merged proof output may be smaller than the aggregate size of the input - /// proofs due to deduplication of trie nodes. + /// covering all keys. The merged proof output may be smaller than the aggregate size of the + /// input proofs due to deduplication of trie nodes. pub fn merge(proofs: I) -> Self where I: IntoIterator, diff --git a/substrate/primitives/utils/src/lib.rs b/substrate/primitives/utils/src/lib.rs index 6461361c96..693b05a8b9 100644 --- a/substrate/primitives/utils/src/lib.rs +++ b/substrate/primitives/utils/src/lib.rs @@ -27,7 +27,8 @@ //! and `UnboundedReceiver` to register every `send`/`received`/`dropped` action happened on //! the channel. //! -//! Also this feature creates and registers a prometheus vector with name `unbounded_channel_len` and labels: +//! Also this feature creates and registers a prometheus vector with name `unbounded_channel_len` +//! and labels: //! //! | Label | Description | //! | ------------ | --------------------------------------------- | diff --git a/substrate/primitives/utils/src/status_sinks.rs b/substrate/primitives/utils/src/status_sinks.rs index 0870ab1192..b8e0578161 100644 --- a/substrate/primitives/utils/src/status_sinks.rs +++ b/substrate/primitives/utils/src/status_sinks.rs @@ -86,8 +86,8 @@ impl StatusSinks { let inner = &mut *inner; loop { - // Future that produces the next ready entry in `entries`, or doesn't produce anything if - // the list is empty. + // Future that produces the next ready entry in `entries`, or doesn't produce anything + // if the list is empty. let next_ready_entry = { let entries = &mut inner.entries; async move { diff --git a/substrate/primitives/version/proc-macro/src/decl_runtime_version.rs b/substrate/primitives/version/proc-macro/src/decl_runtime_version.rs index cdf244f72c..eef6314be4 100644 --- a/substrate/primitives/version/proc-macro/src/decl_runtime_version.rs +++ b/substrate/primitives/version/proc-macro/src/decl_runtime_version.rs @@ -25,9 +25,10 @@ use syn::{ Expr, ExprLit, FieldValue, ItemConst, Lit, }; -/// This macro accepts a `const` item that has a struct initializer expression of `RuntimeVersion`-like type. -/// The macro will pass through this declaration and append an item declaration that will -/// lead to emitting a wasm custom section with the contents of `RuntimeVersion`. +/// This macro accepts a `const` item that has a struct initializer expression of +/// `RuntimeVersion`-like type. The macro will pass through this declaration and append an item +/// declaration that will lead to emitting a wasm custom section with the contents of +/// `RuntimeVersion`. pub fn decl_runtime_version_impl(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let item = parse_macro_input!(input as ItemConst); decl_runtime_version_impl_inner(item) @@ -125,8 +126,8 @@ impl ParseRuntimeVersion { // Intentionally ignored // // The definition will pass through for the declaration, however, it won't get into - // the "runtime_version" custom section. `impl_runtime_apis` is responsible for generating - // a custom section with the supported runtime apis descriptor. + // the "runtime_version" custom section. `impl_runtime_apis` is responsible for + // generating a custom section with the supported runtime apis descriptor. } else { return Err(Error::new(field_name.span(), "unknown field")) } diff --git a/substrate/primitives/version/src/lib.rs b/substrate/primitives/version/src/lib.rs index c76fb44a2c..65b22436a5 100644 --- a/substrate/primitives/version/src/lib.rs +++ b/substrate/primitives/version/src/lib.rs @@ -38,15 +38,15 @@ use sp_runtime::{generic::BlockId, traits::Block as BlockT}; #[cfg(feature = "std")] pub mod embed; -/// An attribute that accepts a version declaration of a runtime and generates a custom wasm section -/// with the equivalent contents. +/// An attribute that accepts a version declaration of a runtime and generates a custom wasm +/// section with the equivalent contents. /// -/// The custom section allows to read the version of the runtime without having to execute any code. -/// Instead, the generated custom section can be relatively easily parsed from the wasm binary. The -/// identifier of the custom section is "runtime_version". +/// The custom section allows to read the version of the runtime without having to execute any +/// code. Instead, the generated custom section can be relatively easily parsed from the wasm +/// binary. The identifier of the custom section is "runtime_version". /// -/// A shortcoming of this macro is that it is unable to embed information regarding supported APIs. -/// This is supported by the `construct_runtime!` macro. +/// A shortcoming of this macro is that it is unable to embed information regarding supported +/// APIs. This is supported by the `construct_runtime!` macro. /// /// # Usage /// @@ -69,32 +69,33 @@ pub mod embed; /// # const RUNTIME_API_VERSIONS: sp_version::ApisVec = sp_version::create_apis_vec!([]); /// ``` /// -/// It will pass it through and add code required for emitting a custom section. The information that -/// will go into the custom section is parsed from the item declaration. Due to that, the macro is -/// somewhat rigid in terms of the code it accepts. There are the following considerations: +/// It will pass it through and add code required for emitting a custom section. The +/// information that will go into the custom section is parsed from the item declaration. Due +/// to that, the macro is somewhat rigid in terms of the code it accepts. There are the +/// following considerations: /// -/// - The `spec_name` and `impl_name` must be set by a macro-like expression. The name of the macro -/// doesn't matter though. +/// - The `spec_name` and `impl_name` must be set by a macro-like expression. The name of the +/// macro doesn't matter though. /// /// - `authoring_version`, `spec_version`, `impl_version` and `transaction_version` must be set -/// by a literal. Literal must be an integer. No other expressions are allowed there. In particular, -/// you can't supply a constant variable. +/// by a literal. Literal must be an integer. No other expressions are allowed there. In +/// particular, you can't supply a constant variable. /// -/// - `apis` doesn't have any specific constraints. This is because this information doesn't get into -/// the custom section and is not parsed. +/// - `apis` doesn't have any specific constraints. This is because this information doesn't +/// get into the custom section and is not parsed. /// /// # Compilation Target & "std" feature /// -/// This macro assumes it will be used within a runtime. By convention, a runtime crate defines a -/// feature named "std". This feature is enabled when the runtime is compiled to native code and -/// disabled when it is compiled to the wasm code. +/// This macro assumes it will be used within a runtime. By convention, a runtime crate defines +/// a feature named "std". This feature is enabled when the runtime is compiled to native code +/// and disabled when it is compiled to the wasm code. /// -/// The custom section can only be emitted while compiling to wasm. In order to detect the compilation -/// target we use the "std" feature. This macro will emit the custom section only if the "std" feature -/// is **not** enabled. +/// The custom section can only be emitted while compiling to wasm. In order to detect the +/// compilation target we use the "std" feature. This macro will emit the custom section only +/// if the "std" feature is **not** enabled. /// -/// Including this macro in the context where there is no "std" feature and the code is not compiled -/// to wasm can lead to cryptic linking errors. +/// Including this macro in the context where there is no "std" feature and the code is not +/// compiled to wasm can lead to cryptic linking errors. pub use sp_version_proc_macro::runtime_version; /// The identity of a particular API interface that the runtime might provide. @@ -119,8 +120,9 @@ macro_rules! create_apis_vec { /// Runtime version. /// This should not be thought of as classic Semver (major/minor/tiny). /// This triplet have different semantics and mis-interpretation could cause problems. -/// In particular: bug fixes should result in an increment of `spec_version` and possibly `authoring_version`, -/// absolutely not `impl_version` since they change the semantics of the runtime. +/// In particular: bug fixes should result in an increment of `spec_version` and possibly +/// `authoring_version`, absolutely not `impl_version` since they change the semantics of the +/// runtime. #[derive(Clone, PartialEq, Eq, Encode, Decode, Default, sp_runtime::RuntimeDebug)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] @@ -168,9 +170,9 @@ pub struct RuntimeVersion { /// number changes, then `spec_version` must change, also. /// /// This number must change when an existing dispatchable (module ID, dispatch ID) is changed, - /// either through an alteration in its user-level semantics, a parameter added/removed/changed, - /// a dispatchable being removed, a module being removed, or a dispatchable/module changing its - /// index. + /// either through an alteration in its user-level semantics, a parameter + /// added/removed/changed, a dispatchable being removed, a module being removed, or a + /// dispatchable/module changing its index. /// /// It need *not* change when a new module is added or when a dispatchable is added. pub transaction_version: u32, diff --git a/substrate/primitives/wasm-interface/src/lib.rs b/substrate/primitives/wasm-interface/src/lib.rs index 3f1f1c1714..e1903ef425 100644 --- a/substrate/primitives/wasm-interface/src/lib.rs +++ b/substrate/primitives/wasm-interface/src/lib.rs @@ -143,7 +143,8 @@ impl Pointer { /// Calculate the offset from this pointer. /// - /// `offset` is in units of `T`. So, `3` means `3 * mem::size_of::()` as offset to the pointer. + /// `offset` is in units of `T`. So, `3` means `3 * mem::size_of::()` as offset to the + /// pointer. /// /// Returns an `Option` to respect that the pointer could probably overflow. pub fn offset(self, offset: u32) -> Option { diff --git a/substrate/rustfmt.toml b/substrate/rustfmt.toml index 15e9bdcdf1..441913f619 100644 --- a/substrate/rustfmt.toml +++ b/substrate/rustfmt.toml @@ -7,6 +7,9 @@ imports_granularity = "Crate" reorder_imports = true # Consistency newline_style = "Unix" +# Format comments +comment_width = 100 +wrap_comments = true # Misc chain_width = 80 spaces_around_ranges = false diff --git a/substrate/test-utils/client/src/lib.rs b/substrate/test-utils/client/src/lib.rs index d08a01a4de..a8d7818ace 100644 --- a/substrate/test-utils/client/src/lib.rs +++ b/substrate/test-utils/client/src/lib.rs @@ -392,8 +392,9 @@ where C: BlockchainEvents, B: BlockT, { - /// Wait for `count` blocks to be imported in the node and then exit. This function will not return if no blocks - /// are ever created, thus you should restrict the maximum amount of time of the test execution. + /// Wait for `count` blocks to be imported in the node and then exit. This function will not + /// return if no blocks are ever created, thus you should restrict the maximum amount of time of + /// the test execution. fn wait_for_blocks(&self, count: usize) -> Pin + Send>>; } diff --git a/substrate/test-utils/src/lib.rs b/substrate/test-utils/src/lib.rs index eef87a29ca..27f13e2a7b 100644 --- a/substrate/test-utils/src/lib.rs +++ b/substrate/test-utils/src/lib.rs @@ -19,8 +19,8 @@ #[doc(hidden)] pub use futures; -/// Marks async function to be executed by an async runtime and provide a `TaskExecutor`, suitable -/// to test environment. +/// Marks async function to be executed by an async runtime and provide a `TaskExecutor`, +/// suitable to test environment. /// /// # Requirements /// diff --git a/substrate/test-utils/test-runner/src/lib.rs b/substrate/test-utils/test-runner/src/lib.rs index ed0cc222bf..2c458f330e 100644 --- a/substrate/test-utils/test-runner/src/lib.rs +++ b/substrate/test-utils/test-runner/src/lib.rs @@ -23,15 +23,15 @@ //! Allows you to test //!
//! -//! - Migrations -//! - Runtime Upgrades -//! - Pallets and general runtime functionality. +//! - Migrations +//! - Runtime Upgrades +//! - Pallets and general runtime functionality. //! //! This works by running a full node with a Manual Seal-BABE™ hybrid consensus for block authoring. //! //!

Note

-//! The running node has no signature verification, which allows us author extrinsics for any account on chain. -//!
+//! The running node has no signature verification, which allows us author extrinsics for any +//! account on chain.
//!
//! //!

How do I Use this?

diff --git a/substrate/utils/fork-tree/src/lib.rs b/substrate/utils/fork-tree/src/lib.rs index bbcea262d4..9143da89a7 100644 --- a/substrate/utils/fork-tree/src/lib.rs +++ b/substrate/utils/fork-tree/src/lib.rs @@ -145,8 +145,8 @@ where child.number < *number && is_descendent_of(&child.hash, hash)?) { root.children.push(child); - // assuming that the tree is well formed only one child should pass this requirement - // due to ancestry restrictions (i.e. they must be different forks). + // assuming that the tree is well formed only one child should pass this + // requirement due to ancestry restrictions (i.e. they must be different forks). is_first = false; } else { removed.push(child); @@ -912,14 +912,15 @@ mod test { ) -> (ForkTree<&'a str, u64, ()>, impl Fn(&&str, &&str) -> Result) { let mut tree = ForkTree::new(); + #[rustfmt::skip] + // // - B - C - D - E // / // / - G // / / // A - F - H - I // \ - // - L - M - // \ + // - L - M \ // - O // \ // — J - K diff --git a/substrate/utils/frame/benchmarking-cli/src/lib.rs b/substrate/utils/frame/benchmarking-cli/src/lib.rs index 51a89f6d58..cd314adebe 100644 --- a/substrate/utils/frame/benchmarking-cli/src/lib.rs +++ b/substrate/utils/frame/benchmarking-cli/src/lib.rs @@ -21,8 +21,8 @@ mod writer; use sc_cli::{ExecutionStrategy, WasmExecutionMethod}; use std::fmt::Debug; -// Add a more relaxed parsing for pallet names by allowing pallet directory names with `-` to be used -// like crate names with `_` +// Add a more relaxed parsing for pallet names by allowing pallet directory names with `-` to be +// used like crate names with `_` fn parse_pallet_name(pallet: &str) -> String { pallet.replace("-", "_") } diff --git a/substrate/utils/frame/benchmarking-cli/src/writer.rs b/substrate/utils/frame/benchmarking-cli/src/writer.rs index b1816d4a7b..8701fb6512 100644 --- a/substrate/utils/frame/benchmarking-cli/src/writer.rs +++ b/substrate/utils/frame/benchmarking-cli/src/writer.rs @@ -188,7 +188,8 @@ fn get_benchmark_data( let writes = analysis_function(&batch.db_results, BenchmarkSelector::Writes) .expect("analysis function should return the number of writes for valid inputs"); - // Analysis data may include components that are not used, this filters out anything whose value is zero. + // Analysis data may include components that are not used, this filters out anything whose value + // is zero. let mut used_components = Vec::new(); let mut used_extrinsic_time = Vec::new(); let mut used_reads = Vec::new(); diff --git a/substrate/utils/frame/remote-externalities/src/lib.rs b/substrate/utils/frame/remote-externalities/src/lib.rs index 53c44780a6..347cc8d66d 100644 --- a/substrate/utils/frame/remote-externalities/src/lib.rs +++ b/substrate/utils/frame/remote-externalities/src/lib.rs @@ -107,7 +107,8 @@ impl From for Transport { /// A state snapshot config may be present and will be written to in that case. #[derive(Clone)] pub struct OnlineConfig { - /// The block hash at which to get the runtime state. Will be latest finalized head if not provided. + /// The block hash at which to get the runtime state. Will be latest finalized head if not + /// provided. pub at: Option, /// An optional state snapshot file to WRITE to, not for reading. Not written if set to `None`. pub state_snapshot: Option, diff --git a/substrate/utils/frame/try-runtime/cli/src/lib.rs b/substrate/utils/frame/try-runtime/cli/src/lib.rs index 4f31bd741b..1f1eef70e1 100644 --- a/substrate/utils/frame/try-runtime/cli/src/lib.rs +++ b/substrate/utils/frame/try-runtime/cli/src/lib.rs @@ -45,7 +45,8 @@ pub enum Command { OnRuntimeUpgrade(OnRuntimeUpgradeCmd), /// Execute "OffchainWorkerApi_offchain_worker" against the given runtime state. OffchainWorker(OffchainWorkerCmd), - /// Execute "Core_execute_block" using the given block and the runtime state of the parent block. + /// Execute "Core_execute_block" using the given block and the runtime state of the parent + /// block. ExecuteBlock(ExecuteBlockCmd), } diff --git a/substrate/utils/wasm-builder/src/builder.rs b/substrate/utils/wasm-builder/src/builder.rs index 20f33583b8..113b5eb068 100644 --- a/substrate/utils/wasm-builder/src/builder.rs +++ b/substrate/utils/wasm-builder/src/builder.rs @@ -215,12 +215,17 @@ fn generate_rerun_if_changed_instructions() { /// The current project is determined by using the `CARGO_MANIFEST_DIR` environment variable. /// /// `file_name` - The name + path of the file being generated. The file contains the -/// constant `WASM_BINARY`, which contains the built WASM binary. +/// constant `WASM_BINARY`, which contains the built WASM binary. +/// /// `project_cargo_toml` - The path to the `Cargo.toml` of the project that should be built. +/// /// `default_rustflags` - Default `RUSTFLAGS` that will always be set for the build. +/// /// `features_to_enable` - Features that should be enabled for the project. -/// `wasm_binary_name` - The optional wasm binary name that is extended with `.compact.compressed.wasm`. -/// If `None`, the project name will be used. +/// +/// `wasm_binary_name` - The optional wasm binary name that is extended with +/// +/// `.compact.compressed.wasm`. If `None`, the project name will be used. fn build_project( file_name: PathBuf, project_cargo_toml: PathBuf, diff --git a/substrate/utils/wasm-builder/src/lib.rs b/substrate/utils/wasm-builder/src/lib.rs index 0bfd4e7550..b13ecc4e4a 100644 --- a/substrate/utils/wasm-builder/src/lib.rs +++ b/substrate/utils/wasm-builder/src/lib.rs @@ -17,8 +17,8 @@ //! # Wasm builder is a utility for building a project as a Wasm binary //! -//! The Wasm builder is a tool that integrates the process of building the WASM binary of your project into the main -//! `cargo` build process. +//! The Wasm builder is a tool that integrates the process of building the WASM binary of your +//! project into the main `cargo` build process. //! //! ## Project setup //! @@ -51,14 +51,14 @@ //! include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); //! ``` //! -//! This will include the generated Wasm binary as two constants `WASM_BINARY` and `WASM_BINARY_BLOATY`. -//! The former is a compact Wasm binary and the latter is the Wasm binary as being generated by the compiler. -//! Both variables have `Option<&'static [u8]>` as type. +//! This will include the generated Wasm binary as two constants `WASM_BINARY` and +//! `WASM_BINARY_BLOATY`. The former is a compact Wasm binary and the latter is the Wasm binary as +//! being generated by the compiler. Both variables have `Option<&'static [u8]>` as type. //! //! ### Feature //! -//! Wasm builder supports to enable cargo features while building the Wasm binary. By default it will -//! enable all features in the wasm build that are enabled for the native build except the +//! Wasm builder supports to enable cargo features while building the Wasm binary. By default it +//! will enable all features in the wasm build that are enabled for the native build except the //! `default` and `std` features. Besides that, wasm builder supports the special `runtime-wasm` //! feature. This `runtime-wasm` feature will be enabled by the wasm builder when it compiles the //! Wasm binary. If this feature is not present, it will not be enabled. @@ -67,24 +67,26 @@ //! //! By using environment variables, you can configure which Wasm binaries are built and how: //! -//! - `SKIP_WASM_BUILD` - Skips building any Wasm binary. This is useful when only native should be recompiled. -//! If this is the first run and there doesn't exist a Wasm binary, this will set both -//! variables to `None`. -//! - `WASM_BUILD_TYPE` - Sets the build type for building Wasm binaries. Supported values are `release` or `debug`. -//! By default the build type is equal to the build type used by the main build. -//! - `FORCE_WASM_BUILD` - Can be set to force a Wasm build. On subsequent calls the value of the variable -//! needs to change. As wasm-builder instructs `cargo` to watch for file changes -//! this environment variable should only be required in certain circumstances. -//! - `WASM_BUILD_RUSTFLAGS` - Extend `RUSTFLAGS` given to `cargo build` while building the wasm binary. +//! - `SKIP_WASM_BUILD` - Skips building any Wasm binary. This is useful when only native should be +//! recompiled. If this is the first run and there doesn't exist a Wasm binary, this will set both +//! variables to `None`. +//! - `WASM_BUILD_TYPE` - Sets the build type for building Wasm binaries. Supported values are +//! `release` or `debug`. By default the build type is equal to the build type used by the main +//! build. +//! - `FORCE_WASM_BUILD` - Can be set to force a Wasm build. On subsequent calls the value of the +//! variable needs to change. As wasm-builder instructs `cargo` to watch for file changes this +//! environment variable should only be required in certain circumstances. +//! - `WASM_BUILD_RUSTFLAGS` - Extend `RUSTFLAGS` given to `cargo build` while building the wasm +//! binary. //! - `WASM_BUILD_NO_COLOR` - Disable color output of the wasm build. -//! - `WASM_TARGET_DIRECTORY` - Will copy any build Wasm binary to the given directory. The path needs -//! to be absolute. +//! - `WASM_TARGET_DIRECTORY` - Will copy any build Wasm binary to the given directory. The path +//! needs to be absolute. //! - `WASM_BUILD_TOOLCHAIN` - The toolchain that should be used to build the Wasm binaries. The -//! format needs to be the same as used by cargo, e.g. `nightly-2020-02-20`. +//! format needs to be the same as used by cargo, e.g. `nightly-2020-02-20`. //! -//! Each project can be skipped individually by using the environment variable `SKIP_PROJECT_NAME_WASM_BUILD`. -//! Where `PROJECT_NAME` needs to be replaced by the name of the cargo project, e.g. `node-runtime` will -//! be `NODE_RUNTIME`. +//! Each project can be skipped individually by using the environment variable +//! `SKIP_PROJECT_NAME_WASM_BUILD`. Where `PROJECT_NAME` needs to be replaced by the name of the +//! cargo project, e.g. `node-runtime` will be `NODE_RUNTIME`. //! //! ## Prerequisites: //! @@ -92,9 +94,10 @@ //! //! - rust nightly + `wasm32-unknown-unknown` toolchain //! -//! If a specific rust nightly is installed with `rustup`, it is important that the wasm target is installed -//! as well. For example if installing the rust nightly from 20.02.2020 using `rustup install nightly-2020-02-20`, -//! the wasm target needs to be installed as well `rustup target add wasm32-unknown-unknown --toolchain nightly-2020-02-20`. +//! If a specific rust nightly is installed with `rustup`, it is important that the wasm target is +//! installed as well. For example if installing the rust nightly from 20.02.2020 using `rustup +//! install nightly-2020-02-20`, the wasm target needs to be installed as well `rustup target add +//! wasm32-unknown-unknown --toolchain nightly-2020-02-20`. use std::{ env, fs, @@ -234,8 +237,8 @@ impl CargoCommand { /// Check if the supplied cargo command is a nightly version fn is_nightly(&self) -> bool { // `RUSTC_BOOTSTRAP` tells a stable compiler to behave like a nightly. So, when this env - // variable is set, we can assume that whatever rust compiler we have, it is a nightly compiler. - // For "more" information, see: + // variable is set, we can assume that whatever rust compiler we have, it is a nightly + // compiler. For "more" information, see: // https://github.com/rust-lang/rust/blob/fa0f7d0080d8e7e9eb20aa9cbf8013f96c81287f/src/libsyntax/feature_gate/check.rs#L891 env::var("RUSTC_BOOTSTRAP").is_ok() || self.command() diff --git a/substrate/utils/wasm-builder/src/wasm_project.rs b/substrate/utils/wasm-builder/src/wasm_project.rs index 4824991aca..868692d341 100644 --- a/substrate/utils/wasm-builder/src/wasm_project.rs +++ b/substrate/utils/wasm-builder/src/wasm_project.rs @@ -432,9 +432,9 @@ fn build_project(project: &Path, default_rustflags: &str, cargo_cmd: CargoComman .args(&["rustc", "--target=wasm32-unknown-unknown"]) .arg(format!("--manifest-path={}", manifest_path.display())) .env("RUSTFLAGS", rustflags) - // Unset the `CARGO_TARGET_DIR` to prevent a cargo deadlock (cargo locks a target dir exclusive). - // The runner project is created in `CARGO_TARGET_DIR` and executing it will create a sub target - // directory inside of `CARGO_TARGET_DIR`. + // Unset the `CARGO_TARGET_DIR` to prevent a cargo deadlock (cargo locks a target dir + // exclusive). The runner project is created in `CARGO_TARGET_DIR` and executing it will + // create a sub target directory inside of `CARGO_TARGET_DIR`. .env_remove("CARGO_TARGET_DIR") // We don't want to call ourselves recursively .env(crate::SKIP_BUILD_ENV, ""); @@ -642,8 +642,9 @@ fn package_rerun_if_changed(package: &DeduplicatePackage) { .into_iter() .filter_entry(|p| { // Ignore this entry if it is a directory that contains a `Cargo.toml` that is not the - // `Cargo.toml` related to the current package. This is done to ignore sub-crates of a crate. - // If such a sub-crate is a dependency, it will be processed independently anyway. + // `Cargo.toml` related to the current package. This is done to ignore sub-crates of a + // crate. If such a sub-crate is a dependency, it will be processed independently + // anyway. p.path() == manifest_path || !p.path().is_dir() || !p.path().join("Cargo.toml").exists() }) .filter_map(|p| p.ok().map(|p| p.into_path()))