From 837d9c3f418ec39b2acab3a404423b58117329a8 Mon Sep 17 00:00:00 2001 From: Pierre Krieger Date: Fri, 20 Sep 2024 11:08:05 +0200 Subject: [PATCH] Replace `NonZeroU*` with `NonZero` (#1965) --- full-node/src/consensus_service.rs | 15 ++--- full-node/src/jaeger_service.rs | 9 ++- full-node/src/json_rpc_service.rs | 8 +-- .../chain_head_subscriptions.rs | 4 +- .../legacy_api_subscriptions.rs | 12 ++-- .../runtime_caches_service.rs | 4 +- lib/src/author/aura.rs | 4 +- lib/src/author/build.rs | 4 +- lib/src/chain/blocks_tree.rs | 6 +- lib/src/chain/blocks_tree/tests.rs | 30 ++++----- lib/src/chain/chain_information.rs | 10 +-- lib/src/chain/chain_information/build.rs | 18 ++--- lib/src/chain_spec.rs | 6 +- lib/src/chain_spec/light_sync_state.rs | 4 +- lib/src/database/finalized_serialize/defs.rs | 10 +-- lib/src/header/babe.rs | 4 +- lib/src/header/grandpa.rs | 8 +-- lib/src/json_rpc/service/client_main_task.rs | 6 +- .../connection/established/single_stream.rs | 8 +-- .../connection/established/substream.rs | 10 +-- lib/src/libp2p/connection/yamux.rs | 65 +++++++++---------- lib/src/libp2p/connection/yamux/header.rs | 14 ++-- lib/src/network/codec/block_request.rs | 8 +-- lib/src/sync/all.rs | 20 ++---- lib/src/sync/all_forks.rs | 11 +--- lib/src/sync/all_forks/pending_blocks.rs | 12 ++-- lib/src/transactions/light_pool/tests.rs | 8 +-- lib/src/transactions/pool/tests.rs | 4 +- lib/src/transactions/validate.rs | 6 +- lib/src/util.rs | 6 +- lib/src/verify/aura.rs | 4 +- lib/src/verify/babe.rs | 6 +- lib/src/verify/header_only.rs | 6 +- light-base/examples/basic.rs | 6 +- light-base/src/json_rpc_service.rs | 4 +- light-base/src/json_rpc_service/background.rs | 40 +++++------- light-base/src/lib.rs | 16 ++--- light-base/src/network_service.rs | 8 +-- light-base/src/runtime_service.rs | 18 ++--- light-base/src/sync_service.rs | 14 ++-- light-base/src/sync_service/parachain.rs | 15 ++--- light-base/src/sync_service/standalone.rs | 15 ++--- light-base/src/transactions_service.rs | 19 ++---- wasm-node/rust/src/lib.rs | 4 +- 44 files changed, 232 insertions(+), 277 deletions(-) diff --git a/full-node/src/consensus_service.rs b/full-node/src/consensus_service.rs index 6f2de5eb49..713f5683eb 100644 --- a/full-node/src/consensus_service.rs +++ b/full-node/src/consensus_service.rs @@ -26,7 +26,6 @@ use crate::{database_thread, jaeger_service, network_service, LogCallback, LogLevel}; -use core::num::NonZeroU32; use futures_channel::{mpsc, oneshot}; use futures_lite::FutureExt as _; use futures_util::{ @@ -56,7 +55,7 @@ use std::{ cmp, future::Future, iter, - num::{NonZeroU64, NonZeroUsize}, + num::NonZero, pin::Pin, sync::Arc, time::{Duration, Instant, SystemTime}, @@ -145,7 +144,7 @@ enum ToBackground { SubscribeAll { buffer_size: usize, // TODO: unused field - _max_finalized_pinned_blocks: NonZeroUsize, + _max_finalized_pinned_blocks: NonZero, result_tx: oneshot::Sender, }, GetSyncState { @@ -302,14 +301,14 @@ impl ConsensusService { 1024 }, max_disjoint_headers: 1024, - max_requests_per_block: NonZeroU32::new(3).unwrap(), + max_requests_per_block: NonZero::::new(3).unwrap(), download_ahead_blocks: { // Assuming a verification speed of 1k blocks/sec and a 99th download time // percentile of two second, the number of blocks to download ahead of time // in order to not block is 2000. // In practice, however, the verification speed and download speed depend on // the chain and the machine of the user. - NonZeroU32::new(2000).unwrap() + NonZero::::new(2000).unwrap() }, download_bodies: true, // We ask for all the chain-information-related storage proofs and call proofs to be @@ -416,7 +415,7 @@ impl ConsensusService { pub async fn subscribe_all( &self, buffer_size: usize, - max_finalized_pinned_blocks: NonZeroUsize, + max_finalized_pinned_blocks: NonZero, ) -> SubscribeAll { let (result_tx, result_rx) = oneshot::channel(); let _ = self @@ -1500,7 +1499,7 @@ impl SyncBackground { } => { // Before notifying the syncing of the request, clamp the number of blocks to // the number of blocks we expect to receive. - let num_blocks = NonZeroU64::new(cmp::min(num_blocks.get(), 64)).unwrap(); + let num_blocks = NonZero::::new(cmp::min(num_blocks.get(), 64)).unwrap(); let peer_id = { let info = self.sync[source_id].clone().unwrap(); @@ -1516,7 +1515,7 @@ impl SyncBackground { self.network_chain_id, network::codec::BlocksRequestConfig { start: network::codec::BlocksRequestConfigStart::Hash(first_block_hash), - desired_count: NonZeroU32::new( + desired_count: NonZero::::new( u32::try_from(num_blocks.get()).unwrap_or(u32::MAX), ) .unwrap(), diff --git a/full-node/src/jaeger_service.rs b/full-node/src/jaeger_service.rs index 1ded09ac79..d75db5fde8 100644 --- a/full-node/src/jaeger_service.rs +++ b/full-node/src/jaeger_service.rs @@ -37,8 +37,7 @@ use smol::{future, net::UdpSocket}; use smoldot::libp2p::PeerId; use std::{ - convert::TryFrom as _, future::Future, io, net::SocketAddr, num::NonZeroU128, pin::Pin, - sync::Arc, + convert::TryFrom as _, future::Future, io, net::SocketAddr, num::NonZero, pin::Pin, sync::Arc, }; /// Configuration for a [`JaegerService`]. @@ -200,10 +199,10 @@ impl JaegerService { block_hash: &[u8; 32], operation_name: impl Into, ) -> mick_jaeger::Span { - let trace_id = NonZeroU128::new(u128::from_be_bytes( + let trace_id = NonZero::::new(u128::from_be_bytes( <[u8; 16]>::try_from(&block_hash[16..]).unwrap(), )) - .unwrap_or_else(|| NonZeroU128::new(1u128).unwrap()); + .unwrap_or_else(|| NonZero::::new(1u128).unwrap()); self.traces_in.span(trace_id, operation_name) } @@ -230,7 +229,7 @@ impl JaegerService { buf[8..].copy_from_slice(&local_peer_id[local_peer_id.len() - 8..]); }; - let trace_id = NonZeroU128::new(u128::from_be_bytes(buf)).unwrap(); + let trace_id = NonZero::::new(u128::from_be_bytes(buf)).unwrap(); self.traces_in.span(trace_id, operation_name) } } diff --git a/full-node/src/json_rpc_service.rs b/full-node/src/json_rpc_service.rs index a4c64e7439..b06effde6d 100644 --- a/full-node/src/json_rpc_service.rs +++ b/full-node/src/json_rpc_service.rs @@ -27,7 +27,7 @@ use std::{ future::Future, io, mem, net::SocketAddr, - num::{NonZeroU32, NonZeroUsize}, + num::NonZero, pin::Pin, sync::{ atomic::{AtomicU32, Ordering}, @@ -149,7 +149,7 @@ impl JsonRpcService { let (virtual_client_main_task, virtual_client_io) = service::client_main_task(service::Config { max_active_subscriptions: u32::MAX, - max_pending_requests: NonZeroU32::new(u32::MAX).unwrap(), + max_pending_requests: NonZero::::new(u32::MAX).unwrap(), }); spawn_client_main_task( @@ -164,7 +164,7 @@ impl JsonRpcService { runtime_caches_service::Config { tasks_executor: config.tasks_executor.clone(), database: config.database.clone(), - num_cache_entries: NonZeroUsize::new(16).unwrap(), // TODO: configurable? + num_cache_entries: NonZero::::new(16).unwrap(), // TODO: configurable? }, )); @@ -349,7 +349,7 @@ impl JsonRpcBackground { ); let (client_main_task, io) = service::client_main_task(service::Config { max_active_subscriptions: 128, - max_pending_requests: NonZeroU32::new(64).unwrap(), + max_pending_requests: NonZero::::new(64).unwrap(), }); spawn_client_io_task( &self.tasks_executor, diff --git a/full-node/src/json_rpc_service/chain_head_subscriptions.rs b/full-node/src/json_rpc_service/chain_head_subscriptions.rs index 270165a7ee..13512d5c9a 100644 --- a/full-node/src/json_rpc_service/chain_head_subscriptions.rs +++ b/full-node/src/json_rpc_service/chain_head_subscriptions.rs @@ -26,7 +26,7 @@ use smoldot::{ }; use std::{ future::Future, - num::NonZeroUsize, + num::NonZero, pin::{self, Pin}, sync::Arc, }; @@ -77,7 +77,7 @@ pub async fn spawn_chain_head_subscription_task(config: Config) -> String { tasks_executor(Box::pin(async move { let consensus_service_subscription = config .consensus_service - .subscribe_all(32, NonZeroUsize::new(32).unwrap()) + .subscribe_all(32, NonZero::::new(32).unwrap()) .await; let mut consensus_service_subscription_new_blocks = pin::pin!(consensus_service_subscription.new_blocks); diff --git a/full-node/src/json_rpc_service/legacy_api_subscriptions.rs b/full-node/src/json_rpc_service/legacy_api_subscriptions.rs index 1f58235767..fcbbd33f2a 100644 --- a/full-node/src/json_rpc_service/legacy_api_subscriptions.rs +++ b/full-node/src/json_rpc_service/legacy_api_subscriptions.rs @@ -22,7 +22,7 @@ use smoldot::{ executor::{host::HostVmPrototype, CoreVersion}, trie, }; -use std::{collections::BTreeSet, iter, mem, num::NonZeroUsize, ops, pin::Pin, sync::Arc}; +use std::{collections::BTreeSet, iter, mem, num::NonZero, ops, pin::Pin, sync::Arc}; use crate::{consensus_service, database_thread}; @@ -58,7 +58,7 @@ impl SubscribeAllHeads { None => { let subscribe_all = self .consensus_service - .subscribe_all(32, NonZeroUsize::new(usize::MAX).unwrap()) + .subscribe_all(32, NonZero::::new(usize::MAX).unwrap()) .await; let blocks_to_unpin = iter::once(subscribe_all.finalized_block_hash) @@ -137,7 +137,7 @@ impl SubscribeFinalizedHeads { None => { let subscribe_all = self .consensus_service - .subscribe_all(32, NonZeroUsize::new(usize::MAX).unwrap()) + .subscribe_all(32, NonZero::::new(usize::MAX).unwrap()) .await; let mut pinned_blocks = HashMap::with_capacity( @@ -248,7 +248,7 @@ impl SubscribeNewHeads { if self.subscription.is_none() { let subscribe_all = self .consensus_service - .subscribe_all(32, NonZeroUsize::new(usize::MAX).unwrap()) + .subscribe_all(32, NonZero::::new(usize::MAX).unwrap()) .await; let mut pinned_blocks = HashMap::with_capacity( @@ -413,7 +413,7 @@ impl SubscribeRuntimeVersion { if self.subscription.is_none() { let subscribe_all = self .consensus_service - .subscribe_all(32, NonZeroUsize::new(usize::MAX).unwrap()) + .subscribe_all(32, NonZero::::new(usize::MAX).unwrap()) .await; let mut pinned_blocks = HashMap::with_capacity( @@ -674,7 +674,7 @@ impl SubscribeStorage { subscription @ None => { let subscribe_all = self .consensus_service - .subscribe_all(32, NonZeroUsize::new(usize::MAX).unwrap()) + .subscribe_all(32, NonZero::::new(usize::MAX).unwrap()) .await; let mut pinned_blocks_by_hash = HashMap::with_capacity( diff --git a/full-node/src/json_rpc_service/runtime_caches_service.rs b/full-node/src/json_rpc_service/runtime_caches_service.rs index 280a1e45a8..8e5fdf7ba1 100644 --- a/full-node/src/json_rpc_service/runtime_caches_service.rs +++ b/full-node/src/json_rpc_service/runtime_caches_service.rs @@ -23,7 +23,7 @@ use smol::lock::Mutex; use smoldot::{executor, trie}; use std::{ iter, - num::NonZeroUsize, + num::NonZero, pin::{self, Pin}, sync::Arc, }; @@ -37,7 +37,7 @@ pub struct Config { pub database: Arc, /// Number of entries in the cache of runtimes. - pub num_cache_entries: NonZeroUsize, + pub num_cache_entries: NonZero, } /// A running runtime caches service. diff --git a/lib/src/author/aura.rs b/lib/src/author/aura.rs index c4e61618cd..4e90ad7016 100644 --- a/lib/src/author/aura.rs +++ b/lib/src/author/aura.rs @@ -16,7 +16,7 @@ // along with this program. If not, see . use crate::header; -use core::{num::NonZeroU64, time::Duration}; +use core::{num::NonZero, time::Duration}; /// Configuration for [`next_slot_claim`]. pub struct Config<'a, TLocAuth> { @@ -25,7 +25,7 @@ pub struct Config<'a, TLocAuth> { pub now_from_unix_epoch: Duration, /// Duration, in milliseconds, of an Aura slot. - pub slot_duration: NonZeroU64, + pub slot_duration: NonZero, /// List of the Aura authorities allowed to produce a block. This is either the same as the /// ones of the current best block, or a new list if the current best block contains an diff --git a/lib/src/author/build.rs b/lib/src/author/build.rs index d70d8d2071..58a2cbf502 100644 --- a/lib/src/author/build.rs +++ b/lib/src/author/build.rs @@ -25,7 +25,7 @@ use crate::{ }; use alloc::vec::Vec; -use core::{num::NonZeroU64, time::Duration}; +use core::{num::NonZero, time::Duration}; pub use runtime::{Nibble, StorageChanges, TrieEntryVersion}; @@ -44,7 +44,7 @@ pub enum ConfigConsensus<'a, TLocAuth> { now_from_unix_epoch: Duration, /// Duration, in milliseconds, of an Aura slot. - slot_duration: NonZeroU64, + slot_duration: NonZero, /// List of the Aura authorities allowed to produce a block. This is either the same as /// the ones of the current best block, or a new list if the current best block contains diff --git a/lib/src/chain/blocks_tree.rs b/lib/src/chain/blocks_tree.rs index 6b59d92caa..c6905319e7 100644 --- a/lib/src/chain/blocks_tree.rs +++ b/lib/src/chain/blocks_tree.rs @@ -71,7 +71,7 @@ use alloc::{ sync::Arc, vec::Vec, }; -use core::{cmp, fmt, mem, num::NonZeroU64, ops, time::Duration}; +use core::{cmp, fmt, mem, num::NonZero, ops, time::Duration}; use hashbrown::HashMap; mod finality; @@ -549,7 +549,7 @@ enum FinalizedConsensus { authorities_list: Arc>, /// Duration, in milliseconds, of a slot. - slot_duration: NonZeroU64, + slot_duration: NonZero, }, Babe { /// See [`chain_information::ChainInformationConsensus::Babe::finalized_block_epoch_information`]. @@ -559,7 +559,7 @@ enum FinalizedConsensus { next_epoch_transition: Arc, /// See [`chain_information::ChainInformationConsensus::Babe::slots_per_epoch`]. - slots_per_epoch: NonZeroU64, + slots_per_epoch: NonZero, }, } diff --git a/lib/src/chain/blocks_tree/tests.rs b/lib/src/chain/blocks_tree/tests.rs index c8b80686bd..fb2e55e59f 100644 --- a/lib/src/chain/blocks_tree/tests.rs +++ b/lib/src/chain/blocks_tree/tests.rs @@ -19,7 +19,7 @@ #![cfg(test)] -use core::{num::NonZeroU64, time::Duration}; +use core::{num::NonZero, time::Duration}; use super::{Config, HeaderVerifySuccess, NonFinalizedTree}; use crate::{chain::chain_information, header}; @@ -45,7 +45,7 @@ fn polkadot_blocks_0_to_2() { digest: header::Digest::from(header::DigestRef::empty()), }), consensus: chain_information::ChainInformationConsensus::Babe { - slots_per_epoch: NonZeroU64::new(2400).unwrap(), + slots_per_epoch: NonZero::::new(2400).unwrap(), finalized_block_epoch_information: None, finalized_next_epoch_transition: Box::new( chain_information::BabeEpochInformation { @@ -119,7 +119,7 @@ fn polkadot_blocks_0_to_2() { 31, 16, 89, 116, 113, 220, 29, 39, 241, 68, 41, 90, 214, 251, 147, 60, 122, ], - weight: NonZeroU64::new(1).unwrap(), + weight: NonZero::::new(1).unwrap(), }, header::GrandpaAuthority { public_key: [ @@ -127,7 +127,7 @@ fn polkadot_blocks_0_to_2() { 200, 83, 247, 119, 25, 36, 152, 192, 146, 46, 171, 30, 157, 244, 240, 97, ], - weight: NonZeroU64::new(1).unwrap(), + weight: NonZero::::new(1).unwrap(), }, header::GrandpaAuthority { public_key: [ @@ -135,14 +135,14 @@ fn polkadot_blocks_0_to_2() { 238, 133, 10, 171, 35, 143, 208, 20, 193, 120, 118, 158, 126, 58, 155, 132, ], - weight: NonZeroU64::new(1).unwrap(), + weight: NonZero::::new(1).unwrap(), }, header::GrandpaAuthority { public_key: [ 28, 21, 28, 17, 203, 114, 51, 77, 38, 215, 7, 105, 227, 175, 123, 191, 243, 128, 26, 78, 45, 202, 43, 9, 183, 204, 224, 175, 141, 216, 19, 7, ], - weight: NonZeroU64::new(1).unwrap(), + weight: NonZero::::new(1).unwrap(), }, header::GrandpaAuthority { public_key: [ @@ -150,7 +150,7 @@ fn polkadot_blocks_0_to_2() { 25, 126, 143, 182, 250, 187, 94, 98, 34, 10, 123, 215, 95, 134, 12, 171, ], - weight: NonZeroU64::new(1).unwrap(), + weight: NonZero::::new(1).unwrap(), }, header::GrandpaAuthority { public_key: [ @@ -158,7 +158,7 @@ fn polkadot_blocks_0_to_2() { 214, 101, 29, 28, 104, 154, 13, 87, 129, 63, 151, 104, 219, 170, 222, 207, 113, ], - weight: NonZeroU64::new(1).unwrap(), + weight: NonZero::::new(1).unwrap(), }, ], finalized_scheduled_change: None, @@ -258,7 +258,7 @@ fn kusama_blocks_0_to_2() { digest: header::Digest::from(header::DigestRef::empty()), }), consensus: chain_information::ChainInformationConsensus::Babe { - slots_per_epoch: NonZeroU64::new(600).unwrap(), + slots_per_epoch: NonZero::::new(600).unwrap(), finalized_block_epoch_information: None, finalized_next_epoch_transition: Box::new( chain_information::BabeEpochInformation { @@ -332,7 +332,7 @@ fn kusama_blocks_0_to_2() { 175, 210, 16, 101, 97, 184, 25, 44, 61, 130, 24, 17, 237, 220, 133, 190, 18, ], - weight: NonZeroU64::new(1).unwrap(), + weight: NonZero::::new(1).unwrap(), }, header::GrandpaAuthority { public_key: [ @@ -340,7 +340,7 @@ fn kusama_blocks_0_to_2() { 131, 207, 56, 243, 172, 45, 253, 156, 81, 104, 213, 215, 235, 186, 216, 53, 68, ], - weight: NonZeroU64::new(1).unwrap(), + weight: NonZero::::new(1).unwrap(), }, header::GrandpaAuthority { public_key: [ @@ -348,7 +348,7 @@ fn kusama_blocks_0_to_2() { 107, 44, 125, 4, 199, 114, 119, 251, 136, 177, 195, 199, 137, 250, 100, 23, 55, ], - weight: NonZeroU64::new(1).unwrap(), + weight: NonZero::::new(1).unwrap(), }, header::GrandpaAuthority { public_key: [ @@ -356,14 +356,14 @@ fn kusama_blocks_0_to_2() { 250, 50, 20, 190, 158, 118, 105, 255, 125, 192, 150, 209, 125, 40, 107, 210, ], - weight: NonZeroU64::new(1).unwrap(), + weight: NonZero::::new(1).unwrap(), }, header::GrandpaAuthority { public_key: [ 92, 227, 13, 140, 0, 125, 10, 67, 140, 146, 195, 122, 102, 11, 119, 9, 253, 31, 243, 187, 167, 156, 108, 72, 50, 234, 65, 7, 210, 102, 224, 1, ], - weight: NonZeroU64::new(1).unwrap(), + weight: NonZero::::new(1).unwrap(), }, header::GrandpaAuthority { public_key: [ @@ -371,7 +371,7 @@ fn kusama_blocks_0_to_2() { 227, 98, 247, 250, 68, 41, 214, 101, 206, 16, 169, 218, 42, 206, 37, 76, ], - weight: NonZeroU64::new(1).unwrap(), + weight: NonZero::::new(1).unwrap(), }, ], finalized_scheduled_change: None, diff --git a/lib/src/chain/chain_information.rs b/lib/src/chain/chain_information.rs index 0a170b2d79..a5cb4ab4f1 100644 --- a/lib/src/chain/chain_information.rs +++ b/lib/src/chain/chain_information.rs @@ -41,7 +41,7 @@ use crate::header; use alloc::{boxed::Box, vec::Vec}; -use core::num::NonZeroU64; +use core::num::NonZero; pub mod build; @@ -178,13 +178,13 @@ pub enum ChainInformationConsensus { finalized_authorities_list: Vec, /// Duration, in milliseconds, of an Aura slot. - slot_duration: NonZeroU64, + slot_duration: NonZero, }, /// Chain is using the Babe consensus engine. Babe { /// Number of slots per epoch. Configured at the genesis block and never touched later. - slots_per_epoch: NonZeroU64, + slots_per_epoch: NonZero, /// Babe epoch information about the epoch the finalized block belongs to. /// @@ -498,13 +498,13 @@ pub enum ChainInformationConsensusRef<'a> { finalized_authorities_list: header::AuraAuthoritiesIter<'a>, /// See equivalent field in [`ChainInformationConsensus`]. - slot_duration: NonZeroU64, + slot_duration: NonZero, }, /// Chain is using the Babe consensus engine. Babe { /// See equivalent field in [`ChainInformationConsensus`]. - slots_per_epoch: NonZeroU64, + slots_per_epoch: NonZero, /// See equivalent field in [`ChainInformationConsensus`]. finalized_block_epoch_information: Option>, diff --git a/lib/src/chain/chain_information/build.rs b/lib/src/chain/chain_information/build.rs index c7c61be8a4..44b8ad305a 100644 --- a/lib/src/chain/chain_information/build.rs +++ b/lib/src/chain/chain_information/build.rs @@ -21,7 +21,7 @@ //! process of building the chain information of a certain finalized point of a chain. use alloc::{boxed::Box, vec::Vec}; -use core::{fmt, iter, num::NonZeroU64}; +use core::{fmt, iter, num::NonZero}; use crate::{ chain::chain_information, @@ -883,7 +883,7 @@ struct ChainInformationBuildInner { runtime_grandpa_supports_currentsetid: Option, /// Output of the call to `AuraApi_slot_duration`, if it was already made. - aura_slot_duration_call_output: Option, + aura_slot_duration_call_output: Option>, /// Output of the call to `AuraApi_authorities`, if it was already made. aura_autorities_call_output: Option>, /// Output of the call to `BabeApi_current_epoch`, if it was already made. @@ -899,10 +899,10 @@ struct ChainInformationBuildInner { } /// Decodes the output of a call to `AuraApi_slot_duration`. -fn decode_aura_slot_duration_output(bytes: &[u8]) -> Result { +fn decode_aura_slot_duration_output(bytes: &[u8]) -> Result, Error> { <[u8; 8]>::try_from(bytes) .ok() - .and_then(|b| NonZeroU64::new(u64::from_le_bytes(b))) + .and_then(|b| NonZero::::new(u64::from_le_bytes(b))) .ok_or(Error::AuraSlotDurationOutputDecode) } @@ -918,7 +918,7 @@ fn decode_aura_authorities_output( #[derive(Debug, Clone, PartialEq, Eq)] struct BabeGenesisConfiguration { - slots_per_epoch: NonZeroU64, + slots_per_epoch: NonZero, epoch0_configuration: header::BabeNextConfig, epoch0_information: header::BabeNextEpoch, } @@ -932,7 +932,7 @@ fn decode_babe_configuration_output( nom::combinator::all_consuming(nom::combinator::complete(nom::combinator::map( nom::sequence::tuple(( nom::number::streaming::le_u64, - nom::combinator::map_opt(nom::number::streaming::le_u64, NonZeroU64::new), + nom::combinator::map_opt(nom::number::streaming::le_u64, NonZero::::new), nom::number::streaming::le_u64, nom::number::streaming::le_u64, nom::combinator::flat_map(crate::util::nom_scale_compact_usize, |num_elems| { @@ -1094,7 +1094,7 @@ fn decode_grandpa_authorities_output( num_elems, nom::sequence::tuple(( nom::bytes::streaming::take(32u32), - nom::combinator::map_opt(nom::number::streaming::le_u64, NonZeroU64::new), + nom::combinator::map_opt(nom::number::streaming::le_u64, NonZero::::new), )), move || Vec::with_capacity(num_elems), |mut acc, (public_key, weight)| { @@ -1128,7 +1128,7 @@ fn decode_grandpa_current_set_id_output(bytes: &[u8]) -> Result { #[cfg(test)] mod tests { use crate::header; - use core::num::NonZeroU64; + use core::num::NonZero; #[test] fn decode_babe_epoch_output_sample_decode() { @@ -1174,7 +1174,7 @@ mod tests { assert_eq!( super::decode_babe_configuration_output(&data, true).unwrap(), super::BabeGenesisConfiguration { - slots_per_epoch: NonZeroU64::new(600).unwrap(), + slots_per_epoch: NonZero::::new(600).unwrap(), epoch0_configuration: header::BabeNextConfig { allowed_slots: header::BabeAllowedSlots::PrimaryAndSecondaryPlainSlots, c: (1, 4), diff --git a/lib/src/chain_spec.rs b/lib/src/chain_spec.rs index 79184aae25..072c5a0e2c 100644 --- a/lib/src/chain_spec.rs +++ b/lib/src/chain_spec.rs @@ -47,7 +47,7 @@ use alloc::{ string::{String, ToString as _}, vec::Vec, }; -use core::{iter, num::NonZeroU64, ops::Bound}; +use core::{iter, num::NonZero, ops::Bound}; mod light_sync_state; mod structs; @@ -504,7 +504,7 @@ impl LightSyncState { ChainInformation { finalized_block_header: Box::new(self.inner.finalized_block_header.clone()), consensus: ChainInformationConsensus::Babe { - slots_per_epoch: NonZeroU64::new(next_epoch.duration) + slots_per_epoch: NonZero::::new(next_epoch.duration) .ok_or(CheckpointToChainInformationError::InvalidBabeSlotsPerEpoch)?, finalized_block_epoch_information: Some(convert_epoch(current_epoch)), finalized_next_epoch_transition: convert_epoch(next_epoch), @@ -519,7 +519,7 @@ impl LightSyncState { .map(|authority| { Ok(crate::header::GrandpaAuthority { public_key: authority.public_key, - weight: NonZeroU64::new(authority.weight) + weight: NonZero::::new(authority.weight) .ok_or(CheckpointToChainInformationError::InvalidGrandpaAuthorityWeight)?, }) }) diff --git a/lib/src/chain_spec/light_sync_state.rs b/lib/src/chain_spec/light_sync_state.rs index 91ff0fbe4f..bf3b552688 100644 --- a/lib/src/chain_spec/light_sync_state.rs +++ b/lib/src/chain_spec/light_sync_state.rs @@ -265,7 +265,7 @@ pub struct BabeAuthority { /// Arbitrary number indicating the weight of the authority. /// /// This value can only be compared to other weight values. - // TODO: should be NonZeroU64; requires deep changes in decoding code though + // TODO: should be NonZero; requires deep changes in decoding code though pub weight: u64, } @@ -398,7 +398,7 @@ pub struct GrandpaAuthority { /// Arbitrary number indicating the weight of the authority. /// /// This value can only be compared to other weight values. - // TODO: should be NonZeroU64; requires deep changes in decoding code though + // TODO: should be NonZero; requires deep changes in decoding code though pub weight: u64, } diff --git a/lib/src/database/finalized_serialize/defs.rs b/lib/src/database/finalized_serialize/defs.rs index b5a1fb84f0..d67a426042 100644 --- a/lib/src/database/finalized_serialize/defs.rs +++ b/lib/src/database/finalized_serialize/defs.rs @@ -20,7 +20,7 @@ use crate::{chain::chain_information, header}; use alloc::{boxed::Box, vec::Vec}; -use core::{fmt, num::NonZeroU64}; +use core::{fmt, num::NonZero}; use hashbrown::HashMap; /// Error that can happen when deserializing the data. @@ -64,11 +64,11 @@ pub(super) struct SerializedChainInformationV1 { )] finalized_block_header: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] - aura_slot_duration: Option, + aura_slot_duration: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] aura_finalized_authorities: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] - babe_slots_per_epoch: Option, + babe_slots_per_epoch: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] babe_finalized_block_epoch_information: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -372,7 +372,7 @@ struct SerializedBabeAuthorityV1 { deserialize_with = "deserialize_hash32" )] public_key: [u8; 32], - weight: u64, // TODO: should be NonZeroU64; requires changing crate::header first + weight: u64, // TODO: should be NonZero; requires changing crate::header first } impl<'a> From> for SerializedBabeAuthorityV1 { @@ -452,7 +452,7 @@ struct SerializedGrandpaAuthorityV1 { deserialize_with = "deserialize_hash32" )] public_key: [u8; 32], - weight: NonZeroU64, + weight: NonZero, } impl<'a> From> for SerializedGrandpaAuthorityV1 { diff --git a/lib/src/header/babe.rs b/lib/src/header/babe.rs index df46f3b58c..2da724ed70 100644 --- a/lib/src/header/babe.rs +++ b/lib/src/header/babe.rs @@ -280,7 +280,7 @@ pub struct BabeAuthorityRef<'a> { /// Arbitrary number indicating the weight of the authority. /// /// This value can only be compared to other weight values. - // TODO: should be NonZeroU64; requires deep changes in decoding code though + // TODO: should be NonZero; requires deep changes in decoding code though pub weight: u64, } @@ -311,7 +311,7 @@ pub struct BabeAuthority { /// Arbitrary number indicating the weight of the authority. /// /// This value can only be compared to other weight values. - // TODO: should be NonZeroU64; requires deep changes in decoding code though + // TODO: should be NonZero; requires deep changes in decoding code though pub weight: u64, } diff --git a/lib/src/header/grandpa.rs b/lib/src/header/grandpa.rs index 9bca20e653..98f5b25288 100644 --- a/lib/src/header/grandpa.rs +++ b/lib/src/header/grandpa.rs @@ -19,7 +19,7 @@ use super::Error; use crate::util; use alloc::vec::Vec; -use core::{cmp, fmt, iter, num::NonZeroU64, slice}; +use core::{cmp, fmt, iter, num::NonZero, slice}; /// A consensus log item for GrandPa. #[derive(Debug, Clone, PartialEq, Eq)] @@ -369,7 +369,7 @@ pub struct GrandpaAuthorityRef<'a> { /// Arbitrary number indicating the weight of the authority. /// /// This value can only be compared to other weight values. - pub weight: NonZeroU64, + pub weight: NonZero, } impl<'a> GrandpaAuthorityRef<'a> { @@ -400,7 +400,7 @@ pub struct GrandpaAuthority { /// Arbitrary number indicating the weight of the authority. /// /// This value can only be compared to other weight values. - pub weight: NonZeroU64, + pub weight: NonZero, } impl GrandpaAuthority { @@ -523,7 +523,7 @@ fn grandpa_authority_ref< nom::combinator::map( nom::sequence::tuple(( nom::bytes::streaming::take(32u32), - nom::combinator::map_opt(nom::number::streaming::le_u64, NonZeroU64::new), + nom::combinator::map_opt(nom::number::streaming::le_u64, NonZero::::new), )), |(public_key, weight)| GrandpaAuthorityRef { public_key: TryFrom::try_from(public_key).unwrap(), diff --git a/lib/src/json_rpc/service/client_main_task.rs b/lib/src/json_rpc/service/client_main_task.rs index ca69ac0841..712245194f 100644 --- a/lib/src/json_rpc/service/client_main_task.rs +++ b/lib/src/json_rpc/service/client_main_task.rs @@ -28,7 +28,7 @@ use alloc::{ use async_lock::Mutex; use core::{ cmp, fmt, mem, - num::NonZeroU32, + num::NonZero, sync::atomic::{AtomicBool, AtomicU32, Ordering}, }; use futures_lite::FutureExt as _; @@ -95,7 +95,7 @@ struct SerializedIo { /// Maximum value that [`SerializedIo::num_requests_in_fly`] is allowed to reach. /// Beyond this, no more request should be added to [`SerializedIo::requests_queue`]. - max_requests_in_fly: NonZeroU32, + max_requests_in_fly: NonZero, /// Queue of responses. responses_queue: Mutex, @@ -149,7 +149,7 @@ pub struct Config { /// /// If this limit is reached, it is not possible to send further requests without pulling /// responses first. - pub max_pending_requests: NonZeroU32, + pub max_pending_requests: NonZero, /// Maximum number of simultaneous subscriptions allowed. Trying to create a subscription will /// be automatically rejected if this limit is reached. diff --git a/lib/src/libp2p/connection/established/single_stream.rs b/lib/src/libp2p/connection/established/single_stream.rs index 94c48b32ce..fa145a574c 100644 --- a/lib/src/libp2p/connection/established/single_stream.rs +++ b/lib/src/libp2p/connection/established/single_stream.rs @@ -59,7 +59,7 @@ use super::{ use alloc::{boxed::Box, string::String, vec::Vec}; use core::{ fmt, - num::{NonZeroU32, NonZeroUsize}, + num::NonZero, ops::{Add, Index, IndexMut, Sub}, time::Duration, }; @@ -854,9 +854,9 @@ impl ConnectionPrototype { randomness.fill_bytes(&mut seed); seed }, - max_out_data_frame_size: NonZeroU32::new(8192).unwrap(), // TODO: make configurable? - max_simultaneous_queued_pongs: NonZeroUsize::new(4).unwrap(), - max_simultaneous_rst_substreams: NonZeroUsize::new(1024).unwrap(), + max_out_data_frame_size: NonZero::::new(8192).unwrap(), // TODO: make configurable? + max_simultaneous_queued_pongs: NonZero::::new(4).unwrap(), + max_simultaneous_rst_substreams: NonZero::::new(1024).unwrap(), }); let outgoing_pings = yamux diff --git a/lib/src/libp2p/connection/established/substream.rs b/lib/src/libp2p/connection/established/substream.rs index 537ae1c453..6d1c02f638 100644 --- a/lib/src/libp2p/connection/established/substream.rs +++ b/lib/src/libp2p/connection/established/substream.rs @@ -29,7 +29,7 @@ use crate::util::leb128; use alloc::{borrow::ToOwned as _, collections::VecDeque, string::String, vec::Vec}; use core::{ fmt, mem, - num::NonZeroUsize, + num::NonZero, ops::{Add, Sub}, time::Duration, }; @@ -1013,7 +1013,7 @@ where ( Some(SubstreamInner::PingOutFailed { queued_pings }), Some(Event::PingOutError { - num_pings: NonZeroUsize::new(1).unwrap(), + num_pings: NonZero::::new(1).unwrap(), }), ) } else { @@ -1070,7 +1070,7 @@ where queued_pings, }), Some(Event::PingOutError { - num_pings: NonZeroUsize::new(1).unwrap(), + num_pings: NonZero::::new(1).unwrap(), }), ); } @@ -1149,7 +1149,7 @@ where SubstreamInner::RequestInRespond { .. } => None, SubstreamInner::PingOut { queued_pings, .. } | SubstreamInner::PingOutFailed { queued_pings, .. } => { - NonZeroUsize::new(queued_pings.len()) + NonZero::::new(queued_pings.len()) .map(|num_pings| Event::PingOutError { num_pings }) } } @@ -1502,7 +1502,7 @@ pub enum Event { /// Remote has failed to answer one or more pings. PingOutError { /// Number of pings that the remote has failed to answer. - num_pings: NonZeroUsize, + num_pings: NonZero, }, } diff --git a/lib/src/libp2p/connection/yamux.rs b/lib/src/libp2p/connection/yamux.rs index 8ff801d319..6bbce8c518 100644 --- a/lib/src/libp2p/connection/yamux.rs +++ b/lib/src/libp2p/connection/yamux.rs @@ -45,11 +45,7 @@ use alloc::{ collections::{BTreeSet, VecDeque}, vec::Vec, }; -use core::{ - cmp, fmt, mem, - num::{NonZeroU32, NonZeroU64, NonZeroUsize}, - ops, -}; +use core::{cmp, fmt, mem, num::NonZero, ops}; use rand::seq::IteratorRandom as _; use rand_chacha::{ rand_core::{RngCore as _, SeedableRng as _}, @@ -89,20 +85,20 @@ pub struct Config { /// impossible to tell. /// /// A typical value is `8192`. - pub max_out_data_frame_size: NonZeroU32, + pub max_out_data_frame_size: NonZero, /// When the remote sends a ping, we need to send out a pong. However, the remote could refuse /// to read any additional data from the socket and continue sending pings, thus increasing /// the local buffer size indefinitely. In order to protect against this attack, there exists /// a maximum number of queued pongs, after which the connection will be shut down abruptly. - pub max_simultaneous_queued_pongs: NonZeroUsize, + pub max_simultaneous_queued_pongs: NonZero, /// When the remote sends a substream, and this substream gets rejected by the API user, some /// data needs to be sent out. However, the remote could refuse reading any additional data /// and continue sending new substream requests, thus increasing the local buffer size /// indefinitely. In order to protect against this attack, there exists a maximum number of /// queued substream rejections after which the connection will be shut down abruptly. - pub max_simultaneous_rst_substreams: NonZeroUsize, + pub max_simultaneous_rst_substreams: NonZero, } /// Yamux state machine. See [the module-level documentation](..) for more information. @@ -116,11 +112,11 @@ struct YamuxInner { /// List of substreams currently open in the Yamux state machine. /// /// A `SipHasher` is used in order to avoid hash collision attacks on substream IDs. - substreams: hashbrown::HashMap, SipHasherBuild>, + substreams: hashbrown::HashMap, Substream, SipHasherBuild>, /// Subset of the content of [`YamuxInner::substreams`] that is considered "dead", meaning /// that it is returned by [`Yamux::dead_substreams`]. - dead_substreams: hashbrown::HashSet, + dead_substreams: hashbrown::HashSet, SipHasherBuild>, /// Subset of the content of [`YamuxInner::substreams`] that requires some process because /// they have data in their read buffer or their `wake_up_after` value is reached. @@ -129,7 +125,7 @@ struct YamuxInner { /// /// Keys are the time after which this substream should be processed, which can be inferior or /// equal to "now" for an immediate wake up. A key equal to `None` means "right now". - substreams_wake_up: BTreeSet<(Option, NonZeroU32)>, + substreams_wake_up: BTreeSet<(Option, NonZero)>, /// List of substreams that might want to write out additional data. Processed when it is /// possible to send out data. @@ -138,11 +134,11 @@ struct YamuxInner { /// /// Contrary to [`YamuxInner::substreams_wake_up`], the substreams in this list are processed /// only if it is possible to queue out more data for sending. - substreams_write_ready: hashbrown::HashSet, + substreams_write_ready: hashbrown::HashSet, SipHasherBuild>, /// List of window frames to send to the remote. For each substream, the amount of bytes to /// add to the window. - window_frames_to_send: hashbrown::HashMap, + window_frames_to_send: hashbrown::HashMap, NonZero, SipHasherBuild>, /// Number of substreams within [`YamuxInner::substreams`] whose [`Substream::inbound`] is /// `true`. @@ -161,12 +157,12 @@ struct YamuxInner { outgoing: Outgoing, /// See [`Config::max_out_data_frame_size`]. - max_out_data_frame_size: NonZeroU32, + max_out_data_frame_size: NonZero, /// Id of the next outgoing substream to open. /// This implementation allocates identifiers linearly. Every time a substream is open, its /// value is incremented by two. - next_outbound_substream: NonZeroU32, + next_outbound_substream: NonZero, /// Number of pings to send out that haven't been queued yet. pings_to_send: usize, @@ -179,14 +175,14 @@ struct YamuxInner { pongs_to_send: VecDeque, /// See [`Config::max_simultaneous_queued_pongs`]. - max_simultaneous_queued_pongs: NonZeroUsize, + max_simultaneous_queued_pongs: NonZero, /// List of substream IDs that have been reset locally. For each entry, a RST header should /// be sent to the remote. - rsts_to_send: VecDeque, + rsts_to_send: VecDeque>, /// See [`Config::max_simultaneous_rst_substreams`]. - max_simultaneous_rst_substreams: NonZeroUsize, + max_simultaneous_rst_substreams: NonZero, /// Source of randomness used for various purposes. randomness: ChaCha20Rng, @@ -252,7 +248,7 @@ enum Incoming { /// is still data to be received. DataFrame { /// Identifier of the substream the data belongs to. - substream_id: NonZeroU32, + substream_id: NonZero, /// Number of bytes of data remaining before the frame ends. remaining_bytes: u32, }, @@ -261,7 +257,7 @@ enum Incoming { /// is blocked waiting for the API user to accept or reject this substream. PendingIncomingSubstream { /// Identifier of the pending substream. - substream_id: NonZeroU32, + substream_id: NonZero, /// Extra local window size to give to this substream. extra_window: u32, /// If non-zero, must transition to a [`Incoming::DataFrame`]. @@ -278,7 +274,7 @@ enum Outgoing { }, PreparingDataFrame { /// Substream concerned by the data frame. Always healthy. - substream_id: NonZeroU32, + substream_id: NonZero, /// Buffers of data that the substream is producing. Does not include the Yamux header. /// Must never be empty. write_buffers: Vec>, @@ -353,9 +349,9 @@ impl Yamux { outgoing_goaway: OutgoingGoAway::NotRequired, max_out_data_frame_size: config.max_out_data_frame_size, next_outbound_substream: if config.is_initiator { - NonZeroU32::new(1).unwrap() + NonZero::::new(1).unwrap() } else { - NonZeroU32::new(2).unwrap() + NonZero::::new(2).unwrap() }, pings_to_send: 0, // We leave the initial capacity at 0, as it is likely that no ping is sent at all. @@ -640,7 +636,8 @@ where // In the rare situation where the window update doesn't fit in a `u32`, we // have to send another window frame again later. - if let Some(pending_window_increase) = NonZeroU64::new(pending_window_increase) + if let Some(pending_window_increase) = + NonZero::::new(pending_window_increase) { self.inner .window_frames_to_send @@ -1430,7 +1427,7 @@ where .unwrap_or_else(|| panic!()) .state { - let Some(bytes) = NonZeroU64::new(bytes) else { + let Some(bytes) = NonZero::::new(bytes) else { return; }; @@ -1766,17 +1763,17 @@ where /// Identifier of a substream in the context of a connection. #[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, derive_more::From)] -pub struct SubstreamId(NonZeroU32); +pub struct SubstreamId(NonZero); impl SubstreamId { /// Value that compares inferior or equal to all possible values. - pub const MIN: Self = Self(match NonZeroU32::new(1) { + pub const MIN: Self = Self(match NonZero::::new(1) { Some(v) => v, None => unreachable!(), }); /// Value that compares superior or equal to all possible values. - pub const MAX: Self = Self(match NonZeroU32::new(u32::MAX) { + pub const MAX: Self = Self(match NonZero::::new(u32::MAX) { Some(v) => v, None => unreachable!(), }); @@ -1854,7 +1851,7 @@ where outer_read_write: &'a mut ReadWrite, inner_read_write: ReadWrite, yamux: Yamux, - substream_id: NonZeroU32, + substream_id: NonZero, /// Size of the write buffers of the substream prior to its processing. write_buffers_len_before: usize, @@ -1926,18 +1923,18 @@ where // If the substream requests more data than the remote is allowed to send, send out a // window frame. This ensures that the reading can never stall due to window frames issues. - if let Some(mut missing_window_size) = NonZeroUsize::new( + if let Some(mut missing_window_size) = NonZero::::new( expected_incoming_bytes .unwrap() .saturating_sub(usize::try_from(*remote_allowed_window).unwrap_or(usize::MAX)), ) { // Don't send super tiny window frames. if missing_window_size.get() < 1024 { - missing_window_size = NonZeroUsize::new(1024).unwrap(); + missing_window_size = NonZero::::new(1024).unwrap(); } let missing_window_size = - NonZeroU64::new(u64::try_from(missing_window_size.get()).unwrap_or(u64::MAX)) + NonZero::::new(u64::try_from(missing_window_size.get()).unwrap_or(u64::MAX)) .unwrap(); self.yamux @@ -2182,10 +2179,10 @@ pub enum Error { /// Failed to decode an incoming Yamux header. HeaderDecode(header::YamuxHeaderDecodeError), /// Received a SYN flag with a substream ID that is of the same side as the local side. - InvalidInboundStreamId(NonZeroU32), + InvalidInboundStreamId(NonZero), /// Received a SYN flag with a known substream ID. #[display(fmt = "Received a SYN flag with a known substream ID")] - UnexpectedSyn(NonZeroU32), + UnexpectedSyn(NonZero), /// Remote tried to send more data than it was allowed to. CreditsExceeded, /// Number of credits allocated to the local node has overflowed. diff --git a/lib/src/libp2p/connection/yamux/header.rs b/lib/src/libp2p/connection/yamux/header.rs index 415c1e5b94..a9b5bc92e7 100644 --- a/lib/src/libp2p/connection/yamux/header.rs +++ b/lib/src/libp2p/connection/yamux/header.rs @@ -19,7 +19,7 @@ //! //! See -use core::num::NonZeroU32; +use core::num::NonZero; /// A Yamux header in its decoded form. #[derive(Debug, Copy, Clone, PartialEq, Eq)] @@ -33,7 +33,7 @@ pub enum DecodedYamuxHeader { fin: bool, /// Value of the RST flag. rst: bool, - stream_id: NonZeroU32, + stream_id: NonZero, length: u32, }, Window { @@ -45,7 +45,7 @@ pub enum DecodedYamuxHeader { fin: bool, /// Value of the RST flag. rst: bool, - stream_id: NonZeroU32, + stream_id: NonZero, length: u32, }, PingRequest { @@ -186,7 +186,7 @@ fn decode(bytes: &'_ [u8]) -> nom::IResult<&'_ [u8], DecodedYamuxHeader> { nom::sequence::tuple(( nom::bytes::streaming::tag(&[0]), flags, - nom::combinator::map_opt(nom::number::streaming::be_u32, NonZeroU32::new), + nom::combinator::map_opt(nom::number::streaming::be_u32, NonZero::::new), nom::number::streaming::be_u32, )), |(_, (syn, ack, fin, rst), stream_id, length)| DecodedYamuxHeader::Data { @@ -202,7 +202,7 @@ fn decode(bytes: &'_ [u8]) -> nom::IResult<&'_ [u8], DecodedYamuxHeader> { nom::sequence::tuple(( nom::bytes::streaming::tag(&[1]), flags, - nom::combinator::map_opt(nom::number::streaming::be_u32, NonZeroU32::new), + nom::combinator::map_opt(nom::number::streaming::be_u32, NonZero::::new), nom::number::streaming::be_u32, )), |(_, (syn, ack, fin, rst), stream_id, length)| DecodedYamuxHeader::Window { @@ -273,7 +273,7 @@ fn flags(bytes: &'_ [u8]) -> nom::IResult<&'_ [u8], (bool, bool, bool, bool)> { #[cfg(test)] mod tests { - use core::num::NonZeroU32; + use core::num::NonZero; #[test] fn decode_data_frame() { @@ -284,7 +284,7 @@ mod tests { ack: false, fin: false, rst: false, - stream_id: NonZeroU32::new(15).unwrap(), + stream_id: NonZero::::new(15).unwrap(), length: 577 } ); diff --git a/lib/src/network/codec/block_request.rs b/lib/src/network/codec/block_request.rs index 15b2c34951..ffd5797ccf 100644 --- a/lib/src/network/codec/block_request.rs +++ b/lib/src/network/codec/block_request.rs @@ -18,7 +18,7 @@ use crate::util::protobuf; use alloc::{borrow::ToOwned as _, vec::Vec}; -use core::num::NonZeroU32; +use core::num::NonZero; /// Description of a block request that can be sent to a peer. #[derive(Debug, Clone, PartialEq, Eq)] @@ -26,7 +26,7 @@ pub struct BlocksRequestConfig { /// First block that the remote must return. pub start: BlocksRequestConfigStart, /// Number of blocks to request. The remote is free to return fewer blocks than requested. - pub desired_count: NonZeroU32, + pub desired_count: NonZero, /// Whether the first block should be the one with the highest number, of the one with the /// lowest number. pub direction: BlocksRequestDirection, @@ -190,8 +190,8 @@ pub fn decode_block_request( }, desired_count: { // A missing field or a `0` field are both interpreted as "no limit". - NonZeroU32::new(decoded.max_blocks.unwrap_or(u32::MAX)) - .unwrap_or(NonZeroU32::new(u32::MAX).unwrap()) + NonZero::::new(decoded.max_blocks.unwrap_or(u32::MAX)) + .unwrap_or(NonZero::::new(u32::MAX).unwrap()) }, direction: match decoded.direction { None | Some(0) => BlocksRequestDirection::Ascending, diff --git a/lib/src/sync/all.rs b/lib/src/sync/all.rs index e86fa90b4c..dbc0ccc807 100644 --- a/lib/src/sync/all.rs +++ b/lib/src/sync/all.rs @@ -40,13 +40,7 @@ use crate::{ }; use alloc::{borrow::Cow, vec::Vec}; -use core::{ - iter, - marker::PhantomData, - num::{NonZeroU32, NonZeroU64}, - ops, - time::Duration, -}; +use core::{iter, marker::PhantomData, num::NonZero, ops, time::Duration}; pub use crate::executor::vm::ExecHint; pub use blocks_tree::{CommitVerifyError, JustificationVerifyError}; @@ -101,7 +95,7 @@ pub struct Config { /// Maximum number of simultaneous pending requests made towards the same block. /// /// See [`all_forks::Config::max_requests_per_block`] for more information. - pub max_requests_per_block: NonZeroU32, + pub max_requests_per_block: NonZero, /// Number of blocks to download ahead of the best verified block. /// @@ -112,7 +106,7 @@ pub struct Config { /// /// The ideal value here depends on the speed of blocks verification speed and latency of /// block requests. - pub download_ahead_blocks: NonZeroU32, + pub download_ahead_blocks: NonZero, /// If true, the body of a block is downloaded (if necessary) before a /// [`ProcessOne::VerifyBlock`] is generated. @@ -670,7 +664,7 @@ impl AllSync { } => DesiredRequest::BlocksRequest { first_block_height: block_number, first_block_hash: block_hash, - num_blocks: NonZeroU64::new(1).unwrap(), + num_blocks: NonZero::::new(1).unwrap(), request_headers: false, request_bodies: true, request_justification: false, @@ -1643,7 +1637,7 @@ pub enum DesiredRequest { /// /// This might be equal to `u64::MAX` in case no upper bound is required. The API /// user is responsible for clamping this value to a reasonable limit. - num_blocks: NonZeroU64, + num_blocks: NonZero, /// `True` if headers should be included in the response. request_headers: bool, /// `True` if bodies should be included in the response. @@ -1696,7 +1690,7 @@ pub enum RequestDetail { /// /// This might be equal to `u64::MAX` in case no upper bound is required. The API /// user is responsible for clamping this value to a reasonable limit. - num_blocks: NonZeroU64, + num_blocks: NonZero, /// `True` if headers should be included in the response. request_headers: bool, /// `True` if bodies should be included in the response. @@ -2448,7 +2442,7 @@ struct Shared { /// Value passed through [`Config::max_disjoint_headers`]. max_disjoint_headers: usize, /// Value passed through [`Config::max_requests_per_block`]. - max_requests_per_block: NonZeroU32, + max_requests_per_block: NonZero, /// Value passed through [`Config::block_number_bytes`]. block_number_bytes: usize, /// Value passed through [`Config::allow_unknown_consensus_engines`]. diff --git a/lib/src/sync/all_forks.rs b/lib/src/sync/all_forks.rs index 582197593d..620137348f 100644 --- a/lib/src/sync/all_forks.rs +++ b/lib/src/sync/all_forks.rs @@ -81,12 +81,7 @@ use crate::{ }; use alloc::{borrow::ToOwned as _, boxed::Box, vec::Vec}; -use core::{ - cmp, mem, - num::{NonZeroU32, NonZeroU64}, - ops, - time::Duration, -}; +use core::{cmp, mem, num::NonZero, ops, time::Duration}; mod disjoint; mod pending_blocks; @@ -160,7 +155,7 @@ pub struct Config { /// because of malicious sources. /// /// The higher the value, the more bandwidth is potentially wasted. - pub max_requests_per_block: NonZeroU32, + pub max_requests_per_block: NonZero, /// If true, the body of a block is downloaded (if necessary) before a /// [`ProcessOne::BlockVerify`] is generated. @@ -696,7 +691,7 @@ impl AllForksSync { RequestParams { first_block_hash: *block_hash, first_block_height: block_height, - num_blocks: NonZeroU64::new(1).unwrap(), + num_blocks: NonZero::::new(1).unwrap(), }, ) }) diff --git a/lib/src/sync/all_forks/pending_blocks.rs b/lib/src/sync/all_forks/pending_blocks.rs index 0f1fc9eb35..1982fc9872 100644 --- a/lib/src/sync/all_forks/pending_blocks.rs +++ b/lib/src/sync/all_forks/pending_blocks.rs @@ -91,11 +91,7 @@ use super::{disjoint, sources}; use alloc::{collections::BTreeSet, vec::Vec}; -use core::{ - iter, - num::{NonZeroU32, NonZeroU64}, - ops, -}; +use core::{iter, num::NonZero, ops}; pub use disjoint::TreeRoot; pub use sources::SourceId; @@ -129,7 +125,7 @@ pub struct Config { /// because of malicious sources. /// /// The higher the value, the more bandwidth is potentially wasted. - pub max_requests_per_block: NonZeroU32, + pub max_requests_per_block: NonZero, } /// State of a block in the data structure. @@ -1069,7 +1065,7 @@ impl PendingBlocks { request_params: RequestParams { first_block_hash: *unknown_block_hash, first_block_height: unknown_block_height, - num_blocks: NonZeroU64::new(if download_many { + num_blocks: NonZero::::new(if download_many { unknown_block_height - self.sources.finalized_block_height() } else { 1 @@ -1125,5 +1121,5 @@ pub struct RequestParams { /// /// Note that this is only an indication, and the source is free to give fewer blocks /// than requested. - pub num_blocks: NonZeroU64, + pub num_blocks: NonZero, } diff --git a/lib/src/transactions/light_pool/tests.rs b/lib/src/transactions/light_pool/tests.rs index 860e3c6445..9fe2163ee2 100644 --- a/lib/src/transactions/light_pool/tests.rs +++ b/lib/src/transactions/light_pool/tests.rs @@ -17,7 +17,7 @@ #![cfg(test)] -use core::num::NonZeroU64; +use core::num::NonZero; use super::super::validate; use super::{Config, LightPool}; @@ -166,7 +166,7 @@ fn longevity_works_non_finalized() { tx_id, &[1; 32], Ok(validate::ValidTransaction { - longevity: NonZeroU64::new(2).unwrap(), + longevity: NonZero::::new(2).unwrap(), priority: 1, propagate: true, provides: Vec::new(), @@ -226,7 +226,7 @@ fn longevity_works_finalized() { tx_id, &[1; 32], Ok(validate::ValidTransaction { - longevity: NonZeroU64::new(2).unwrap(), + longevity: NonZero::::new(2).unwrap(), priority: 1, propagate: true, provides: Vec::new(), @@ -279,7 +279,7 @@ fn longevity_works_finalized_base() { tx_id, &[0; 32], Ok(validate::ValidTransaction { - longevity: NonZeroU64::new(2).unwrap(), + longevity: NonZero::::new(2).unwrap(), priority: 1, propagate: true, provides: Vec::new(), diff --git a/lib/src/transactions/pool/tests.rs b/lib/src/transactions/pool/tests.rs index 4b954bba3b..e8df03937b 100644 --- a/lib/src/transactions/pool/tests.rs +++ b/lib/src/transactions/pool/tests.rs @@ -17,7 +17,7 @@ #![cfg(test)] -use core::num::NonZeroU64; +use core::num::NonZero; use super::{Config, Pool, ValidTransaction}; @@ -38,7 +38,7 @@ fn basic_includable() { tx_id, 1, ValidTransaction { - longevity: NonZeroU64::new(16).unwrap(), + longevity: NonZero::::new(16).unwrap(), priority: 0, propagate: true, provides: Vec::new(), diff --git a/lib/src/transactions/validate.rs b/lib/src/transactions/validate.rs index 5d6fdb2e5a..de53f06259 100644 --- a/lib/src/transactions/validate.rs +++ b/lib/src/transactions/validate.rs @@ -20,7 +20,7 @@ use crate::util; use alloc::{borrow::ToOwned as _, vec::Vec}; -use core::{iter, num::NonZeroU64}; +use core::{iter, num::NonZero}; mod tests; @@ -93,7 +93,7 @@ pub struct ValidTransaction { /// > after a certain number of blocks. In that case, the longevity returned by the /// > validation function will be at most this number of blocks. The concept of /// > mortal transactions, however, is not relevant from the client's perspective. - pub longevity: NonZeroU64, + pub longevity: NonZero, /// A flag indicating whether the transaction should be propagated to other peers. /// @@ -258,7 +258,7 @@ fn valid_transaction(bytes: &[u8]) -> nom::IResult<&[u8], ValidTransaction> { tags, // TODO: maybe show by strong typing the fact that the provide tags are never empty nom::combinator::verify(tags, |provides: &Vec>| !provides.is_empty()), - nom::combinator::map_opt(nom::number::streaming::le_u64, NonZeroU64::new), + nom::combinator::map_opt(nom::number::streaming::le_u64, NonZero::::new), util::nom_bool_decode, )), |(priority, requires, provides, longevity, propagate)| ValidTransaction { diff --git a/lib/src/util.rs b/lib/src/util.rs index d0b421b80d..9d36da7e85 100644 --- a/lib/src/util.rs +++ b/lib/src/util.rs @@ -167,7 +167,7 @@ macro_rules! decode_scale_compact { 0b01 => { if bytes.len() < 2 { return Err(nom::Err::Incomplete(nom::Needed::Size( - core::num::NonZeroUsize::new(2 - bytes.len()).unwrap(), + core::num::NonZero::::new(2 - bytes.len()).unwrap(), ))); } @@ -188,7 +188,7 @@ macro_rules! decode_scale_compact { 0b10 => { if bytes.len() < 4 { return Err(nom::Err::Incomplete(nom::Needed::Size( - core::num::NonZeroUsize::new(4 - bytes.len()).unwrap(), + core::num::NonZero::::new(4 - bytes.len()).unwrap(), ))); } @@ -227,7 +227,7 @@ macro_rules! decode_scale_compact { if bytes.len() < num_bytes + 1 { return Err(nom::Err::Incomplete(nom::Needed::Size( - core::num::NonZeroUsize::new(num_bytes + 1 - bytes.len()).unwrap(), + core::num::NonZero::::new(num_bytes + 1 - bytes.len()).unwrap(), ))); } diff --git a/lib/src/verify/aura.rs b/lib/src/verify/aura.rs index cdb7958f9d..3dd661ab76 100644 --- a/lib/src/verify/aura.rs +++ b/lib/src/verify/aura.rs @@ -48,7 +48,7 @@ use crate::header; use alloc::vec::Vec; -use core::{num::NonZeroU64, time::Duration}; +use core::{num::NonZero, time::Duration}; /// Configuration for [`verify_header`]. pub struct VerifyConfig<'a, TAuthList> { @@ -77,7 +77,7 @@ pub struct VerifyConfig<'a, TAuthList> { /// Duration of a slot in milliseconds. /// Can be found by calling the `AuraApi_slot_duration` runtime function. - pub slot_duration: NonZeroU64, + pub slot_duration: NonZero, } /// Information yielded back after successfully verifying a block. diff --git a/lib/src/verify/babe.rs b/lib/src/verify/babe.rs index 4d410d0162..89367d9f50 100644 --- a/lib/src/verify/babe.rs +++ b/lib/src/verify/babe.rs @@ -131,7 +131,7 @@ use crate::{chain::chain_information, header}; -use core::{num::NonZeroU64, time::Duration}; +use core::{num::NonZero, time::Duration}; /// Configuration for [`verify_header`]. pub struct VerifyConfig<'a> { @@ -154,7 +154,7 @@ pub struct VerifyConfig<'a> { pub now_from_unix_epoch: Duration, /// Number of slots per epoch in the Babe configuration. - pub slots_per_epoch: NonZeroU64, + pub slots_per_epoch: NonZero, /// Epoch the parent block belongs to. Must be `None` if and only if the parent block's number /// is 0, as block #0 doesn't belong to any epoch. @@ -558,7 +558,7 @@ macro_rules! gen_calculate_primary_threshold { fn $name( c: (u64, u64), authorities_weights: impl Iterator, - authority_weight: u64, // TODO: use a NonZeroU64 once crate::header also has weights that use NonZeroU64 + authority_weight: u64, // TODO: use a NonZero once crate::header also has weights that use NonZero ) -> u128 { // We import `libm` no matter what, so that there's no warning about an unused // dependency. diff --git a/lib/src/verify/header_only.rs b/lib/src/verify/header_only.rs index ecf3a9db05..8c9e70446f 100644 --- a/lib/src/verify/header_only.rs +++ b/lib/src/verify/header_only.rs @@ -22,7 +22,7 @@ use crate::{ }; use alloc::vec::Vec; -use core::{num::NonZeroU64, time::Duration}; +use core::{num::NonZero, time::Duration}; /// Configuration for a block verification. pub struct Config<'a> { @@ -73,7 +73,7 @@ pub enum ConfigConsensus<'a> { /// Duration of a slot in milliseconds. /// Can be found by calling the `AuraApi_slot_duration` runtime function. - slot_duration: NonZeroU64, + slot_duration: NonZero, /// Time elapsed since [the Unix Epoch](https://en.wikipedia.org/wiki/Unix_time) (i.e. /// 00:00:00 UTC on 1 January 1970), ignoring leap seconds. @@ -83,7 +83,7 @@ pub enum ConfigConsensus<'a> { /// Chain is using the Babe consensus engine. Babe { /// Number of slots per epoch in the Babe configuration. - slots_per_epoch: NonZeroU64, + slots_per_epoch: NonZero, /// Epoch the parent block belongs to. Must be `None` if and only if the parent block's /// number is 0, as block #0 doesn't belong to any epoch. diff --git a/light-base/examples/basic.rs b/light-base/examples/basic.rs index 80d762c8fb..062f42d7ed 100644 --- a/light-base/examples/basic.rs +++ b/light-base/examples/basic.rs @@ -15,7 +15,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use core::{iter, num::NonZeroU32}; +use core::{iter, num::NonZero}; use futures_lite::FutureExt as _; fn main() { @@ -54,7 +54,7 @@ fn main() { // This parameter is necessary for situations where the JSON-RPC clients aren't // trusted. If you control all the requests that are sent out and don't want them // to fail, feel free to pass `u32::MAX`. - max_pending_requests: NonZeroU32::new(128).unwrap(), + max_pending_requests: NonZero::::new(128).unwrap(), // Maximum number of active subscriptions before new ones are automatically // rejected. Any JSON-RPC request that causes the server to generate notifications // counts as a subscription. @@ -97,7 +97,7 @@ fn main() { // These options are the same as above. specification: include_str!("../../demo-chain-specs/polkadot-asset-hub.json"), json_rpc: smoldot_light::AddChainConfigJsonRpc::Enabled { - max_pending_requests: NonZeroU32::new(128).unwrap(), + max_pending_requests: NonZero::::new(128).unwrap(), max_subscriptions: 1024, }, database_content: "", diff --git a/light-base/src/json_rpc_service.rs b/light-base/src/json_rpc_service.rs index 6efb32e367..6d95e31c09 100644 --- a/light-base/src/json_rpc_service.rs +++ b/light-base/src/json_rpc_service.rs @@ -51,7 +51,7 @@ use alloc::{ string::{String, ToString as _}, sync::Arc, }; -use core::{num::NonZeroU32, pin::Pin}; +use core::{num::NonZero, pin::Pin}; use futures_lite::StreamExt as _; /// Configuration for [`service()`]. @@ -72,7 +72,7 @@ pub struct Config { /// the client. // TODO: unused at the moment #[allow(unused)] - pub max_pending_requests: NonZeroU32, + pub max_pending_requests: NonZero, /// Maximum number of active subscriptions. Any additional subscription will be immediately /// rejected. diff --git a/light-base/src/json_rpc_service/background.rs b/light-base/src/json_rpc_service/background.rs index 4603c9d408..6597745f72 100644 --- a/light-base/src/json_rpc_service/background.rs +++ b/light-base/src/json_rpc_service/background.rs @@ -32,12 +32,7 @@ use alloc::{ vec, vec::Vec, }; -use core::{ - iter, mem, - num::{NonZeroU32, NonZeroUsize}, - pin::Pin, - time::Duration, -}; +use core::{iter, mem, num::NonZero, pin::Pin, time::Duration}; use futures_lite::{FutureExt as _, StreamExt as _}; use futures_util::{future, stream}; use rand_chacha::{ @@ -539,19 +534,19 @@ pub(super) async fn run( responses_tx, multistage_requests_to_advance: VecDeque::new(), block_headers_cache: lru::LruCache::with_hasher( - NonZeroUsize::new(32).unwrap_or_else(|| unreachable!()), + NonZero::::new(32).unwrap_or_else(|| unreachable!()), Default::default(), ), best_block_hash_pending: Vec::new(), pending_get_finalized_head: Vec::new(), block_headers_pending: hashbrown::HashMap::with_capacity_and_hasher(0, Default::default()), block_runtimes_cache: lru::LruCache::with_hasher( - NonZeroUsize::new(32).unwrap_or_else(|| unreachable!()), + NonZero::::new(32).unwrap_or_else(|| unreachable!()), Default::default(), ), block_runtimes_pending: hashbrown::HashMap::with_capacity_and_hasher(0, Default::default()), state_get_keys_paged_cache: lru::LruCache::with_hasher( - NonZeroUsize::new(2).unwrap(), + NonZero::::new(2).unwrap(), util::SipHasherBuild::new({ let mut seed = [0; 16]; config.platform.fill_random_bytes(&mut seed); @@ -1760,7 +1755,7 @@ pub(super) async fn run( }, 3, Duration::from_secs(20), - NonZeroU32::new(2).unwrap(), + NonZero::::new(2).unwrap(), ); // Allocate an operation ID, update the local state, and notify the @@ -1935,7 +1930,7 @@ pub(super) async fn run( call_parameters, 3, Duration::from_secs(20), - NonZeroU32::new(2).unwrap(), + NonZero::::new(2).unwrap(), ) .await } @@ -2128,7 +2123,7 @@ pub(super) async fn run( storage_operations.into_iter(), 3, Duration::from_secs(20), - NonZeroU32::new(2).unwrap(), + NonZero::::new(2).unwrap(), ); let operation_id = { @@ -2269,7 +2264,8 @@ pub(super) async fn run( subscription: runtime_service .subscribe_all( 32, - NonZeroUsize::new(32).unwrap_or_else(|| unreachable!()), + NonZero::::new(32) + .unwrap_or_else(|| unreachable!()), ) .await, } @@ -2883,7 +2879,7 @@ pub(super) async fn run( }, 3, Duration::from_secs(8), - NonZeroU32::new(1).unwrap(), + NonZero::::new(1).unwrap(), ) .await } else { @@ -2897,7 +2893,7 @@ pub(super) async fn run( }, 3, Duration::from_secs(8), - NonZeroU32::new(1).unwrap(), + NonZero::::new(1).unwrap(), ) .await }; @@ -3002,7 +2998,7 @@ pub(super) async fn run( }, 3, Duration::from_secs(5), - NonZeroU32::new(1).unwrap_or_else(|| unreachable!()), + NonZero::::new(1).unwrap_or_else(|| unreachable!()), ); let block_number_bytes = me.runtime_service.block_number_bytes(); Box::pin(async move { @@ -3162,7 +3158,7 @@ pub(super) async fn run( parameters_vectored, 3, Duration::from_secs(5), - NonZeroU32::new(1).unwrap_or_else(|| unreachable!()), + NonZero::::new(1).unwrap_or_else(|| unreachable!()), ) .await, } @@ -3220,7 +3216,7 @@ pub(super) async fn run( .into_iter(), 3, Duration::from_secs(20), - NonZeroU32::new(1).unwrap(), + NonZero::::new(1).unwrap(), ) .advance() .await; @@ -3509,7 +3505,7 @@ pub(super) async fn run( storage_request, 3, Duration::from_secs(10), - NonZeroU32::new(1).unwrap_or_else(|| unreachable!()), + NonZero::::new(1).unwrap_or_else(|| unreachable!()), ); me.background_tasks.push(Box::pin(async move { @@ -4576,7 +4572,7 @@ pub(super) async fn run( let mut pinned_blocks = hashbrown::HashMap::with_capacity_and_hasher(32, Default::default()); let mut finalized_and_pruned_lru = lru::LruCache::with_hasher( - NonZeroUsize::new(32).unwrap(), + NonZero::::new(32).unwrap(), fnv::FnvBuildHasher::default(), ); @@ -4667,7 +4663,7 @@ pub(super) async fn run( runtime_service .subscribe_all( 32, - NonZeroUsize::new(usize::MAX).unwrap_or_else(|| unreachable!()), + NonZero::::new(usize::MAX).unwrap_or_else(|| unreachable!()), ) .await })); @@ -5464,7 +5460,7 @@ pub(super) async fn run( }), 4, Duration::from_secs(12), - NonZeroU32::new(2).unwrap(), + NonZero::::new(2).unwrap(), ) .advance() .await; diff --git a/light-base/src/lib.rs b/light-base/src/lib.rs index a7f67be68a..c7bd5e1a96 100644 --- a/light-base/src/lib.rs +++ b/light-base/src/lib.rs @@ -86,7 +86,7 @@ extern crate alloc; use alloc::{borrow::ToOwned as _, boxed::Box, format, string::String, sync::Arc, vec, vec::Vec}; -use core::{num::NonZeroU32, ops, time::Duration}; +use core::{num::NonZero, ops, time::Duration}; use hashbrown::{hash_map::Entry, HashMap}; use itertools::Itertools as _; use platform::PlatformRef; @@ -162,7 +162,7 @@ pub enum AddChainConfigJsonRpc { /// completely reasonable. /// /// A typical value is 128. - max_pending_requests: NonZeroU32, + max_pending_requests: NonZero, /// Maximum number of active subscriptions that can be started through JSON-RPC functions. /// Any request that causes the JSON-RPC server to generate notifications counts as a @@ -278,7 +278,7 @@ struct RunningChain { /// Number of elements in [`Client::public_api_chains`] that reference this chain. If this /// number reaches `0`, the [`RunningChain`] should be destroyed. - num_references: NonZeroU32, + num_references: NonZero, } struct ChainServices { @@ -866,7 +866,7 @@ impl Client { let entry = entry.insert(RunningChain { services, log_name, - num_references: NonZeroU32::new(1).unwrap(), + num_references: NonZero::::new(1).unwrap(), }); (&mut entry.services, &entry.log_name) @@ -1010,7 +1010,7 @@ impl Client { chains_by_key.remove(&removed_chain.key); } else { running_chain.num_references = - NonZeroU32::new(running_chain.num_references.get() - 1).unwrap(); + NonZero::::new(running_chain.num_references.get() - 1).unwrap(); } self.public_api_chains.shrink_to_fit(); @@ -1288,9 +1288,9 @@ fn start_services( sync_service: sync_service.clone(), runtime_service: runtime_service.clone(), network_service: network_service_chain.clone(), - max_pending_transactions: NonZeroU32::new(64).unwrap(), - max_concurrent_downloads: NonZeroU32::new(3).unwrap(), - max_concurrent_validations: NonZeroU32::new(2).unwrap(), + max_pending_transactions: NonZero::::new(64).unwrap(), + max_concurrent_downloads: NonZero::::new(3).unwrap(), + max_concurrent_validations: NonZero::::new(2).unwrap(), }, )); diff --git a/light-base/src/network_service.rs b/light-base/src/network_service.rs index 4b8c475f27..b17e8fe419 100644 --- a/light-base/src/network_service.rs +++ b/light-base/src/network_service.rs @@ -54,7 +54,7 @@ use alloc::{ sync::Arc, vec::{self, Vec}, }; -use core::{cmp, mem, num::NonZeroUsize, pin::Pin, time::Duration}; +use core::{cmp, mem, num::NonZero, pin::Pin, time::Duration}; use futures_channel::oneshot; use futures_lite::FutureExt as _; use futures_util::{future, stream, StreamExt as _}; @@ -245,7 +245,7 @@ impl NetworkService { log_name: config.log_name, block_number_bytes: config.block_number_bytes, num_out_slots: config.num_out_slots, - num_references: NonZeroUsize::new(1).unwrap(), + num_references: NonZero::::new(1).unwrap(), next_discovery_period: Duration::from_secs(2), next_discovery_when: self.platform.now(), }, @@ -842,7 +842,7 @@ struct Chain { log_name: String, // TODO: this field is a hack due to the fact that `add_chain` can't be `async`; should eventually be fixed after a lib.rs refactor - num_references: NonZeroUsize, + num_references: NonZero, /// See [`ConfigChain::block_number_bytes`]. // TODO: redundant with ChainNetwork? since we might not need to know this in the future i'm reluctant to add a getter to ChainNetwork @@ -1167,7 +1167,7 @@ async fn background_task(mut task: BackgroundTask) { } WakeUpReason::MessageForChain(chain_id, ToBackgroundChain::RemoveChain) => { if let Some(new_ref) = - NonZeroUsize::new(task.network[chain_id].num_references.get() - 1) + NonZero::::new(task.network[chain_id].num_references.get() - 1) { task.network[chain_id].num_references = new_ref; continue; diff --git a/light-base/src/runtime_service.rs b/light-base/src/runtime_service.rs index b753950778..c3f04c7dba 100644 --- a/light-base/src/runtime_service.rs +++ b/light-base/src/runtime_service.rs @@ -66,13 +66,7 @@ use alloc::{ vec::Vec, }; use async_lock::Mutex; -use core::{ - cmp, iter, mem, - num::{NonZeroU32, NonZeroUsize}, - ops, - pin::Pin, - time::Duration, -}; +use core::{cmp, iter, mem, num::NonZero, ops, pin::Pin, time::Duration}; use futures_channel::oneshot; use futures_lite::FutureExt as _; use futures_util::{future, stream, Stream, StreamExt as _}; @@ -182,7 +176,7 @@ impl RuntimeService { pub async fn subscribe_all( &self, buffer_size: usize, - max_pinned_blocks: NonZeroUsize, + max_pinned_blocks: NonZero, ) -> SubscribeAll { loop { let (result_tx, result_rx) = oneshot::channel(); @@ -313,7 +307,7 @@ impl RuntimeService { parameters_vectored: Vec, total_attempts: u32, timeout_per_request: Duration, - max_parallel: NonZeroU32, + max_parallel: NonZero, ) -> Result { let (result_tx, result_rx) = oneshot::channel(); @@ -721,14 +715,14 @@ enum ToBackground { parameters_vectored: Vec, total_attempts: u32, timeout_per_request: Duration, - _max_parallel: NonZeroU32, + _max_parallel: NonZero, }, } struct ToBackgroundSubscribeAll { result_tx: oneshot::Sender>, buffer_size: usize, - max_pinned_blocks: NonZeroUsize, + max_pinned_blocks: NonZero, } #[derive(Clone)] @@ -2997,7 +2991,7 @@ fn download_runtime( .into_iter(), 3, Duration::from_secs(20), - NonZeroU32::new(3).unwrap(), + NonZero::::new(3).unwrap(), ) .advance() .await; diff --git a/light-base/src/sync_service.rs b/light-base/src/sync_service.rs index b78288d8b0..8753ef36a3 100644 --- a/light-base/src/sync_service.rs +++ b/light-base/src/sync_service.rs @@ -32,7 +32,7 @@ use alloc::{ borrow::ToOwned as _, boxed::Box, collections::VecDeque, format, string::String, sync::Arc, vec::Vec, }; -use core::{cmp, fmt, future::Future, mem, num::NonZeroU32, pin::Pin, time::Duration}; +use core::{cmp, fmt, future::Future, mem, num::NonZero, pin::Pin, time::Duration}; use futures_channel::oneshot; use rand::seq::IteratorRandom as _; use rand_chacha::rand_core::SeedableRng as _; @@ -316,12 +316,12 @@ impl SyncService { fields: codec::BlocksRequestFields, total_attempts: u32, timeout_per_request: Duration, - _max_parallel: NonZeroU32, + _max_parallel: NonZero, ) -> Result { // TODO: better error? let request_config = codec::BlocksRequestConfig { start: codec::BlocksRequestConfigStart::Hash(hash), - desired_count: NonZeroU32::new(1).unwrap(), + desired_count: NonZero::::new(1).unwrap(), direction: codec::BlocksRequestDirection::Ascending, fields: fields.clone(), }; @@ -365,12 +365,12 @@ impl SyncService { fields: codec::BlocksRequestFields, total_attempts: u32, timeout_per_request: Duration, - _max_parallel: NonZeroU32, + _max_parallel: NonZero, ) -> Result { // TODO: better error? let request_config = codec::BlocksRequestConfig { start: codec::BlocksRequestConfigStart::Hash(hash), - desired_count: NonZeroU32::new(1).unwrap(), + desired_count: NonZero::::new(1).unwrap(), direction: codec::BlocksRequestDirection::Ascending, fields: fields.clone(), }; @@ -424,7 +424,7 @@ impl SyncService { requests: impl Iterator, total_attempts: u32, timeout_per_request: Duration, - max_parallel: NonZeroU32, + max_parallel: NonZero, ) -> StorageQuery { let total_attempts = usize::try_from(total_attempts).unwrap_or(usize::MAX); @@ -578,7 +578,7 @@ pub struct StorageQuery { /// How long to wait for a response to the request. timeout_per_request: Duration, // TODO: value presently ignored - _max_parallel: NonZeroU32, + _max_parallel: NonZero, /// Non-fatal errors that have happened in the network requests. outcome_errors: Vec, /// List of responses that are available to yield. diff --git a/light-base/src/sync_service/parachain.rs b/light-base/src/sync_service/parachain.rs index 63e70fe8bb..435bbe88aa 100644 --- a/light-base/src/sync_service/parachain.rs +++ b/light-base/src/sync_service/parachain.rs @@ -19,12 +19,7 @@ use super::ToBackground; use crate::{log, network_service, platform::PlatformRef, runtime_service, util}; use alloc::{borrow::ToOwned as _, boxed::Box, format, string::String, sync::Arc, vec::Vec}; -use core::{ - mem, - num::{NonZeroU32, NonZeroUsize}, - pin::Pin, - time::Duration, -}; +use core::{mem, num::NonZero, pin::Pin, time::Duration}; use futures_lite::FutureExt as _; use futures_util::{future, stream, StreamExt as _}; use hashbrown::HashMap; @@ -66,7 +61,7 @@ pub(super) async fn start_parachain( let relay_chain_sync = relay_chain_sync.clone(); Box::pin(async move { relay_chain_sync - .subscribe_all(32, NonZeroUsize::new(usize::MAX).unwrap()) + .subscribe_all(32, NonZero::::new(usize::MAX).unwrap()) .await }) }, @@ -878,7 +873,7 @@ impl ParachainBackgroundTask { let relay_chain_sync = self.relay_chain_sync.clone(); Box::pin(async move { relay_chain_sync - .subscribe_all(32, NonZeroUsize::new(usize::MAX).unwrap()) + .subscribe_all(32, NonZero::::new(usize::MAX).unwrap()) .await }) }, @@ -950,7 +945,7 @@ impl ParachainBackgroundTask { let relay_chain_sync = self.relay_chain_sync.clone(); Box::pin(async move { relay_chain_sync - .subscribe_all(32, NonZeroUsize::new(usize::MAX).unwrap()) + .subscribe_all(32, NonZero::::new(usize::MAX).unwrap()) .await }) }, @@ -1330,7 +1325,7 @@ async fn fetch_parahead( }), 6, Duration::from_secs(10), - NonZeroU32::new(2).unwrap(), + NonZero::::new(2).unwrap(), ) .await .map_err(ParaheadError::RuntimeCall)?; diff --git a/light-base/src/sync_service/standalone.rs b/light-base/src/sync_service/standalone.rs index 927445d86d..c5bacf50e7 100644 --- a/light-base/src/sync_service/standalone.rs +++ b/light-base/src/sync_service/standalone.rs @@ -29,12 +29,7 @@ use alloc::{ sync::Arc, vec::Vec, }; -use core::{ - cmp, iter, - num::{NonZeroU32, NonZeroU64}, - pin::Pin, - time::Duration, -}; +use core::{cmp, iter, num::NonZero, pin::Pin, time::Duration}; use futures_lite::FutureExt as _; use futures_util::{future, stream, FutureExt as _, StreamExt as _}; use hashbrown::HashMap; @@ -74,7 +69,7 @@ pub(super) async fn start_standalone_chain( 1024 }, max_disjoint_headers: 1024, - max_requests_per_block: NonZeroU32::new(3).unwrap(), + max_requests_per_block: NonZero::::new(3).unwrap(), download_ahead_blocks: { // Verifying a block mostly consists in: // @@ -89,7 +84,7 @@ pub(super) async fn start_standalone_chain( // Assuming a maximum verification speed of 5k blocks/sec and a 95% latency of one // second, the number of blocks to download ahead of time in order to not block // is 5k. - NonZeroU32::new(5000).unwrap() + NonZero::::new(5000).unwrap() }, download_bodies: false, download_all_chain_information_storage_proofs: false, @@ -1165,7 +1160,7 @@ pub(super) async fn start_standalone_chain( // This constant corresponds to the maximum number of blocks that nodes will answer // in one request. If this constant happens to be inaccurate, everything will still // work but less efficiently. - let num_blocks = NonZeroU64::new(cmp::min(64, num_blocks.get())).unwrap(); + let num_blocks = NonZero::::new(cmp::min(64, num_blocks.get())).unwrap(); let peer_id = sync[source_id].0.clone(); // TODO: why does this require cloning? weird borrow chk issue @@ -1173,7 +1168,7 @@ pub(super) async fn start_standalone_chain( peer_id, network::codec::BlocksRequestConfig { start: network::codec::BlocksRequestConfigStart::Hash(first_block_hash), - desired_count: NonZeroU32::new( + desired_count: NonZero::::new( u32::try_from(num_blocks.get()).unwrap_or(u32::MAX), ) .unwrap(), diff --git a/light-base/src/transactions_service.rs b/light-base/src/transactions_service.rs index ec76b901ea..1ae88c9c14 100644 --- a/light-base/src/transactions_service.rs +++ b/light-base/src/transactions_service.rs @@ -77,12 +77,7 @@ use alloc::{ sync::Arc, vec::Vec, }; -use core::{ - cmp, iter, - num::{NonZeroU32, NonZeroUsize}, - pin, - time::Duration, -}; +use core::{cmp, iter, num::NonZero, pin, time::Duration}; use futures_channel::oneshot; use futures_lite::FutureExt as _; use futures_util::stream::FuturesUnordered; @@ -120,16 +115,16 @@ pub struct Config { /// Maximum number of pending transactions allowed in the service. /// /// Any extra transaction will lead to [`DropReason::MaxPendingTransactionsReached`]. - pub max_pending_transactions: NonZeroU32, + pub max_pending_transactions: NonZero, /// Maximum number of block body downloads that can be performed in parallel. /// /// > **Note**: This is the maximum number of *blocks* whose body is being download, not the /// > number of block requests emitted on the network. - pub max_concurrent_downloads: NonZeroU32, + pub max_concurrent_downloads: NonZero, /// Maximum number of transaction validations that can be performed in parallel. - pub max_concurrent_validations: NonZeroU32, + pub max_concurrent_validations: NonZero, } /// See [the module-level documentation](..). @@ -459,7 +454,7 @@ async fn background_task( // malicious. worker .runtime_service - .subscribe_all(32, NonZeroUsize::new(usize::MAX).unwrap()) + .subscribe_all(32, NonZero::::new(usize::MAX).unwrap()) .await, ) }; @@ -728,7 +723,7 @@ async fn background_task( }, 3, Duration::from_secs(8), - NonZeroU32::new(3).unwrap(), + NonZero::::new(3).unwrap(), ); Box::pin(async move { @@ -1497,7 +1492,7 @@ async fn validate_transaction( }), 3, Duration::from_secs(8), - NonZeroU32::new(1).unwrap(), + NonZero::::new(1).unwrap(), ); let success = match runtime_call_future.await { diff --git a/wasm-node/rust/src/lib.rs b/wasm-node/rust/src/lib.rs index 89be8e7994..9cf6f18854 100644 --- a/wasm-node/rust/src/lib.rs +++ b/wasm-node/rust/src/lib.rs @@ -31,7 +31,7 @@ use alloc::{ vec::Vec, }; use async_lock::Mutex; -use core::{num::NonZeroU32, pin::Pin, str, task}; +use core::{num::NonZero, pin::Pin, str, task}; use futures_util::{stream, Stream as _, StreamExt as _}; use smoldot_light::{platform::PlatformRef, HandleRpcError}; @@ -126,7 +126,7 @@ fn add_chain( database_content: str::from_utf8(&database_content) .unwrap_or_else(|_| panic!("non-utf8 database content")), json_rpc: if let Some(json_rpc_max_pending_requests) = - NonZeroU32::new(json_rpc_max_pending_requests) + NonZero::::new(json_rpc_max_pending_requests) { smoldot_light::AddChainConfigJsonRpc::Enabled { max_pending_requests: json_rpc_max_pending_requests,