From d003203618110bdb89293d057b13df5c46ae234b Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Thu, 19 Dec 2024 15:54:34 -0500 Subject: [PATCH 1/8] Add stacks-common to clippy CI and fix errors Signed-off-by: Jacinta Ferrant --- .github/workflows/clippy.yml | 2 +- stacks-common/Cargo.toml | 3 +- stacks-common/src/bitvec.rs | 8 +- stacks-common/src/deps_common/bech32/mod.rs | 4 +- .../deps_common/bitcoin/blockdata/opcodes.rs | 2 +- .../deps_common/bitcoin/blockdata/script.rs | 14 +- .../bitcoin/blockdata/transaction.rs | 4 +- .../deps_common/bitcoin/internal_macros.rs | 40 ++--- stacks-common/src/deps_common/bitcoin/mod.rs | 1 - .../deps_common/bitcoin/network/encodable.rs | 2 +- .../bitcoin/network/message_network.rs | 1 - .../deps_common/bitcoin/network/serialize.rs | 8 +- .../src/deps_common/bitcoin/util/hash.rs | 2 +- stacks-common/src/deps_common/ctrlc/mod.rs | 2 +- stacks-common/src/deps_common/httparse/mod.rs | 5 +- stacks-common/src/types/chainstate.rs | 7 +- stacks-common/src/types/mod.rs | 145 ++++++++++-------- stacks-common/src/types/tests.rs | 70 +++++---- stacks-common/src/util/chunked_encoding.rs | 14 +- stacks-common/src/util/hash.rs | 9 +- stacks-common/src/util/log.rs | 3 +- stacks-common/src/util/macros.rs | 4 +- stacks-common/src/util/pipe.rs | 11 +- stacks-common/src/util/retry.rs | 6 +- stacks-common/src/util/secp256k1.rs | 4 +- stacks-common/src/util/vrf.rs | 7 +- 26 files changed, 200 insertions(+), 178 deletions(-) diff --git a/.github/workflows/clippy.yml b/.github/workflows/clippy.yml index 4be5785f3d..1ba4825527 100644 --- a/.github/workflows/clippy.yml +++ b/.github/workflows/clippy.yml @@ -37,4 +37,4 @@ jobs: uses: actions-rs/clippy-check@v1 with: token: ${{ secrets.GITHUB_TOKEN }} - args: -p libstackerdb -p stacks-signer -p pox-locking -p clarity -p libsigner --no-deps --tests --all-features -- -D warnings \ No newline at end of file + args: -p libstackerdb -p stacks-signer -p pox-locking -p clarity -p libsigner -p stacks-common --no-deps --tests --all-features -- -D warnings \ No newline at end of file diff --git a/stacks-common/Cargo.toml b/stacks-common/Cargo.toml index 81b4326d4c..fef6c9408d 100644 --- a/stacks-common/Cargo.toml +++ b/stacks-common/Cargo.toml @@ -19,7 +19,7 @@ path = "./src/libcommon.rs" [dependencies] rand = { workspace = true } -serde = "1" +serde = { version = "1.0", features = ["derive"] } serde_derive = "1" serde_stacker = "0.1" sha3 = "0.10.1" @@ -77,7 +77,6 @@ testing = ["canonical"] serde = [] bech32_std = [] bech32_strict = [] -strason = [] [target.'cfg(all(any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64"), not(any(target_os="windows"))))'.dependencies] sha2 = { version = "0.10", features = ["asm"] } diff --git a/stacks-common/src/bitvec.rs b/stacks-common/src/bitvec.rs index 6602f62e5c..7c77e5da32 100644 --- a/stacks-common/src/bitvec.rs +++ b/stacks-common/src/bitvec.rs @@ -129,7 +129,7 @@ pub struct BitVecIter<'a, const MAX_SIZE: u16> { bitvec: &'a BitVec, } -impl<'a, const MAX_SIZE: u16> Iterator for BitVecIter<'a, MAX_SIZE> { +impl Iterator for BitVecIter<'_, MAX_SIZE> { type Item = bool; fn next(&mut self) -> Option { @@ -172,7 +172,7 @@ impl BitVec { } pub fn iter(&self) -> BitVecIter { - let byte = self.data.get(0); + let byte = self.data.first(); BitVecIter { index: 0, bitvec: self, @@ -184,6 +184,10 @@ impl BitVec { self.len } + pub fn is_empty(&self) -> bool { + self.len == 0 + } + /// Return the number of bytes needed to store `len` bits. fn data_len(len: u16) -> u16 { len / 8 + if len % 8 == 0 { 0 } else { 1 } diff --git a/stacks-common/src/deps_common/bech32/mod.rs b/stacks-common/src/deps_common/bech32/mod.rs index 655f2b1a82..8e7eca9540 100644 --- a/stacks-common/src/deps_common/bech32/mod.rs +++ b/stacks-common/src/deps_common/bech32/mod.rs @@ -201,7 +201,7 @@ impl<'a> Bech32Writer<'a> { } } -impl<'a> WriteBase32 for Bech32Writer<'a> { +impl WriteBase32 for Bech32Writer<'_> { type Err = fmt::Error; /// Writes a single 5 bit value of the data part @@ -211,7 +211,7 @@ impl<'a> WriteBase32 for Bech32Writer<'a> { } } -impl<'a> Drop for Bech32Writer<'a> { +impl Drop for Bech32Writer<'_> { fn drop(&mut self) { self.write_checksum() .expect("Unhandled error writing the checksum on drop.") diff --git a/stacks-common/src/deps_common/bitcoin/blockdata/opcodes.rs b/stacks-common/src/deps_common/bitcoin/blockdata/opcodes.rs index 5e628b06f8..6b70031f6f 100644 --- a/stacks-common/src/deps_common/bitcoin/blockdata/opcodes.rs +++ b/stacks-common/src/deps_common/bitcoin/blockdata/opcodes.rs @@ -606,7 +606,7 @@ impl All { Class::PushBytes(*self as u32) // 60 opcodes } else { - Class::Ordinary(unsafe { transmute(*self) }) + Class::Ordinary(unsafe { transmute::(*self) }) } } } diff --git a/stacks-common/src/deps_common/bitcoin/blockdata/script.rs b/stacks-common/src/deps_common/bitcoin/blockdata/script.rs index be5a6144c7..cc602a76b8 100644 --- a/stacks-common/src/deps_common/bitcoin/blockdata/script.rs +++ b/stacks-common/src/deps_common/bitcoin/blockdata/script.rs @@ -648,7 +648,7 @@ impl<'de> serde::Deserialize<'de> for Script { where E: serde::de::Error, { - let v: Vec = ::hex::decode(v).map_err(E::custom)?; + let v: Vec = crate::util::hash::hex_bytes(v).map_err(E::custom)?; Ok(Script::from(v)) } @@ -834,15 +834,15 @@ mod test { } #[test] - #[cfg(all(feature = "serde", feature = "strason"))] + #[cfg(feature = "serde")] fn script_json_serialize() { - use strason::Json; + use serde_json; let original = hex_script!("827651a0698faaa9a8a7a687"); - let json = Json::from_serialize(&original).unwrap(); - assert_eq!(json.to_bytes(), b"\"827651a0698faaa9a8a7a687\""); - assert_eq!(json.string(), Some("827651a0698faaa9a8a7a687")); - let des = json.into_deserialize().unwrap(); + let json_value = serde_json::to_value(&original).unwrap(); + assert_eq!(serde_json::to_vec(&json_value).unwrap(), b"\"827651a0698faaa9a8a7a687\""); + assert_eq!(json_value.to_string(), "\"827651a0698faaa9a8a7a687\""); + let des = serde_json::from_value(json_value).unwrap(); assert_eq!(original, des); } diff --git a/stacks-common/src/deps_common/bitcoin/blockdata/transaction.rs b/stacks-common/src/deps_common/bitcoin/blockdata/transaction.rs index 1ece07c511..c2d4c4e0a2 100644 --- a/stacks-common/src/deps_common/bitcoin/blockdata/transaction.rs +++ b/stacks-common/src/deps_common/bitcoin/blockdata/transaction.rs @@ -342,7 +342,7 @@ impl Transaction { let mut script_len_bytes = serialize(&script_len).expect("FATAL: failed to encode varint"); length_script.append(&mut script_len_bytes); - length_script.extend_from_slice(&script_bytes); + length_script.extend_from_slice(script_bytes); length_script } } @@ -361,7 +361,7 @@ impl Transaction { let mut script_len_bytes = serialize(&script_len).expect("FATAL: failed to encode varint"); raw_vec.append(&mut script_len_bytes); - raw_vec.extend_from_slice(&script_bytes); + raw_vec.extend_from_slice(script_bytes); } Sha256dHash::from_data(&raw_vec) } else if sighash_type == SigHashType::Single && input_index < self.output.len() { diff --git a/stacks-common/src/deps_common/bitcoin/internal_macros.rs b/stacks-common/src/deps_common/bitcoin/internal_macros.rs index 2d0873498c..e74eebe0ad 100644 --- a/stacks-common/src/deps_common/bitcoin/internal_macros.rs +++ b/stacks-common/src/deps_common/bitcoin/internal_macros.rs @@ -106,16 +106,16 @@ macro_rules! user_enum { } #[cfg(feature = "serde")] - impl<'de> $crate::serde::Deserialize<'de> for $name { + impl<'de> serde::Deserialize<'de> for $name { #[inline] fn deserialize(deserializer: D) -> Result where - D: $crate::serde::Deserializer<'de>, + D: serde::Deserializer<'de>, { - use $crate::std::fmt::{self, Formatter}; + use std::fmt::{self, Formatter}; struct Visitor; - impl<'de> $crate::serde::de::Visitor<'de> for Visitor { + impl<'de> serde::de::Visitor<'de> for Visitor { type Value = $name; fn expecting(&self, formatter: &mut Formatter) -> fmt::Result { @@ -124,7 +124,7 @@ macro_rules! user_enum { fn visit_str(self, v: &str) -> Result where - E: $crate::serde::de::Error, + E: serde::de::Error, { static FIELDS: &'static [&'static str] = &[$(stringify!($txt)),*]; @@ -136,14 +136,14 @@ macro_rules! user_enum { fn visit_borrowed_str(self, v: &'de str) -> Result where - E: $crate::serde::de::Error, + E: serde::de::Error, { self.visit_str(v) } fn visit_string(self, v: String) -> Result where - E: $crate::serde::de::Error, + E: serde::de::Error, { self.visit_str(&v) } @@ -222,19 +222,19 @@ macro_rules! hex_script (($s:expr) => (crate::deps_common::bitcoin::blockdata::s macro_rules! serde_struct_impl { ($name:ident, $($fe:ident),*) => ( #[cfg(feature = "serde")] - impl<'de> $crate::serde::Deserialize<'de> for $name { + impl<'de> serde::Deserialize<'de> for $name { fn deserialize(deserializer: D) -> Result<$name, D::Error> where - D: $crate::serde::de::Deserializer<'de>, + D: serde::de::Deserializer<'de>, { - use $crate::std::fmt::{self, Formatter}; - use $crate::serde::de::IgnoredAny; + use std::fmt::{self, Formatter}; + use serde::de::IgnoredAny; #[allow(non_camel_case_types)] enum Enum { Unknown__Field, $($fe),* } struct EnumVisitor; - impl<'de> $crate::serde::de::Visitor<'de> for EnumVisitor { + impl<'de> serde::de::Visitor<'de> for EnumVisitor { type Value = Enum; fn expecting(&self, formatter: &mut Formatter) -> fmt::Result { @@ -243,7 +243,7 @@ macro_rules! serde_struct_impl { fn visit_str(self, v: &str) -> Result where - E: $crate::serde::de::Error, + E: serde::de::Error, { match v { $( @@ -254,7 +254,7 @@ macro_rules! serde_struct_impl { } } - impl<'de> $crate::serde::Deserialize<'de> for Enum { + impl<'de> serde::Deserialize<'de> for Enum { fn deserialize(deserializer: D) -> Result where D: ::serde::de::Deserializer<'de>, @@ -265,7 +265,7 @@ macro_rules! serde_struct_impl { struct Visitor; - impl<'de> $crate::serde::de::Visitor<'de> for Visitor { + impl<'de> serde::de::Visitor<'de> for Visitor { type Value = $name; fn expecting(&self, formatter: &mut Formatter) -> fmt::Result { @@ -274,9 +274,9 @@ macro_rules! serde_struct_impl { fn visit_map(self, mut map: A) -> Result where - A: $crate::serde::de::MapAccess<'de>, + A: serde::de::MapAccess<'de>, { - use $crate::serde::de::Error; + use serde::de::Error; $(let mut $fe = None;)* @@ -317,12 +317,12 @@ macro_rules! serde_struct_impl { } #[cfg(feature = "serde")] - impl<'de> $crate::serde::Serialize for $name { + impl<'de> serde::Serialize for $name { fn serialize(&self, serializer: S) -> Result where - S: $crate::serde::Serializer, + S: serde::Serializer, { - use $crate::serde::ser::SerializeStruct; + use serde::ser::SerializeStruct; // Only used to get the struct length. static FIELDS: &'static [&'static str] = &[$(stringify!($fe)),*]; diff --git a/stacks-common/src/deps_common/bitcoin/mod.rs b/stacks-common/src/deps_common/bitcoin/mod.rs index b70da5deb2..097bfa2b65 100644 --- a/stacks-common/src/deps_common/bitcoin/mod.rs +++ b/stacks-common/src/deps_common/bitcoin/mod.rs @@ -27,7 +27,6 @@ // Clippy flags #![allow(clippy::needless_range_loop)] // suggests making a big mess of array newtypes -#![allow(clippy::extend_from_slice)] // `extend_from_slice` only available since 1.6 // Coding conventions #![deny(non_upper_case_globals)] diff --git a/stacks-common/src/deps_common/bitcoin/network/encodable.rs b/stacks-common/src/deps_common/bitcoin/network/encodable.rs index f14ee1fb85..b6e372e62e 100644 --- a/stacks-common/src/deps_common/bitcoin/network/encodable.rs +++ b/stacks-common/src/deps_common/bitcoin/network/encodable.rs @@ -30,7 +30,7 @@ //! use std::hash::Hash; -use std::{mem, u32}; +use std::mem; use hashbrown::HashMap; diff --git a/stacks-common/src/deps_common/bitcoin/network/message_network.rs b/stacks-common/src/deps_common/bitcoin/network/message_network.rs index 4f913ee48f..6e3bf4154a 100644 --- a/stacks-common/src/deps_common/bitcoin/network/message_network.rs +++ b/stacks-common/src/deps_common/bitcoin/network/message_network.rs @@ -23,7 +23,6 @@ use crate::deps_common::bitcoin::network::constants; use crate::util; /// Some simple messages - /// The `version` message #[derive(PartialEq, Eq, Clone, Debug)] pub struct VersionMessage { diff --git a/stacks-common/src/deps_common/bitcoin/network/serialize.rs b/stacks-common/src/deps_common/bitcoin/network/serialize.rs index f33a347133..7fd75391c8 100644 --- a/stacks-common/src/deps_common/bitcoin/network/serialize.rs +++ b/stacks-common/src/deps_common/bitcoin/network/serialize.rs @@ -157,9 +157,9 @@ impl BitcoinHash for Vec { } /// Encode an object into a vector -pub fn serialize(data: &T) -> Result, Error> +pub fn serialize(data: &T) -> Result, Error> where - T: ConsensusEncodable>>>, + T: ConsensusEncodable>>> + ?Sized, { let mut encoder = RawEncoder::new(Cursor::new(vec![])); data.consensus_encode(&mut encoder)?; @@ -167,9 +167,9 @@ where } /// Encode an object into a hex-encoded string -pub fn serialize_hex(data: &T) -> Result +pub fn serialize_hex(data: &T) -> Result where - T: ConsensusEncodable>>>, + T: ConsensusEncodable>>> + ?Sized, { let serial = serialize(data)?; Ok(hex_encode(&serial[..])) diff --git a/stacks-common/src/deps_common/bitcoin/util/hash.rs b/stacks-common/src/deps_common/bitcoin/util/hash.rs index daa1de3360..e1a9455e99 100644 --- a/stacks-common/src/deps_common/bitcoin/util/hash.rs +++ b/stacks-common/src/deps_common/bitcoin/util/hash.rs @@ -450,7 +450,7 @@ pub fn bitcoin_merkle_root(data: Vec) -> Sha256dHash { bitcoin_merkle_root(next) } -impl<'a, T: BitcoinHash> MerkleRoot for &'a [T] { +impl MerkleRoot for &[T] { fn merkle_root(&self) -> Sha256dHash { bitcoin_merkle_root(self.iter().map(|obj| obj.bitcoin_hash()).collect()) } diff --git a/stacks-common/src/deps_common/ctrlc/mod.rs b/stacks-common/src/deps_common/ctrlc/mod.rs index 836ae7dfb6..70514b842c 100644 --- a/stacks-common/src/deps_common/ctrlc/mod.rs +++ b/stacks-common/src/deps_common/ctrlc/mod.rs @@ -7,7 +7,7 @@ // notice may not be copied, modified, or distributed except // according to those terms. -#[macro_use] +#![macro_use] mod error; mod platform; diff --git a/stacks-common/src/deps_common/httparse/mod.rs b/stacks-common/src/deps_common/httparse/mod.rs index 67ca2c52cd..b4c9250546 100644 --- a/stacks-common/src/deps_common/httparse/mod.rs +++ b/stacks-common/src/deps_common/httparse/mod.rs @@ -169,14 +169,14 @@ impl<'a> Bytes<'a> { } } -impl<'a> AsRef<[u8]> for Bytes<'a> { +impl AsRef<[u8]> for Bytes<'_> { #[inline] fn as_ref(&self) -> &[u8] { &self.slice_peek()[self.pos..] } } -impl<'a> Iterator for Bytes<'a> { +impl Iterator for Bytes<'_> { type Item = u8; #[inline] @@ -701,6 +701,7 @@ pub fn parse_headers<'b: 'h, 'h>( } #[inline] +#[allow(clippy::never_loop)] fn parse_headers_iter<'a>(headers: &mut &mut [Header<'a>], bytes: &mut Bytes<'a>) -> Result { let mut num_headers: usize = 0; let mut count: usize = 0; diff --git a/stacks-common/src/types/chainstate.rs b/stacks-common/src/types/chainstate.rs index 59347ed36a..9aa91a431a 100644 --- a/stacks-common/src/types/chainstate.rs +++ b/stacks-common/src/types/chainstate.rs @@ -1,4 +1,4 @@ -use std::fmt; +use std::fmt::{self, Display}; use std::io::{Read, Write}; use std::str::FromStr; @@ -48,7 +48,7 @@ impl TrieHash { /// TrieHash from bytes pub fn from_data(data: &[u8]) -> TrieHash { - if data.len() == 0 { + if data.is_empty() { return TrieHash::from_empty_data(); } @@ -62,7 +62,7 @@ impl TrieHash { } pub fn from_data_array>(data: &[B]) -> TrieHash { - if data.len() == 0 { + if data.is_empty() { return TrieHash::from_empty_data(); } @@ -78,6 +78,7 @@ impl TrieHash { } /// Convert to a String that can be used in e.g. sqlite + #[allow(clippy::inherent_to_string_shadow_display)] pub fn to_string(&self) -> String { let s = format!("{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", self.0[0], self.0[1], self.0[2], self.0[3], diff --git a/stacks-common/src/types/mod.rs b/stacks-common/src/types/mod.rs index 49fdfa84fd..e6ab46d473 100644 --- a/stacks-common/src/types/mod.rs +++ b/stacks-common/src/types/mod.rs @@ -18,6 +18,7 @@ use std::cell::LazyCell; use std::cmp::Ordering; use std::fmt; use std::ops::{Deref, DerefMut, Index, IndexMut}; +use std::sync::OnceLock; #[cfg(feature = "canonical")] pub mod sqlite; @@ -134,62 +135,77 @@ pub struct CoinbaseInterval { /// /// The above is for mainnet, which has a burnchain year of 52596 blocks and starts at burnchain height 666050. /// The `Offset Height` column is simply the difference between `Bitcoin Height` and 666050. - +/// /// Mainnet coinbase intervals, as of SIP-029 -pub const COINBASE_INTERVALS_MAINNET: LazyCell<[CoinbaseInterval; 5]> = LazyCell::new(|| { - let emissions_schedule = [ - CoinbaseInterval { - coinbase: 1_000 * u128::from(MICROSTACKS_PER_STACKS), - effective_start_height: 0, - }, - CoinbaseInterval { - coinbase: 500 * u128::from(MICROSTACKS_PER_STACKS), - effective_start_height: 278_950, - }, - CoinbaseInterval { - coinbase: 250 * u128::from(MICROSTACKS_PER_STACKS), - effective_start_height: 383_950, - }, - CoinbaseInterval { - coinbase: 125 * u128::from(MICROSTACKS_PER_STACKS), - effective_start_height: 593_950, - }, - CoinbaseInterval { - coinbase: (625 * u128::from(MICROSTACKS_PER_STACKS)) / 10, - effective_start_height: 803_950, - }, - ]; - assert!(CoinbaseInterval::check_order(&emissions_schedule)); - emissions_schedule -}); - -/// Testnet coinbase intervals, as of SIP-029 -pub const COINBASE_INTERVALS_TESTNET: LazyCell<[CoinbaseInterval; 5]> = LazyCell::new(|| { - let emissions_schedule = [ - CoinbaseInterval { - coinbase: 1_000 * u128::from(MICROSTACKS_PER_STACKS), - effective_start_height: 0, - }, - CoinbaseInterval { - coinbase: 500 * u128::from(MICROSTACKS_PER_STACKS), - effective_start_height: 77_777, - }, - CoinbaseInterval { - coinbase: 250 * u128::from(MICROSTACKS_PER_STACKS), - effective_start_height: 77_777 * 7, - }, - CoinbaseInterval { - coinbase: 125 * u128::from(MICROSTACKS_PER_STACKS), - effective_start_height: 77_777 * 14, - }, - CoinbaseInterval { - coinbase: (625 * u128::from(MICROSTACKS_PER_STACKS)) / 10, - effective_start_height: 77_777 * 21, - }, - ]; - assert!(CoinbaseInterval::check_order(&emissions_schedule)); - emissions_schedule -}); +// This static value is lazily initialized using `OnceLock` to avoid unnecessary +// computation at program startup while ensuring thread safety and one-time initialization. +// The intervals define the emission schedule for mainnet and are validated at runtime. +pub static COINBASE_INTERVALS_MAINNET: OnceLock<[CoinbaseInterval; 5]> = OnceLock::new(); + +pub fn get_coinbase_intervals_mainnet() -> &'static [CoinbaseInterval; 5] { + COINBASE_INTERVALS_MAINNET.get_or_init(|| { + let emissions_schedule = [ + CoinbaseInterval { + coinbase: 1_000 * u128::from(MICROSTACKS_PER_STACKS), + effective_start_height: 0, + }, + CoinbaseInterval { + coinbase: 500 * u128::from(MICROSTACKS_PER_STACKS), + effective_start_height: 278_950, + }, + CoinbaseInterval { + coinbase: 250 * u128::from(MICROSTACKS_PER_STACKS), + effective_start_height: 383_950, + }, + CoinbaseInterval { + coinbase: 125 * u128::from(MICROSTACKS_PER_STACKS), + effective_start_height: 593_950, + }, + CoinbaseInterval { + coinbase: (625 * u128::from(MICROSTACKS_PER_STACKS)) / 10, + effective_start_height: 803_950, + }, + ]; + assert!(CoinbaseInterval::check_order(&emissions_schedule)); + emissions_schedule + }) +} + +/// Testnet coinbase intervals as defined by SIP-029. +/// +/// This static value is lazily initialized using `OnceLock` to avoid unnecessary +/// computation at program startup while ensuring thread safety and one-time initialization. +/// The intervals define the emission schedule for testnet and are validated at runtime. +pub static COINBASE_INTERVALS_TESTNET: OnceLock<[CoinbaseInterval; 5]> = OnceLock::new(); + +pub fn get_coinbase_intervals_testnet() -> &'static [CoinbaseInterval; 5] { + COINBASE_INTERVALS_TESTNET.get_or_init(|| { + let emissions_schedule = [ + CoinbaseInterval { + coinbase: 1_000 * u128::from(MICROSTACKS_PER_STACKS), + effective_start_height: 0, + }, + CoinbaseInterval { + coinbase: 500 * u128::from(MICROSTACKS_PER_STACKS), + effective_start_height: 77_777, + }, + CoinbaseInterval { + coinbase: 250 * u128::from(MICROSTACKS_PER_STACKS), + effective_start_height: 77_777 * 7, + }, + CoinbaseInterval { + coinbase: 125 * u128::from(MICROSTACKS_PER_STACKS), + effective_start_height: 77_777 * 14, + }, + CoinbaseInterval { + coinbase: (625 * u128::from(MICROSTACKS_PER_STACKS)) / 10, + effective_start_height: 77_777 * 21, + }, + ]; + assert!(CoinbaseInterval::check_order(&emissions_schedule)); + emissions_schedule + }) +} /// Used for testing to substitute a coinbase schedule #[cfg(any(test, feature = "testing"))] @@ -245,11 +261,11 @@ impl CoinbaseInterval { } let mut ht = intervals[0].effective_start_height; - for i in 1..intervals.len() { - if intervals[i].effective_start_height < ht { + for interval in intervals { + if interval.effective_start_height < ht { return false; } - ht = intervals[i].effective_start_height; + ht = interval.effective_start_height; } true } @@ -485,18 +501,18 @@ impl StacksEpochId { } if mainnet { - COINBASE_INTERVALS_MAINNET.to_vec() + get_coinbase_intervals_mainnet().to_vec() } else { - COINBASE_INTERVALS_TESTNET.to_vec() + get_coinbase_intervals_testnet().to_vec() } } #[cfg(not(any(test, feature = "testing")))] pub(crate) fn get_coinbase_intervals(mainnet: bool) -> Vec { if mainnet { - COINBASE_INTERVALS_MAINNET.to_vec() + get_coinbase_intervals_mainnet().to_vec() } else { - COINBASE_INTERVALS_TESTNET.to_vec() + get_coinbase_intervals_testnet().to_vec() } } @@ -538,12 +554,11 @@ impl StacksEpochId { self.coinbase_reward_pre_sip029(first_burnchain_height, current_burnchain_height) } StacksEpochId::Epoch31 => { - let cb = self.coinbase_reward_sip029( + self.coinbase_reward_sip029( mainnet, first_burnchain_height, current_burnchain_height, - ); - cb + ) } } } diff --git a/stacks-common/src/types/tests.rs b/stacks-common/src/types/tests.rs index 20676999e7..1e6c44644c 100644 --- a/stacks-common/src/types/tests.rs +++ b/stacks-common/src/types/tests.rs @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::types::{get_coinbase_intervals_mainnet, get_coinbase_intervals_testnet}; + use super::{ set_test_coinbase_schedule, CoinbaseInterval, StacksEpochId, COINBASE_INTERVALS_MAINNET, COINBASE_INTERVALS_TESTNET, @@ -21,50 +23,52 @@ use super::{ #[test] fn test_mainnet_coinbase_emissions() { - assert_eq!(COINBASE_INTERVALS_MAINNET.len(), 5); - assert_eq!(COINBASE_INTERVALS_MAINNET[0].coinbase, 1_000_000_000); - assert_eq!(COINBASE_INTERVALS_MAINNET[1].coinbase, 500_000_000); - assert_eq!(COINBASE_INTERVALS_MAINNET[2].coinbase, 250_000_000); - assert_eq!(COINBASE_INTERVALS_MAINNET[3].coinbase, 125_000_000); - assert_eq!(COINBASE_INTERVALS_MAINNET[4].coinbase, 62_500_000); + let coinbase_intervals_mainnet = get_coinbase_intervals_mainnet(); + assert_eq!(coinbase_intervals_mainnet.len(), 5); + assert_eq!(coinbase_intervals_mainnet[0].coinbase, 1_000_000_000); + assert_eq!(coinbase_intervals_mainnet[1].coinbase, 500_000_000); + assert_eq!(coinbase_intervals_mainnet[2].coinbase, 250_000_000); + assert_eq!(coinbase_intervals_mainnet[3].coinbase, 125_000_000); + assert_eq!(coinbase_intervals_mainnet[4].coinbase, 62_500_000); // heights from SIP-029 assert_eq!( - COINBASE_INTERVALS_MAINNET[0].effective_start_height, + coinbase_intervals_mainnet[0].effective_start_height, 666_050 - 666_050 ); assert_eq!( - COINBASE_INTERVALS_MAINNET[1].effective_start_height, + coinbase_intervals_mainnet[1].effective_start_height, 945_000 - 666_050 ); assert_eq!( - COINBASE_INTERVALS_MAINNET[2].effective_start_height, + coinbase_intervals_mainnet[2].effective_start_height, 1_050_000 - 666_050 ); assert_eq!( - COINBASE_INTERVALS_MAINNET[3].effective_start_height, + coinbase_intervals_mainnet[3].effective_start_height, 1_260_000 - 666_050 ); assert_eq!( - COINBASE_INTERVALS_MAINNET[4].effective_start_height, + coinbase_intervals_mainnet[4].effective_start_height, 1_470_000 - 666_050 ); } #[test] fn test_get_coinbase_at_effective_height() { - assert!(CoinbaseInterval::check_order(&*COINBASE_INTERVALS_MAINNET)); + let coinbase_intervals_mainnet = get_coinbase_intervals_mainnet(); + assert!(CoinbaseInterval::check_order(coinbase_intervals_mainnet)); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 666050 - 666050 ), 1_000_000_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 666051 - 666050 ), 1_000_000_000 @@ -72,21 +76,21 @@ fn test_get_coinbase_at_effective_height() { assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 944_999 - 666050 ), 1_000_000_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 945_000 - 666050 ), 500_000_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 945_001 - 666050 ), 500_000_000 @@ -94,21 +98,21 @@ fn test_get_coinbase_at_effective_height() { assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 1_049_999 - 666050 ), 500_000_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 1_050_000 - 666050 ), 250_000_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 1_050_001 - 666050 ), 250_000_000 @@ -116,21 +120,21 @@ fn test_get_coinbase_at_effective_height() { assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 1_259_999 - 666050 ), 250_000_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 1_260_000 - 666050 ), 125_000_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 1_260_001 - 666050 ), 125_000_000 @@ -138,21 +142,21 @@ fn test_get_coinbase_at_effective_height() { assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 1_469_999 - 666050 ), 125_000_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 1_470_000 - 666050 ), 62_500_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 1_470_001 - 666050 ), 62_500_000 @@ -160,21 +164,21 @@ fn test_get_coinbase_at_effective_height() { assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 2_197_559 - 666050 ), 62_500_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 2_197_560 - 666050 ), 62_500_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - &*COINBASE_INTERVALS_MAINNET, + coinbase_intervals_mainnet, 2_197_561 - 666050 ), 62_500_000 @@ -327,11 +331,11 @@ fn test_set_coinbase_intervals() { assert_eq!( StacksEpochId::get_coinbase_intervals(true), - *COINBASE_INTERVALS_MAINNET + get_coinbase_intervals_mainnet() ); assert_eq!( StacksEpochId::get_coinbase_intervals(false), - *COINBASE_INTERVALS_TESTNET + get_coinbase_intervals_testnet() ); set_test_coinbase_schedule(Some(new_sched.clone())); @@ -343,10 +347,10 @@ fn test_set_coinbase_intervals() { assert_eq!( StacksEpochId::get_coinbase_intervals(true), - *COINBASE_INTERVALS_MAINNET + get_coinbase_intervals_mainnet() ); assert_eq!( StacksEpochId::get_coinbase_intervals(false), - *COINBASE_INTERVALS_TESTNET + get_coinbase_intervals_testnet() ); } diff --git a/stacks-common/src/util/chunked_encoding.rs b/stacks-common/src/util/chunked_encoding.rs index 235a9d14e8..445ec5a831 100644 --- a/stacks-common/src/util/chunked_encoding.rs +++ b/stacks-common/src/util/chunked_encoding.rs @@ -316,7 +316,7 @@ impl HttpChunkedTransferReaderState { } } -impl<'a, R: Read> Read for HttpChunkedTransferReader<'a, R> { +impl Read for HttpChunkedTransferReader<'_, R> { /// Read a HTTP chunk-encoded stream. /// Returns number of decoded bytes (i.e. number of bytes copied to buf, as expected) fn read(&mut self, buf: &mut [u8]) -> io::Result { @@ -401,7 +401,7 @@ impl<'a, 'state, W: Write> HttpChunkedTransferWriter<'a, 'state, W> { } } -impl<'a, 'state, W: Write> Write for HttpChunkedTransferWriter<'a, 'state, W> { +impl Write for HttpChunkedTransferWriter<'_, '_, W> { fn write(&mut self, buf: &[u8]) -> io::Result { let mut written = 0; while written < buf.len() && !self.state.corked { @@ -526,7 +526,7 @@ mod test { #[test] fn test_http_chunked_encode() { - let tests = vec![ + let tests = [ // (chunk size, byte string, expected encoding) (10, "aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd", "a\r\naaaaaaaaaa\r\na\r\nbbbbbbbbbb\r\na\r\ncccccccccc\r\na\r\ndddddddddd\r\n0\r\n\r\n"), (10, "aaaaaaaaaabbbbbbbbbbccccccccccdddddddddde", "a\r\naaaaaaaaaa\r\na\r\nbbbbbbbbbb\r\na\r\ncccccccccc\r\na\r\ndddddddddd\r\n1\r\ne\r\n0\r\n\r\n"), @@ -551,7 +551,7 @@ mod test { #[test] fn test_http_chunked_encode_multi() { - let tests = vec![ + let tests = [ // chunk size, sequence of writes, expected encoding (10, vec!["aaaaaaaaaa", "bbbbb", "bbbbb", "ccc", "ccc", "ccc", "c", "dd", "ddddd", "ddd"], "a\r\naaaaaaaaaa\r\na\r\nbbbbbbbbbb\r\na\r\ncccccccccc\r\na\r\ndddddddddd\r\n0\r\n\r\n"), (10, vec!["a", "a", "a", "a", "a", "a", "a", "a", "a", "a"], "a\r\naaaaaaaaaa\r\n0\r\n\r\n"), @@ -576,7 +576,7 @@ mod test { #[test] fn test_http_chunked_decode() { - let tests = vec![ + let tests = [ ("a\r\naaaaaaaaaa\r\na\r\nbbbbbbbbbb\r\na\r\ncccccccccc\r\na\r\ndddddddddd\r\n0\r\n\r\n", "aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd"), ("A\r\naaaaaaaaaa\r\nA\r\nbbbbbbbbbb\r\nA\r\ncccccccccc\r\nA\r\ndddddddddd\r\n0\r\n\r\n", "aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd"), ("1\r\na\r\n2\r\nbb\r\n3\r\nccc\r\n4\r\ndddd\r\n0\r\n\r\n", "abbcccdddd"), @@ -598,7 +598,7 @@ mod test { #[test] fn test_http_chunked_decode_multi() { - let tests = vec![ + let tests = [ (vec_u8(vec!["1\r\na", "\r\n", "0\r\n\r\n"]), "a"), (vec_u8(vec!["1\r\na\r", "\n0\r\n\r\n"]), "a"), (vec_u8(vec!["1\r\na\r\n", "0\r\n\r", "\n"]), "a"), @@ -694,7 +694,7 @@ mod test { #[test] fn test_http_chunked_decode_err() { - let tests = vec![ + let tests = [ ( "1; reallyreallyreallyreallylongextension;\r\na\r\n0\r\n\r\n", 1, diff --git a/stacks-common/src/util/hash.rs b/stacks-common/src/util/hash.rs index a5e4341b60..7b32790100 100644 --- a/stacks-common/src/util/hash.rs +++ b/stacks-common/src/util/hash.rs @@ -382,12 +382,15 @@ pub struct MerklePathPoint { pub type MerklePath = Vec>; /// Merkle tree implementation with tagged nodes: -/// * a leaf hash is H(0x00 + data) -/// * a node hash is H(0x01 + left.hash + right.hash) -/// An empty tree has root hash 0x00000...00000 +/// +/// * A leaf hash is `H(0x00 + data)` +/// * A node hash is `H(0x01 + left.hash + right.hash)` +/// +/// An empty tree has a root hash of `0x00000...00000`. /// /// NOTE: This is consensus-critical code, because it is used to generate the transaction Merkle /// tree roots in Stacks blocks. +#[allow(clippy::ptr_arg)] impl MerkleTree where H: MerkleHashFunc + Clone + PartialEq + fmt::Debug, diff --git a/stacks-common/src/util/log.rs b/stacks-common/src/util/log.rs index 534f3f9969..b0ac704f0c 100644 --- a/stacks-common/src/util/log.rs +++ b/stacks-common/src/util/log.rs @@ -224,8 +224,7 @@ fn make_logger() -> Logger { let decorator = get_decorator(); let atty = isatty(Stream::Stderr); let drain = TermFormat::new(decorator, pretty_print, debug, atty); - let logger = Logger::root(drain.ignore_res(), o!()); - logger + Logger::root(drain.ignore_res(), o!()) } } diff --git a/stacks-common/src/util/macros.rs b/stacks-common/src/util/macros.rs index b1b26ee014..f06ddceb73 100644 --- a/stacks-common/src/util/macros.rs +++ b/stacks-common/src/util/macros.rs @@ -538,7 +538,7 @@ macro_rules! impl_byte_array_newtype { /// Instantiates from a vector of bytes #[allow(dead_code)] - pub fn from_vec(inp: &Vec) -> Option<$thing> { + pub fn from_vec(inp: &[u8]) -> Option<$thing> { match inp.len() { $len => { let mut ret = [0; $len]; @@ -552,7 +552,7 @@ macro_rules! impl_byte_array_newtype { /// Instantiates from a big-endian vector of bytes, converting to host byte order #[allow(dead_code)] - pub fn from_vec_be(b: &Vec) -> Option<$thing> { + pub fn from_vec_be(b: &[u8]) -> Option<$thing> { match b.len() { $len => { let mut ret = [0; $len]; diff --git a/stacks-common/src/util/pipe.rs b/stacks-common/src/util/pipe.rs index bb7482f949..86d92abd61 100644 --- a/stacks-common/src/util/pipe.rs +++ b/stacks-common/src/util/pipe.rs @@ -25,10 +25,11 @@ use crate::util::log; /// Inter-thread pipe for streaming messages, built on channels. /// Used mainly in conjunction with networking. -/// * The read endpoint lives inside the connection, and will consume data from another thread to -/// be sent out on the network. -/// * The write endpoint gets fed into calls to consensus_serialize(), to be sent out on the -/// network. +/// +/// * The read endpoint lives inside the connection and will consume data from another thread +/// to be sent out on the network. +/// * The write endpoint gets fed into calls to `consensus_serialize()` to be sent out on the +/// network. #[derive(Debug)] pub struct PipeRead { input: Receiver>, @@ -187,7 +188,7 @@ impl PipeWrite { } fn write_or_buffer(&mut self, buf: &[u8]) -> io::Result { - if buf.len() == 0 { + if buf.is_empty() { return Ok(0); } diff --git a/stacks-common/src/util/retry.rs b/stacks-common/src/util/retry.rs index d296e4ae79..e7f6c0b140 100644 --- a/stacks-common/src/util/retry.rs +++ b/stacks-common/src/util/retry.rs @@ -61,7 +61,7 @@ impl<'a, R: Read> RetryReader<'a, R> { } } -impl<'a, R: Read> Read for RetryReader<'a, R> { +impl Read for RetryReader<'_, R> { fn read(&mut self, buf: &mut [u8]) -> io::Result { let nr_buf = if self.i < self.buf.len() { // consume from inner buffer @@ -98,7 +98,7 @@ impl<'a, R: Read> BoundReader<'a, R> { } } -impl<'a, R: Read> Read for BoundReader<'a, R> { +impl Read for BoundReader<'_, R> { fn read(&mut self, buf: &mut [u8]) -> io::Result { let intended_read = self .read_so_far @@ -134,7 +134,7 @@ impl<'a, R: Read> LogReader<'a, R> { } } -impl<'a, R: Read> Read for LogReader<'a, R> { +impl Read for LogReader<'_, R> { fn read(&mut self, buf: &mut [u8]) -> io::Result { let nr = self.fd.read(buf)?; let read = buf[0..nr].to_vec(); diff --git a/stacks-common/src/util/secp256k1.rs b/stacks-common/src/util/secp256k1.rs index c3b80acac5..5c64838855 100644 --- a/stacks-common/src/util/secp256k1.rs +++ b/stacks-common/src/util/secp256k1.rs @@ -72,10 +72,10 @@ impl MessageSignature { #[cfg(any(test, feature = "testing"))] // test method for generating place-holder data - pub fn from_raw(sig: &Vec) -> MessageSignature { + pub fn from_raw(sig: &[u8]) -> MessageSignature { let mut buf = [0u8; 65]; if sig.len() < 65 { - buf.copy_from_slice(&sig[..]); + buf.copy_from_slice(sig); } else { buf.copy_from_slice(&sig[..65]); } diff --git a/stacks-common/src/util/vrf.rs b/stacks-common/src/util/vrf.rs index ddfdedfaa8..e61ce7a8bb 100644 --- a/stacks-common/src/util/vrf.rs +++ b/stacks-common/src/util/vrf.rs @@ -158,10 +158,7 @@ impl VRFPublicKey { // that's what the docs say to do! let checked_pubkey = CompressedEdwardsY(pubkey_slice); - if checked_pubkey.decompress().is_none() { - // invalid - return None; - } + checked_pubkey.decompress()?; let key = ed25519_dalek::VerifyingKey::from_bytes(&pubkey_slice).ok()?; Some(VRFPublicKey(key)) @@ -432,7 +429,7 @@ impl VRF { /// * its public key (an ed25519 curve point) /// * a new private key derived from the hash of the private key /// * a truncated hash of the private key - /// Idea borroed from Algorand (https://github.com/algorand/libsodium/blob/draft-irtf-cfrg-vrf-03/src/libsodium/crypto_vrf/ietfdraft03/prove.c) + /// Idea borroed from Algorand (https://github.com/algorand/libsodium/blob/draft-irtf-cfrg-vrf-03/src/libsodium/crypto_vrf/ietfdraft03/prove.c) fn expand_privkey(secret: &VRFPrivateKey) -> (VRFPublicKey, ed25519_Scalar, [u8; 32]) { let mut hasher = Sha512::new(); let mut h = [0u8; 64]; From be1e4ac77235631e39cbf02688ac544abd5da292 Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Thu, 19 Dec 2024 19:29:56 -0500 Subject: [PATCH 2/8] CRC: fix some comments Signed-off-by: Jacinta Ferrant --- .../deps_common/bitcoin/blockdata/script.rs | 5 ++- .../bitcoin/network/message_network.rs | 3 +- stacks-common/src/types/mod.rs | 45 +++++++++---------- stacks-common/src/types/tests.rs | 3 +- stacks-common/src/util/hash.rs | 4 +- 5 files changed, 30 insertions(+), 30 deletions(-) diff --git a/stacks-common/src/deps_common/bitcoin/blockdata/script.rs b/stacks-common/src/deps_common/bitcoin/blockdata/script.rs index cc602a76b8..34ee5897c3 100644 --- a/stacks-common/src/deps_common/bitcoin/blockdata/script.rs +++ b/stacks-common/src/deps_common/bitcoin/blockdata/script.rs @@ -840,7 +840,10 @@ mod test { let original = hex_script!("827651a0698faaa9a8a7a687"); let json_value = serde_json::to_value(&original).unwrap(); - assert_eq!(serde_json::to_vec(&json_value).unwrap(), b"\"827651a0698faaa9a8a7a687\""); + assert_eq!( + serde_json::to_vec(&json_value).unwrap(), + b"\"827651a0698faaa9a8a7a687\"" + ); assert_eq!(json_value.to_string(), "\"827651a0698faaa9a8a7a687\""); let des = serde_json::from_value(json_value).unwrap(); assert_eq!(original, des); diff --git a/stacks-common/src/deps_common/bitcoin/network/message_network.rs b/stacks-common/src/deps_common/bitcoin/network/message_network.rs index 6e3bf4154a..0cf486ba85 100644 --- a/stacks-common/src/deps_common/bitcoin/network/message_network.rs +++ b/stacks-common/src/deps_common/bitcoin/network/message_network.rs @@ -22,7 +22,8 @@ use crate::deps_common::bitcoin::network::address::Address; use crate::deps_common::bitcoin::network::constants; use crate::util; -/// Some simple messages +// Some simple messages + /// The `version` message #[derive(PartialEq, Eq, Clone, Debug)] pub struct VersionMessage { diff --git a/stacks-common/src/types/mod.rs b/stacks-common/src/types/mod.rs index e6ab46d473..283c5f3b9a 100644 --- a/stacks-common/src/types/mod.rs +++ b/stacks-common/src/types/mod.rs @@ -122,22 +122,21 @@ pub struct CoinbaseInterval { pub effective_start_height: u64, } -/// From SIP-029: -/// -/// | Coinbase Interval | Bitcoin Height | Offset Height | Approx. Supply | STX Reward | Annual Inflation | -/// |--------------------|----------------|---------------------|------------------|------------|------------------| -/// | Current | - | - | 1,552,452,847 | 1000 | - | -/// | 1st | 945,000 | 278,950 | 1,627,352,847 | 500 (50%) | 3.23% | -/// | 2nd | 1,050,000 | 383,950 | 1,679,852,847 | 250 (50%) | 1.57% | -/// | 3rd | 1,260,000 | 593,950 | 1,732,352,847 | 125 (50%) | 0.76% | -/// | 4th | 1,470,000 | 803,950 | 1,758,602,847 | 62.5 (50%) | 0.37% | -/// | - | 2,197,560 | 1,531,510 | 1,804,075,347 | 62.5 (0%) | 0.18% | -/// -/// The above is for mainnet, which has a burnchain year of 52596 blocks and starts at burnchain height 666050. -/// The `Offset Height` column is simply the difference between `Bitcoin Height` and 666050. -/// +// From SIP-029: +// +// | Coinbase Interval | Bitcoin Height | Offset Height | Approx. Supply | STX Reward | Annual Inflation | +// |--------------------|----------------|---------------------|------------------|------------|------------------| +// | Current | - | - | 1,552,452,847 | 1000 | - | +// | 1st | 945,000 | 278,950 | 1,627,352,847 | 500 (50%) | 3.23% | +// | 2nd | 1,050,000 | 383,950 | 1,679,852,847 | 250 (50%) | 1.57% | +// | 3rd | 1,260,000 | 593,950 | 1,732,352,847 | 125 (50%) | 0.76% | +// | 4th | 1,470,000 | 803,950 | 1,758,602,847 | 62.5 (50%) | 0.37% | +// | - | 2,197,560 | 1,531,510 | 1,804,075,347 | 62.5 (0%) | 0.18% | +// +// The above is for mainnet, which has a burnchain year of 52596 blocks and starts at burnchain height 666050. + /// Mainnet coinbase intervals, as of SIP-029 -// This static value is lazily initialized using `OnceLock` to avoid unnecessary +// This static value is lazily initialized using `OnceLock` to avoid unnecessary // computation at program startup while ensuring thread safety and one-time initialization. // The intervals define the emission schedule for mainnet and are validated at runtime. pub static COINBASE_INTERVALS_MAINNET: OnceLock<[CoinbaseInterval; 5]> = OnceLock::new(); @@ -173,7 +172,7 @@ pub fn get_coinbase_intervals_mainnet() -> &'static [CoinbaseInterval; 5] { /// Testnet coinbase intervals as defined by SIP-029. /// -/// This static value is lazily initialized using `OnceLock` to avoid unnecessary +/// This static value is lazily initialized using `OnceLock` to avoid unnecessary /// computation at program startup while ensuring thread safety and one-time initialization. /// The intervals define the emission schedule for testnet and are validated at runtime. pub static COINBASE_INTERVALS_TESTNET: OnceLock<[CoinbaseInterval; 5]> = OnceLock::new(); @@ -261,7 +260,7 @@ impl CoinbaseInterval { } let mut ht = intervals[0].effective_start_height; - for interval in intervals { + for interval in intervals { if interval.effective_start_height < ht { return false; } @@ -553,13 +552,11 @@ impl StacksEpochId { | StacksEpochId::Epoch30 => { self.coinbase_reward_pre_sip029(first_burnchain_height, current_burnchain_height) } - StacksEpochId::Epoch31 => { - self.coinbase_reward_sip029( - mainnet, - first_burnchain_height, - current_burnchain_height, - ) - } + StacksEpochId::Epoch31 => self.coinbase_reward_sip029( + mainnet, + first_burnchain_height, + current_burnchain_height, + ), } } } diff --git a/stacks-common/src/types/tests.rs b/stacks-common/src/types/tests.rs index 1e6c44644c..27e7bc610b 100644 --- a/stacks-common/src/types/tests.rs +++ b/stacks-common/src/types/tests.rs @@ -14,12 +14,11 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use crate::types::{get_coinbase_intervals_mainnet, get_coinbase_intervals_testnet}; - use super::{ set_test_coinbase_schedule, CoinbaseInterval, StacksEpochId, COINBASE_INTERVALS_MAINNET, COINBASE_INTERVALS_TESTNET, }; +use crate::types::{get_coinbase_intervals_mainnet, get_coinbase_intervals_testnet}; #[test] fn test_mainnet_coinbase_emissions() { diff --git a/stacks-common/src/util/hash.rs b/stacks-common/src/util/hash.rs index 7b32790100..5ee1165e42 100644 --- a/stacks-common/src/util/hash.rs +++ b/stacks-common/src/util/hash.rs @@ -382,10 +382,10 @@ pub struct MerklePathPoint { pub type MerklePath = Vec>; /// Merkle tree implementation with tagged nodes: -/// +/// /// * A leaf hash is `H(0x00 + data)` /// * A node hash is `H(0x01 + left.hash + right.hash)` -/// +/// /// An empty tree has a root hash of `0x00000...00000`. /// /// NOTE: This is consensus-critical code, because it is used to generate the transaction Merkle From e4f8b0753b9c65427ce58a0f889e989169b2a3f7 Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Thu, 19 Dec 2024 19:31:55 -0500 Subject: [PATCH 3/8] CRC: fix typo Signed-off-by: Jacinta Ferrant --- stacks-common/src/util/vrf.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/stacks-common/src/util/vrf.rs b/stacks-common/src/util/vrf.rs index e61ce7a8bb..0c2b2c3dad 100644 --- a/stacks-common/src/util/vrf.rs +++ b/stacks-common/src/util/vrf.rs @@ -429,7 +429,7 @@ impl VRF { /// * its public key (an ed25519 curve point) /// * a new private key derived from the hash of the private key /// * a truncated hash of the private key - /// Idea borroed from Algorand (https://github.com/algorand/libsodium/blob/draft-irtf-cfrg-vrf-03/src/libsodium/crypto_vrf/ietfdraft03/prove.c) + /// Idea borrowed from Algorand (https://github.com/algorand/libsodium/blob/draft-irtf-cfrg-vrf-03/src/libsodium/crypto_vrf/ietfdraft03/prove.c) fn expand_privkey(secret: &VRFPrivateKey) -> (VRFPublicKey, ed25519_Scalar, [u8; 32]) { let mut hasher = Sha512::new(); let mut h = [0u8; 64]; From a482b493d9e069c7e4fa15df23d1eb499a8d265b Mon Sep 17 00:00:00 2001 From: Brice Dobry Date: Thu, 19 Dec 2024 20:40:24 -0500 Subject: [PATCH 4/8] test: fix bitcoin test yaml --- .github/workflows/bitcoin-tests.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/bitcoin-tests.yml b/.github/workflows/bitcoin-tests.yml index 5ae22b272e..e2815aa505 100644 --- a/.github/workflows/bitcoin-tests.yml +++ b/.github/workflows/bitcoin-tests.yml @@ -89,7 +89,8 @@ jobs: - tests::nakamoto_integrations::miner_writes_proposed_block_to_stackerdb - tests::nakamoto_integrations::correct_burn_outs - tests::nakamoto_integrations::vote_for_aggregate_key_burn_op - - tests::nakamoto_integrations::follower_bootup + - tests::nakamoto_integrations::follower_bootup_simple + - tests::nakamoto_integrations::follower_bootup_custom_chain_id - tests::nakamoto_integrations::forked_tenure_is_ignored - tests::nakamoto_integrations::nakamoto_attempt_time - tests::nakamoto_integrations::skip_mining_long_tx From 767dd7e3f580ba40850bfce2f067fd61578488d3 Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Fri, 20 Dec 2024 19:25:07 -0500 Subject: [PATCH 5/8] CRC: cleanup Signed-off-by: Jacinta Ferrant --- libsigner/src/v0/messages.rs | 2 +- stacks-common/src/types/chainstate.rs | 3 +++ stacks-common/src/types/mod.rs | 2 +- stacks-common/src/util/hash.rs | 3 +-- stacks-signer/src/client/stackerdb.rs | 2 +- stackslib/src/chainstate/nakamoto/miner.rs | 2 +- stackslib/src/chainstate/nakamoto/mod.rs | 2 +- .../src/chainstate/nakamoto/tests/mod.rs | 20 +++++++++---------- stackslib/src/chainstate/stacks/block.rs | 18 ++++++++--------- stackslib/src/chainstate/stacks/db/blocks.rs | 4 ++-- .../src/chainstate/stacks/db/transactions.rs | 2 +- stackslib/src/chainstate/stacks/miner.rs | 6 +++--- stackslib/src/chainstate/stacks/mod.rs | 4 ++-- .../stacks/tests/block_construction.rs | 4 ++-- .../src/chainstate/stacks/transaction.rs | 2 +- stackslib/src/net/tests/relay/epoch2x.rs | 4 ++-- .../src/tests/neon_integrations.rs | 2 +- 17 files changed, 42 insertions(+), 40 deletions(-) diff --git a/libsigner/src/v0/messages.rs b/libsigner/src/v0/messages.rs index 087c4ba7a3..4d27f0e9d1 100644 --- a/libsigner/src/v0/messages.rs +++ b/libsigner/src/v0/messages.rs @@ -1237,7 +1237,7 @@ mod test { txs: vec![], }; let tx_merkle_root = { - let txid_vecs = block + let txid_vecs: Vec<_> = block .txs .iter() .map(|tx| tx.txid().as_bytes().to_vec()) diff --git a/stacks-common/src/types/chainstate.rs b/stacks-common/src/types/chainstate.rs index 9aa91a431a..630ce70c9d 100644 --- a/stacks-common/src/types/chainstate.rs +++ b/stacks-common/src/types/chainstate.rs @@ -78,6 +78,9 @@ impl TrieHash { } /// Convert to a String that can be used in e.g. sqlite + /// If we did not implement this seperate from Display, + /// we would use the stacks_common::util::hash::to_hex function + /// which is the unrolled version of this function. #[allow(clippy::inherent_to_string_shadow_display)] pub fn to_string(&self) -> String { let s = format!("{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", diff --git a/stacks-common/src/types/mod.rs b/stacks-common/src/types/mod.rs index 283c5f3b9a..3ec090a907 100644 --- a/stacks-common/src/types/mod.rs +++ b/stacks-common/src/types/mod.rs @@ -260,7 +260,7 @@ impl CoinbaseInterval { } let mut ht = intervals[0].effective_start_height; - for interval in intervals { + for interval in intervals.iter().skip(1) { if interval.effective_start_height < ht { return false; } diff --git a/stacks-common/src/util/hash.rs b/stacks-common/src/util/hash.rs index 5ee1165e42..666e72c8e2 100644 --- a/stacks-common/src/util/hash.rs +++ b/stacks-common/src/util/hash.rs @@ -390,7 +390,6 @@ pub type MerklePath = Vec>; /// /// NOTE: This is consensus-critical code, because it is used to generate the transaction Merkle /// tree roots in Stacks blocks. -#[allow(clippy::ptr_arg)] impl MerkleTree where H: MerkleHashFunc + Clone + PartialEq + fmt::Debug, @@ -399,7 +398,7 @@ where MerkleTree { nodes: vec![] } } - pub fn new(data: &Vec>) -> MerkleTree { + pub fn new(data: &[Vec]) -> MerkleTree { if data.is_empty() { return MerkleTree { nodes: vec![] }; } diff --git a/stacks-signer/src/client/stackerdb.rs b/stacks-signer/src/client/stackerdb.rs index 934686d1c2..0316976a4c 100644 --- a/stacks-signer/src/client/stackerdb.rs +++ b/stacks-signer/src/client/stackerdb.rs @@ -270,7 +270,7 @@ mod tests { txs: vec![], }; let tx_merkle_root = { - let txid_vecs = block + let txid_vecs: Vec<_> = block .txs .iter() .map(|tx| tx.txid().as_bytes().to_vec()) diff --git a/stackslib/src/chainstate/nakamoto/miner.rs b/stackslib/src/chainstate/nakamoto/miner.rs index 68cdb2454a..9c5fb0292c 100644 --- a/stackslib/src/chainstate/nakamoto/miner.rs +++ b/stackslib/src/chainstate/nakamoto/miner.rs @@ -464,7 +464,7 @@ impl NakamotoBlockBuilder { /// Returns the unsigned Nakamoto block fn finalize_block(&mut self, clarity_tx: &mut ClarityTx) -> NakamotoBlock { // done! Calculate state root and tx merkle root - let txid_vecs = self + let txid_vecs: Vec<_> = self .txs .iter() .map(|tx| tx.txid().as_bytes().to_vec()) diff --git a/stackslib/src/chainstate/nakamoto/mod.rs b/stackslib/src/chainstate/nakamoto/mod.rs index 929d8dfe90..da74823293 100644 --- a/stackslib/src/chainstate/nakamoto/mod.rs +++ b/stackslib/src/chainstate/nakamoto/mod.rs @@ -4987,7 +4987,7 @@ impl StacksMessageCodec for NakamotoBlock { } // header and transactions must be consistent - let txid_vecs = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); + let txid_vecs: Vec<_> = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); let merkle_tree = MerkleTree::new(&txid_vecs); let tx_merkle_root: Sha512Trunc256Sum = merkle_tree.root(); diff --git a/stackslib/src/chainstate/nakamoto/tests/mod.rs b/stackslib/src/chainstate/nakamoto/tests/mod.rs index 94ef81c077..fd06919203 100644 --- a/stackslib/src/chainstate/nakamoto/tests/mod.rs +++ b/stackslib/src/chainstate/nakamoto/tests/mod.rs @@ -616,7 +616,7 @@ pub fn test_load_store_update_nakamoto_blocks() { let epoch2_txs = vec![coinbase_tx.clone()]; let epoch2_tx_merkle_root = { - let txid_vecs = epoch2_txs + let txid_vecs: Vec<_> = epoch2_txs .iter() .map(|tx| tx.txid().as_bytes().to_vec()) .collect(); @@ -710,7 +710,7 @@ pub fn test_load_store_update_nakamoto_blocks() { let nakamoto_txs = vec![tenure_change_tx.clone(), coinbase_tx.clone()]; let nakamoto_tx_merkle_root = { - let txid_vecs = nakamoto_txs + let txid_vecs: Vec<_> = nakamoto_txs .iter() .map(|tx| tx.txid().as_bytes().to_vec()) .collect(); @@ -720,7 +720,7 @@ pub fn test_load_store_update_nakamoto_blocks() { let nakamoto_txs_2 = vec![stx_transfer_tx.clone()]; let nakamoto_tx_merkle_root_2 = { - let txid_vecs = nakamoto_txs_2 + let txid_vecs: Vec<_> = nakamoto_txs_2 .iter() .map(|tx| tx.txid().as_bytes().to_vec()) .collect(); @@ -730,7 +730,7 @@ pub fn test_load_store_update_nakamoto_blocks() { let nakamoto_txs_3 = vec![stx_transfer_tx_3.clone()]; let nakamoto_tx_merkle_root_3 = { - let txid_vecs = nakamoto_txs_3 + let txid_vecs: Vec<_> = nakamoto_txs_3 .iter() .map(|tx| tx.txid().as_bytes().to_vec()) .collect(); @@ -740,7 +740,7 @@ pub fn test_load_store_update_nakamoto_blocks() { let nakamoto_txs_4 = vec![stx_transfer_tx_4.clone()]; let nakamoto_tx_merkle_root_4 = { - let txid_vecs = nakamoto_txs_4 + let txid_vecs: Vec<_> = nakamoto_txs_4 .iter() .map(|tx| tx.txid().as_bytes().to_vec()) .collect(); @@ -1780,7 +1780,7 @@ fn test_nakamoto_block_static_verification() { let nakamoto_txs = vec![tenure_change_tx.clone(), coinbase_tx.clone()]; let nakamoto_tx_merkle_root = { - let txid_vecs = nakamoto_txs + let txid_vecs: Vec<_> = nakamoto_txs .iter() .map(|tx| tx.txid().as_bytes().to_vec()) .collect(); @@ -1790,7 +1790,7 @@ fn test_nakamoto_block_static_verification() { let nakamoto_recipient_txs = vec![tenure_change_tx.clone(), coinbase_recipient_tx.clone()]; let nakamoto_recipient_tx_merkle_root = { - let txid_vecs = nakamoto_recipient_txs + let txid_vecs: Vec<_> = nakamoto_recipient_txs .iter() .map(|tx| tx.txid().as_bytes().to_vec()) .collect(); @@ -1803,7 +1803,7 @@ fn test_nakamoto_block_static_verification() { coinbase_shadow_recipient_tx.clone(), ]; let nakamoto_shadow_recipient_tx_merkle_root = { - let txid_vecs = nakamoto_shadow_recipient_txs + let txid_vecs: Vec<_> = nakamoto_shadow_recipient_txs .iter() .map(|tx| tx.txid().as_bytes().to_vec()) .collect(); @@ -1813,7 +1813,7 @@ fn test_nakamoto_block_static_verification() { let nakamoto_txs_bad_ch = vec![tenure_change_tx_bad_ch.clone(), coinbase_tx.clone()]; let nakamoto_tx_merkle_root_bad_ch = { - let txid_vecs = nakamoto_txs_bad_ch + let txid_vecs: Vec<_> = nakamoto_txs_bad_ch .iter() .map(|tx| tx.txid().as_bytes().to_vec()) .collect(); @@ -1824,7 +1824,7 @@ fn test_nakamoto_block_static_verification() { let nakamoto_txs_bad_miner_sig = vec![tenure_change_tx_bad_miner_sig.clone(), coinbase_tx.clone()]; let nakamoto_tx_merkle_root_bad_miner_sig = { - let txid_vecs = nakamoto_txs_bad_miner_sig + let txid_vecs: Vec<_> = nakamoto_txs_bad_miner_sig .iter() .map(|tx| tx.txid().as_bytes().to_vec()) .collect(); diff --git a/stackslib/src/chainstate/stacks/block.rs b/stackslib/src/chainstate/stacks/block.rs index 85bfcc5576..e0efe6a7c0 100644 --- a/stackslib/src/chainstate/stacks/block.rs +++ b/stackslib/src/chainstate/stacks/block.rs @@ -338,7 +338,7 @@ impl StacksMessageCodec for StacksBlock { } // header and transactions must be consistent - let txid_vecs = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); + let txid_vecs: Vec<_> = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); let merkle_tree = MerkleTree::::new(&txid_vecs); let tx_merkle_root = merkle_tree.root(); @@ -388,7 +388,7 @@ impl StacksBlock { state_index_root: &TrieHash, microblock_pubkey_hash: &Hash160, ) -> StacksBlock { - let txids = txs + let txids: Vec<_> = txs .iter() .map(|ref tx| tx.txid().as_bytes().to_vec()) .collect(); @@ -853,7 +853,7 @@ impl StacksMessageCodec for StacksMicroblock { } // header and transactions must be consistent - let txid_vecs = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); + let txid_vecs: Vec<_> = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); let merkle_tree = MerkleTree::::new(&txid_vecs); let tx_merkle_root = merkle_tree.root(); @@ -880,7 +880,7 @@ impl StacksMicroblock { parent_block_hash: &BlockHeaderHash, txs: Vec, ) -> StacksMicroblock { - let txids = txs + let txids: Vec<_> = txs .iter() .map(|ref tx| tx.txid().as_bytes().to_vec()) .collect(); @@ -897,7 +897,7 @@ impl StacksMicroblock { parent_header: &StacksMicroblockHeader, txs: Vec, ) -> Option { - let txids = txs + let txids: Vec<_> = txs .iter() .map(|ref tx| tx.txid().as_bytes().to_vec()) .collect(); @@ -1173,7 +1173,7 @@ mod test { all_txs[3 * i + 2].clone(), ]; - let txid_vecs = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); + let txid_vecs: Vec<_> = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); let merkle_tree = MerkleTree::::new(&txid_vecs); let tx_merkle_root = merkle_tree.root(); @@ -1501,7 +1501,7 @@ mod test { let txs_dup = vec![tx_coinbase.clone(), tx_dup.clone(), tx_dup.clone()]; let get_tx_root = |txs: &Vec| { - let txid_vecs = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); + let txid_vecs: Vec<_> = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); let merkle_tree = MerkleTree::::new(&txid_vecs); let tx_merkle_root = merkle_tree.root(); @@ -1628,7 +1628,7 @@ mod test { let txs_dup = vec![tx_dup.clone(), tx_dup.clone()]; let get_tx_root = |txs: &Vec| { - let txid_vecs = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); + let txid_vecs: Vec<_> = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); let merkle_tree = MerkleTree::::new(&txid_vecs); let tx_merkle_root = merkle_tree.root(); @@ -1718,7 +1718,7 @@ mod test { StacksEpochId::Epoch30, ]; let get_tx_root = |txs: &Vec| { - let txid_vecs = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); + let txid_vecs: Vec<_> = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); let merkle_tree = MerkleTree::::new(&txid_vecs); let tx_merkle_root = merkle_tree.root(); diff --git a/stackslib/src/chainstate/stacks/db/blocks.rs b/stackslib/src/chainstate/stacks/db/blocks.rs index 233a9d5978..df8db66aca 100644 --- a/stackslib/src/chainstate/stacks/db/blocks.rs +++ b/stackslib/src/chainstate/stacks/db/blocks.rs @@ -7165,7 +7165,7 @@ pub mod test { all_txs[3 * i + 2].clone(), ]; - let txid_vecs = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); + let txid_vecs: Vec<_> = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); let merkle_tree = MerkleTree::::new(&txid_vecs); let tx_merkle_root = merkle_tree.root(); @@ -8846,7 +8846,7 @@ pub mod test { conflicting_microblock.txs.push(extra_tx); - let txid_vecs = conflicting_microblock + let txid_vecs: Vec<_> = conflicting_microblock .txs .iter() .map(|tx| tx.txid().as_bytes().to_vec()) diff --git a/stackslib/src/chainstate/stacks/db/transactions.rs b/stackslib/src/chainstate/stacks/db/transactions.rs index 3df99ea886..6e34cebd48 100644 --- a/stackslib/src/chainstate/stacks/db/transactions.rs +++ b/stackslib/src/chainstate/stacks/db/transactions.rs @@ -8238,7 +8238,7 @@ pub mod test { // make block let txs = vec![signed_contract_tx]; - let txid_vecs = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); + let txid_vecs: Vec<_> = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); let merkle_tree = MerkleTree::::new(&txid_vecs); let tx_merkle_root = merkle_tree.root(); diff --git a/stackslib/src/chainstate/stacks/miner.rs b/stackslib/src/chainstate/stacks/miner.rs index 082e9c374c..c954be9e0b 100644 --- a/stackslib/src/chainstate/stacks/miner.rs +++ b/stackslib/src/chainstate/stacks/miner.rs @@ -880,7 +880,7 @@ impl<'a> StacksMicroblockBuilder<'a> { return Err(Error::NoTransactionsToMine); } - let txid_vecs = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); + let txid_vecs: Vec<_> = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); let merkle_tree = MerkleTree::::new(&txid_vecs); let tx_merkle_root = merkle_tree.root(); @@ -1704,7 +1704,7 @@ impl StacksBlockBuilder { pub fn finalize_block(&mut self, clarity_tx: &mut ClarityTx) -> StacksBlock { // done! Calculate state root and tx merkle root - let txid_vecs = self + let txid_vecs: Vec<_> = self .txs .iter() .map(|tx| tx.txid().as_bytes().to_vec()) @@ -1770,7 +1770,7 @@ impl StacksBlockBuilder { /// Cut the next microblock. pub fn mine_next_microblock<'a>(&mut self) -> Result { - let txid_vecs = self + let txid_vecs: Vec<_> = self .micro_txs .iter() .map(|tx| tx.txid().as_bytes().to_vec()) diff --git a/stackslib/src/chainstate/stacks/mod.rs b/stackslib/src/chainstate/stacks/mod.rs index fd370a8b12..4a53541c0b 100644 --- a/stackslib/src/chainstate/stacks/mod.rs +++ b/stackslib/src/chainstate/stacks/mod.rs @@ -1602,7 +1602,7 @@ pub mod test { } } - let txid_vecs = txs_anchored + let txid_vecs: Vec<_> = txs_anchored .iter() .map(|tx| tx.txid().as_bytes().to_vec()) .collect(); @@ -1718,7 +1718,7 @@ pub mod test { ); let txs_mblock: Vec<_> = all_txs.into_iter().take(num_txs).collect(); - let txid_vecs = txs_mblock + let txid_vecs: Vec<_> = txs_mblock .iter() .map(|tx| tx.txid().as_bytes().to_vec()) .collect(); diff --git a/stackslib/src/chainstate/stacks/tests/block_construction.rs b/stackslib/src/chainstate/stacks/tests/block_construction.rs index 90fc7f1705..c637f2078d 100644 --- a/stackslib/src/chainstate/stacks/tests/block_construction.rs +++ b/stackslib/src/chainstate/stacks/tests/block_construction.rs @@ -2794,7 +2794,7 @@ fn test_build_microblock_stream_forks() { forked_parent_microblock_stream[i].txs[0] = forked_mblock_tx; // re-calculate merkle root - let txid_vecs = forked_parent_microblock_stream[i].txs + let txid_vecs: Vec<_> = forked_parent_microblock_stream[i].txs .iter() .map(|tx| tx.txid().as_bytes().to_vec()) .collect(); @@ -3121,7 +3121,7 @@ fn test_build_microblock_stream_forks_with_descendants() { forked_parent_microblock_stream[i].txs[0] = forked_mblock_tx; // re-calculate merkle root - let txid_vecs = forked_parent_microblock_stream[i].txs + let txid_vecs: Vec<_> = forked_parent_microblock_stream[i].txs .iter() .map(|tx| tx.txid().as_bytes().to_vec()) .collect(); diff --git a/stackslib/src/chainstate/stacks/transaction.rs b/stackslib/src/chainstate/stacks/transaction.rs index c45b212b68..dfedf3cc64 100644 --- a/stackslib/src/chainstate/stacks/transaction.rs +++ b/stackslib/src/chainstate/stacks/transaction.rs @@ -345,7 +345,7 @@ where H: MerkleHashFunc + Clone + PartialEq + fmt::Debug, { fn from_iter>(iter: T) -> Self { - let txid_vec = iter + let txid_vec: Vec<_> = iter .into_iter() .map(|x| x.txid().as_bytes().to_vec()) .collect(); diff --git a/stackslib/src/net/tests/relay/epoch2x.rs b/stackslib/src/net/tests/relay/epoch2x.rs index f4fc8d9eb8..dbe4ea7dc4 100644 --- a/stackslib/src/net/tests/relay/epoch2x.rs +++ b/stackslib/src/net/tests/relay/epoch2x.rs @@ -2968,7 +2968,7 @@ fn process_new_blocks_rejects_problematic_asts() { let mut bad_block = bad_block.0; bad_block.txs.push(bad_tx.clone()); - let txid_vecs = bad_block + let txid_vecs: Vec<_> = bad_block .txs .iter() .map(|tx| tx.txid().as_bytes().to_vec()) @@ -3024,7 +3024,7 @@ fn process_new_blocks_rejects_problematic_asts() { bad_mblock.txs.push(bad_tx.clone()); // force it in anyway - let txid_vecs = bad_mblock + let txid_vecs: Vec<_> = bad_mblock .txs .iter() .map(|tx| tx.txid().as_bytes().to_vec()) diff --git a/testnet/stacks-node/src/tests/neon_integrations.rs b/testnet/stacks-node/src/tests/neon_integrations.rs index fc363d3db8..482cfd1fc4 100644 --- a/testnet/stacks-node/src/tests/neon_integrations.rs +++ b/testnet/stacks-node/src/tests/neon_integrations.rs @@ -3378,7 +3378,7 @@ fn make_signed_microblock( ) -> StacksMicroblock { let mut rng = rand::thread_rng(); - let txid_vecs = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); + let txid_vecs: Vec<_> = txs.iter().map(|tx| tx.txid().as_bytes().to_vec()).collect(); let merkle_tree = MerkleTree::::new(&txid_vecs); let tx_merkle_root = merkle_tree.root(); From 3d2949da0e96e4fd69234d8492cb7d107cdc8222 Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Mon, 30 Dec 2024 11:33:02 -0500 Subject: [PATCH 6/8] CRC: use lazyLock instead of OnceLock for static sync global variable Signed-off-by: Jacinta Ferrant --- stacks-common/src/types/mod.rs | 133 ++++++++++++++----------------- stacks-common/src/types/tests.rs | 69 ++++++++-------- 2 files changed, 92 insertions(+), 110 deletions(-) diff --git a/stacks-common/src/types/mod.rs b/stacks-common/src/types/mod.rs index 3ec090a907..93ebd17bc0 100644 --- a/stacks-common/src/types/mod.rs +++ b/stacks-common/src/types/mod.rs @@ -18,7 +18,7 @@ use std::cell::LazyCell; use std::cmp::Ordering; use std::fmt; use std::ops::{Deref, DerefMut, Index, IndexMut}; -use std::sync::OnceLock; +use std::sync::LazyLock; #[cfg(feature = "canonical")] pub mod sqlite; @@ -136,75 +136,60 @@ pub struct CoinbaseInterval { // The above is for mainnet, which has a burnchain year of 52596 blocks and starts at burnchain height 666050. /// Mainnet coinbase intervals, as of SIP-029 -// This static value is lazily initialized using `OnceLock` to avoid unnecessary -// computation at program startup while ensuring thread safety and one-time initialization. -// The intervals define the emission schedule for mainnet and are validated at runtime. -pub static COINBASE_INTERVALS_MAINNET: OnceLock<[CoinbaseInterval; 5]> = OnceLock::new(); - -pub fn get_coinbase_intervals_mainnet() -> &'static [CoinbaseInterval; 5] { - COINBASE_INTERVALS_MAINNET.get_or_init(|| { - let emissions_schedule = [ - CoinbaseInterval { - coinbase: 1_000 * u128::from(MICROSTACKS_PER_STACKS), - effective_start_height: 0, - }, - CoinbaseInterval { - coinbase: 500 * u128::from(MICROSTACKS_PER_STACKS), - effective_start_height: 278_950, - }, - CoinbaseInterval { - coinbase: 250 * u128::from(MICROSTACKS_PER_STACKS), - effective_start_height: 383_950, - }, - CoinbaseInterval { - coinbase: 125 * u128::from(MICROSTACKS_PER_STACKS), - effective_start_height: 593_950, - }, - CoinbaseInterval { - coinbase: (625 * u128::from(MICROSTACKS_PER_STACKS)) / 10, - effective_start_height: 803_950, - }, - ]; - assert!(CoinbaseInterval::check_order(&emissions_schedule)); - emissions_schedule - }) -} - -/// Testnet coinbase intervals as defined by SIP-029. -/// -/// This static value is lazily initialized using `OnceLock` to avoid unnecessary -/// computation at program startup while ensuring thread safety and one-time initialization. -/// The intervals define the emission schedule for testnet and are validated at runtime. -pub static COINBASE_INTERVALS_TESTNET: OnceLock<[CoinbaseInterval; 5]> = OnceLock::new(); - -pub fn get_coinbase_intervals_testnet() -> &'static [CoinbaseInterval; 5] { - COINBASE_INTERVALS_TESTNET.get_or_init(|| { - let emissions_schedule = [ - CoinbaseInterval { - coinbase: 1_000 * u128::from(MICROSTACKS_PER_STACKS), - effective_start_height: 0, - }, - CoinbaseInterval { - coinbase: 500 * u128::from(MICROSTACKS_PER_STACKS), - effective_start_height: 77_777, - }, - CoinbaseInterval { - coinbase: 250 * u128::from(MICROSTACKS_PER_STACKS), - effective_start_height: 77_777 * 7, - }, - CoinbaseInterval { - coinbase: 125 * u128::from(MICROSTACKS_PER_STACKS), - effective_start_height: 77_777 * 14, - }, - CoinbaseInterval { - coinbase: (625 * u128::from(MICROSTACKS_PER_STACKS)) / 10, - effective_start_height: 77_777 * 21, - }, - ]; - assert!(CoinbaseInterval::check_order(&emissions_schedule)); - emissions_schedule - }) -} +pub static COINBASE_INTERVALS_MAINNET: LazyLock<[CoinbaseInterval; 5]> = LazyLock::new(|| { + let emissions_schedule = [ + CoinbaseInterval { + coinbase: 1_000 * u128::from(MICROSTACKS_PER_STACKS), + effective_start_height: 0, + }, + CoinbaseInterval { + coinbase: 500 * u128::from(MICROSTACKS_PER_STACKS), + effective_start_height: 278_950, + }, + CoinbaseInterval { + coinbase: 250 * u128::from(MICROSTACKS_PER_STACKS), + effective_start_height: 383_950, + }, + CoinbaseInterval { + coinbase: 125 * u128::from(MICROSTACKS_PER_STACKS), + effective_start_height: 593_950, + }, + CoinbaseInterval { + coinbase: (625 * u128::from(MICROSTACKS_PER_STACKS)) / 10, + effective_start_height: 803_950, + }, + ]; + assert!(CoinbaseInterval::check_order(&emissions_schedule)); + emissions_schedule +}); + +/// Testnet coinbase intervals, as of SIP-029 +pub static COINBASE_INTERVALS_TESTNET: LazyLock<[CoinbaseInterval; 5]> = LazyLock::new(|| { + let emissions_schedule = [ + CoinbaseInterval { + coinbase: 1_000 * u128::from(MICROSTACKS_PER_STACKS), + effective_start_height: 0, + }, + CoinbaseInterval { + coinbase: 500 * u128::from(MICROSTACKS_PER_STACKS), + effective_start_height: 77_777, + }, + CoinbaseInterval { + coinbase: 250 * u128::from(MICROSTACKS_PER_STACKS), + effective_start_height: 77_777 * 7, + }, + CoinbaseInterval { + coinbase: 125 * u128::from(MICROSTACKS_PER_STACKS), + effective_start_height: 77_777 * 14, + }, + CoinbaseInterval { + coinbase: (625 * u128::from(MICROSTACKS_PER_STACKS)) / 10, + effective_start_height: 77_777 * 21, + }, + ]; + assert!(CoinbaseInterval::check_order(&emissions_schedule)); + emissions_schedule +}); /// Used for testing to substitute a coinbase schedule #[cfg(any(test, feature = "testing"))] @@ -500,18 +485,18 @@ impl StacksEpochId { } if mainnet { - get_coinbase_intervals_mainnet().to_vec() + COINBASE_INTERVALS_MAINNET.to_vec() } else { - get_coinbase_intervals_testnet().to_vec() + COINBASE_INTERVALS_TESTNET.to_vec() } } #[cfg(not(any(test, feature = "testing")))] pub(crate) fn get_coinbase_intervals(mainnet: bool) -> Vec { if mainnet { - get_coinbase_intervals_mainnet().to_vec() + COINBASE_INTERVALS_MAINNET.to_vec() } else { - get_coinbase_intervals_testnet().to_vec() + COINBASE_INTERVALS_TESTNET.to_vec() } } diff --git a/stacks-common/src/types/tests.rs b/stacks-common/src/types/tests.rs index 27e7bc610b..20676999e7 100644 --- a/stacks-common/src/types/tests.rs +++ b/stacks-common/src/types/tests.rs @@ -18,56 +18,53 @@ use super::{ set_test_coinbase_schedule, CoinbaseInterval, StacksEpochId, COINBASE_INTERVALS_MAINNET, COINBASE_INTERVALS_TESTNET, }; -use crate::types::{get_coinbase_intervals_mainnet, get_coinbase_intervals_testnet}; #[test] fn test_mainnet_coinbase_emissions() { - let coinbase_intervals_mainnet = get_coinbase_intervals_mainnet(); - assert_eq!(coinbase_intervals_mainnet.len(), 5); - assert_eq!(coinbase_intervals_mainnet[0].coinbase, 1_000_000_000); - assert_eq!(coinbase_intervals_mainnet[1].coinbase, 500_000_000); - assert_eq!(coinbase_intervals_mainnet[2].coinbase, 250_000_000); - assert_eq!(coinbase_intervals_mainnet[3].coinbase, 125_000_000); - assert_eq!(coinbase_intervals_mainnet[4].coinbase, 62_500_000); + assert_eq!(COINBASE_INTERVALS_MAINNET.len(), 5); + assert_eq!(COINBASE_INTERVALS_MAINNET[0].coinbase, 1_000_000_000); + assert_eq!(COINBASE_INTERVALS_MAINNET[1].coinbase, 500_000_000); + assert_eq!(COINBASE_INTERVALS_MAINNET[2].coinbase, 250_000_000); + assert_eq!(COINBASE_INTERVALS_MAINNET[3].coinbase, 125_000_000); + assert_eq!(COINBASE_INTERVALS_MAINNET[4].coinbase, 62_500_000); // heights from SIP-029 assert_eq!( - coinbase_intervals_mainnet[0].effective_start_height, + COINBASE_INTERVALS_MAINNET[0].effective_start_height, 666_050 - 666_050 ); assert_eq!( - coinbase_intervals_mainnet[1].effective_start_height, + COINBASE_INTERVALS_MAINNET[1].effective_start_height, 945_000 - 666_050 ); assert_eq!( - coinbase_intervals_mainnet[2].effective_start_height, + COINBASE_INTERVALS_MAINNET[2].effective_start_height, 1_050_000 - 666_050 ); assert_eq!( - coinbase_intervals_mainnet[3].effective_start_height, + COINBASE_INTERVALS_MAINNET[3].effective_start_height, 1_260_000 - 666_050 ); assert_eq!( - coinbase_intervals_mainnet[4].effective_start_height, + COINBASE_INTERVALS_MAINNET[4].effective_start_height, 1_470_000 - 666_050 ); } #[test] fn test_get_coinbase_at_effective_height() { - let coinbase_intervals_mainnet = get_coinbase_intervals_mainnet(); - assert!(CoinbaseInterval::check_order(coinbase_intervals_mainnet)); + assert!(CoinbaseInterval::check_order(&*COINBASE_INTERVALS_MAINNET)); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 666050 - 666050 ), 1_000_000_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 666051 - 666050 ), 1_000_000_000 @@ -75,21 +72,21 @@ fn test_get_coinbase_at_effective_height() { assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 944_999 - 666050 ), 1_000_000_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 945_000 - 666050 ), 500_000_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 945_001 - 666050 ), 500_000_000 @@ -97,21 +94,21 @@ fn test_get_coinbase_at_effective_height() { assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 1_049_999 - 666050 ), 500_000_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 1_050_000 - 666050 ), 250_000_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 1_050_001 - 666050 ), 250_000_000 @@ -119,21 +116,21 @@ fn test_get_coinbase_at_effective_height() { assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 1_259_999 - 666050 ), 250_000_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 1_260_000 - 666050 ), 125_000_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 1_260_001 - 666050 ), 125_000_000 @@ -141,21 +138,21 @@ fn test_get_coinbase_at_effective_height() { assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 1_469_999 - 666050 ), 125_000_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 1_470_000 - 666050 ), 62_500_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 1_470_001 - 666050 ), 62_500_000 @@ -163,21 +160,21 @@ fn test_get_coinbase_at_effective_height() { assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 2_197_559 - 666050 ), 62_500_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 2_197_560 - 666050 ), 62_500_000 ); assert_eq!( CoinbaseInterval::get_coinbase_at_effective_height( - coinbase_intervals_mainnet, + &*COINBASE_INTERVALS_MAINNET, 2_197_561 - 666050 ), 62_500_000 @@ -330,11 +327,11 @@ fn test_set_coinbase_intervals() { assert_eq!( StacksEpochId::get_coinbase_intervals(true), - get_coinbase_intervals_mainnet() + *COINBASE_INTERVALS_MAINNET ); assert_eq!( StacksEpochId::get_coinbase_intervals(false), - get_coinbase_intervals_testnet() + *COINBASE_INTERVALS_TESTNET ); set_test_coinbase_schedule(Some(new_sched.clone())); @@ -346,10 +343,10 @@ fn test_set_coinbase_intervals() { assert_eq!( StacksEpochId::get_coinbase_intervals(true), - get_coinbase_intervals_mainnet() + *COINBASE_INTERVALS_MAINNET ); assert_eq!( StacksEpochId::get_coinbase_intervals(false), - get_coinbase_intervals_testnet() + *COINBASE_INTERVALS_TESTNET ); } From fb6c6834d70586fb9ebafce0afd4ae3b2f92b03a Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Tue, 31 Dec 2024 10:38:33 -0500 Subject: [PATCH 7/8] Fix profile-sqlite feature build Signed-off-by: Jacinta Ferrant --- stackslib/src/util_lib/db.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/stackslib/src/util_lib/db.rs b/stackslib/src/util_lib/db.rs index 53f597daa2..197384d389 100644 --- a/stackslib/src/util_lib/db.rs +++ b/stackslib/src/util_lib/db.rs @@ -681,6 +681,7 @@ pub fn tx_begin_immediate_sqlite<'a>(conn: &'a mut Connection) -> Result Date: Mon, 30 Dec 2024 14:20:28 -0500 Subject: [PATCH 8/8] Fix all redundant_field_name warnings in stackslib Signed-off-by: Jacinta Ferrant --- stackslib/src/burnchains/bitcoin/address.rs | 12 ++-- stackslib/src/burnchains/bitcoin/bits.rs | 6 +- stackslib/src/burnchains/bitcoin/blocks.rs | 24 +++---- stackslib/src/burnchains/bitcoin/indexer.rs | 4 +- stackslib/src/burnchains/bitcoin/mod.rs | 4 +- stackslib/src/burnchains/bitcoin/network.rs | 4 +- stackslib/src/burnchains/bitcoin/spv.rs | 12 ++-- stackslib/src/burnchains/db.rs | 4 +- stackslib/src/burnchains/tests/affirmation.rs | 4 +- stackslib/src/burnchains/tests/db.rs | 2 +- stackslib/src/burnchains/tests/mod.rs | 8 +-- stackslib/src/chainstate/burn/db/sortdb.rs | 40 +++++------ .../burn/operations/leader_block_commit.rs | 20 +++--- .../burn/operations/leader_key_register.rs | 12 ++-- .../chainstate/burn/operations/stack_stx.rs | 4 +- stackslib/src/chainstate/burn/sortition.rs | 4 +- .../src/chainstate/nakamoto/tests/mod.rs | 2 +- stackslib/src/chainstate/stacks/address.rs | 2 +- stackslib/src/chainstate/stacks/auth.rs | 16 ++--- stackslib/src/chainstate/stacks/block.rs | 23 ++----- .../src/chainstate/stacks/db/accounts.rs | 4 +- stackslib/src/chainstate/stacks/db/blocks.rs | 19 +++--- stackslib/src/chainstate/stacks/db/mod.rs | 12 ++-- .../src/chainstate/stacks/db/transactions.rs | 14 ++-- .../src/chainstate/stacks/db/unconfirmed.rs | 2 +- stackslib/src/chainstate/stacks/index/marf.rs | 2 +- stackslib/src/chainstate/stacks/index/node.rs | 20 +++--- .../src/chainstate/stacks/index/storage.rs | 20 +++--- stackslib/src/chainstate/stacks/miner.rs | 8 +-- stackslib/src/chainstate/stacks/mod.rs | 4 +- stackslib/src/chainstate/stacks/tests/mod.rs | 14 ++-- .../src/chainstate/stacks/transaction.rs | 8 +-- stackslib/src/clarity_cli.rs | 4 +- stackslib/src/clarity_vm/clarity.rs | 2 +- stackslib/src/net/api/getheaders.rs | 2 +- .../src/net/api/getmicroblocks_indexed.rs | 4 +- .../src/net/api/gettransaction_unconfirmed.rs | 2 +- stackslib/src/net/asn.rs | 6 +- stackslib/src/net/atlas/mod.rs | 2 +- stackslib/src/net/chat.rs | 18 ++--- stackslib/src/net/codec.rs | 35 +++++----- stackslib/src/net/connection.rs | 12 ++-- stackslib/src/net/db.rs | 67 ++++++++----------- stackslib/src/net/dns.rs | 15 ++--- stackslib/src/net/download/epoch2x.rs | 22 +++--- stackslib/src/net/http/request.rs | 20 +++--- stackslib/src/net/http/response.rs | 20 +++--- stackslib/src/net/inv/epoch2x.rs | 24 +++---- stackslib/src/net/mod.rs | 22 +++--- stackslib/src/net/neighbors/neighbor.rs | 2 +- stackslib/src/net/poll.rs | 6 +- stackslib/src/net/relay.rs | 2 +- stackslib/src/net/tests/relay/epoch2x.rs | 4 +- stackslib/src/util_lib/bloom.rs | 2 +- stackslib/src/util_lib/db.rs | 2 +- 55 files changed, 300 insertions(+), 329 deletions(-) diff --git a/stackslib/src/burnchains/bitcoin/address.rs b/stackslib/src/burnchains/bitcoin/address.rs index bc5ab4b459..e69ede63c3 100644 --- a/stackslib/src/burnchains/bitcoin/address.rs +++ b/stackslib/src/burnchains/bitcoin/address.rs @@ -234,8 +234,8 @@ impl LegacyBitcoinAddress { payload_bytes.copy_from_slice(b); Ok(LegacyBitcoinAddress { - network_id: network_id, - addrtype: addrtype, + network_id, + addrtype, bytes: Hash160(payload_bytes), }) } @@ -436,8 +436,8 @@ impl BitcoinAddress { my_bytes.copy_from_slice(b); Ok(BitcoinAddress::Legacy(LegacyBitcoinAddress { - network_id: network_id, - addrtype: addrtype, + network_id, + addrtype, bytes: Hash160(my_bytes), })) } @@ -478,7 +478,7 @@ impl BitcoinAddress { my_bytes.copy_from_slice(b); Some(BitcoinAddress::Legacy(LegacyBitcoinAddress { - network_id: network_id, + network_id, addrtype: LegacyBitcoinAddressType::PublicKeyHash, bytes: Hash160(my_bytes), })) @@ -492,7 +492,7 @@ impl BitcoinAddress { my_bytes.copy_from_slice(b); Some(BitcoinAddress::Legacy(LegacyBitcoinAddress { - network_id: network_id, + network_id, addrtype: LegacyBitcoinAddressType::ScriptHash, bytes: Hash160(my_bytes), })) diff --git a/stackslib/src/burnchains/bitcoin/bits.rs b/stackslib/src/burnchains/bitcoin/bits.rs index afeaefc0dc..fad0132235 100644 --- a/stackslib/src/burnchains/bitcoin/bits.rs +++ b/stackslib/src/burnchains/bitcoin/bits.rs @@ -136,7 +136,7 @@ impl BitcoinTxInputStructured { Some(BitcoinTxInputStructured { tx_ref: input_txid, - keys: keys, + keys, num_required: num_sigs, in_type: if segwit { BitcoinInputType::SegwitP2SH @@ -184,7 +184,7 @@ impl BitcoinTxInputStructured { let tx_input = BitcoinTxInputStructured { tx_ref: input_txid, - keys: keys, + keys, num_required: num_sigs, in_type: BitcoinInputType::SegwitP2SH, }; @@ -498,7 +498,7 @@ impl BitcoinTxInputRaw { ) -> BitcoinTxInputRaw { BitcoinTxInputRaw { scriptSig: script_sig.clone().into_bytes(), - witness: witness, + witness, tx_ref: input_txid, } } diff --git a/stackslib/src/burnchains/bitcoin/blocks.rs b/stackslib/src/burnchains/bitcoin/blocks.rs index 0cee9e60e6..b4b5dc24e4 100644 --- a/stackslib/src/burnchains/bitcoin/blocks.rs +++ b/stackslib/src/burnchains/bitcoin/blocks.rs @@ -231,7 +231,7 @@ impl BitcoinBlockParser { /// New block parser pub fn new(network_id: BitcoinNetworkType, magic_bytes: MagicBytes) -> BitcoinBlockParser { BitcoinBlockParser { - network_id: network_id, + network_id, magic_bytes: magic_bytes.clone(), } } @@ -478,7 +478,7 @@ impl BitcoinBlockParser { } BitcoinBlock { - block_height: block_height, + block_height, block_hash: BurnchainHeaderHash::from_bitcoin_hash(&block.bitcoin_hash()), parent_block_hash: BurnchainHeaderHash::from_bitcoin_hash(&block.header.prev_blockhash), txs: accepted_txs, @@ -596,7 +596,7 @@ mod tests { let header = deserialize(&header_bin.to_vec()).map_err(|_e| "failed to deserialize header")?; Ok(LoneBlockHeader { - header: header, + header, tx_count: VarInt(0), }) } @@ -655,7 +655,7 @@ mod tests { result: Some(BitcoinTransaction { data_amt: 0, txid: to_txid(&hex_bytes("185c112401590b11acdfea6bb26d2a8e37cb31f24a0c89dbb8cc14b3d6271fb1").unwrap()), - vtxindex: vtxindex, + vtxindex, opcode: '+' as u8, data: hex_bytes("fae543ff5672fb607fe15e16b1c3ef38737c631c7c5d911c6617993c21fba731363f1cfe").unwrap(), inputs: vec![ @@ -702,7 +702,7 @@ mod tests { result: Some(BitcoinTransaction { data_amt: 0, txid: to_txid(&hex_bytes("eb2e84a45cf411e528185a98cd5fb45ed349843a83d39fd4dff2de47adad8c8f").unwrap()), - vtxindex: vtxindex, + vtxindex, opcode: '~' as u8, data: hex_bytes("7061747269636b7374616e6c6579322e6964").unwrap(), inputs: vec![ @@ -745,7 +745,7 @@ mod tests { result: Some(BitcoinTransaction { data_amt: 0, txid: to_txid(&hex_bytes("b908952b30ccfdfa59985dc1ffdd2a22ef054d20fa253510d2af7797dddee459").unwrap()), - vtxindex: vtxindex, + vtxindex, opcode: ':' as u8, data: hex_bytes("666f6f2e74657374").unwrap(), inputs: vec![ @@ -776,7 +776,7 @@ mod tests { result: Some(BitcoinTransaction { data_amt: 0, txid: to_txid(&hex_bytes("16751ca54407b922e3072830cf4be58c5562a6dc350f6703192b673c4cc86182").unwrap()), - vtxindex: vtxindex, + vtxindex, opcode: '?' as u8, data: hex_bytes("9fab7f294936ddb6524a48feff691ecbd0ca9e8f107d845c417a5438d1cb441e827c5126").unwrap(), inputs: vec![ @@ -826,7 +826,7 @@ mod tests { result: Some(BitcoinTransaction { data_amt: 0, txid: to_txid(&hex_bytes("185c112401590b11acdfea6bb26d2a8e37cb31f24a0c89dbb8cc14b3d6271fb1").unwrap()), - vtxindex: vtxindex, + vtxindex, opcode: '+' as u8, data: hex_bytes("fae543ff5672fb607fe15e16b1c3ef38737c631c7c5d911c6617993c21fba731363f1cfe").unwrap(), inputs: vec![ @@ -864,7 +864,7 @@ mod tests { result: Some(BitcoinTransaction { data_amt: 0, txid: to_txid(&hex_bytes("eb2e84a45cf411e528185a98cd5fb45ed349843a83d39fd4dff2de47adad8c8f").unwrap()), - vtxindex: vtxindex, + vtxindex, opcode: '~' as u8, data: hex_bytes("7061747269636b7374616e6c6579322e6964").unwrap(), inputs: vec![ @@ -897,7 +897,7 @@ mod tests { result: Some(BitcoinTransaction { data_amt: 0, txid: to_txid(&hex_bytes("b908952b30ccfdfa59985dc1ffdd2a22ef054d20fa253510d2af7797dddee459").unwrap()), - vtxindex: vtxindex, + vtxindex, opcode: ':' as u8, data: hex_bytes("666f6f2e74657374").unwrap(), inputs: vec![ @@ -928,7 +928,7 @@ mod tests { result: Some(BitcoinTransaction { data_amt: 0, txid: to_txid(&hex_bytes("16751ca54407b922e3072830cf4be58c5562a6dc350f6703192b673c4cc86182").unwrap()), - vtxindex: vtxindex, + vtxindex, opcode: '?' as u8, data: hex_bytes("9fab7f294936ddb6524a48feff691ecbd0ca9e8f107d845c417a5438d1cb441e827c5126").unwrap(), inputs: vec![ @@ -961,7 +961,7 @@ mod tests { result: Some(BitcoinTransaction { data_amt: 0, txid: to_txid(&hex_bytes("8b8a12909d48fd86c06e92270133d320498fb36caa0fdcb3292a8bba99669ebd").unwrap()), - vtxindex: vtxindex, + vtxindex, opcode: '&' as u8, data: hex_bytes("0000cd73fa046543210000000000aa000174657374").unwrap(), inputs: vec![ diff --git a/stackslib/src/burnchains/bitcoin/indexer.rs b/stackslib/src/burnchains/bitcoin/indexer.rs index 3361301675..f7160cf83a 100644 --- a/stackslib/src/burnchains/bitcoin/indexer.rs +++ b/stackslib/src/burnchains/bitcoin/indexer.rs @@ -160,7 +160,7 @@ impl BitcoinIndexerConfig { username: Some("blockstack".to_string()), password: Some("blockstacksystem".to_string()), timeout: 30, - spv_headers_path: spv_headers_path, + spv_headers_path, first_block: 0, magic_bytes: BLOCKSTACK_MAGIC_MAINNET.clone(), epochs: None, @@ -193,7 +193,7 @@ impl BitcoinIndexerRuntime { services: 0, user_agent: USER_AGENT.to_owned(), version_nonce: rng.gen(), - network_id: network_id, + network_id, block_height: 0, last_getdata_send_time: 0, last_getheaders_send_time: 0, diff --git a/stackslib/src/burnchains/bitcoin/mod.rs b/stackslib/src/burnchains/bitcoin/mod.rs index d273b1f5f8..6ba66f524b 100644 --- a/stackslib/src/burnchains/bitcoin/mod.rs +++ b/stackslib/src/burnchains/bitcoin/mod.rs @@ -239,8 +239,8 @@ impl BitcoinBlock { block_height: height, block_hash: hash.clone(), parent_block_hash: parent.clone(), - txs: txs, - timestamp: timestamp, + txs, + timestamp, } } } diff --git a/stackslib/src/burnchains/bitcoin/network.rs b/stackslib/src/burnchains/bitcoin/network.rs index 3e8bf9340c..3411885ddb 100644 --- a/stackslib/src/burnchains/bitcoin/network.rs +++ b/stackslib/src/burnchains/bitcoin/network.rs @@ -45,7 +45,7 @@ impl BitcoinIndexer { pub fn send_message(&mut self, payload: btc_message::NetworkMessage) -> Result<(), btc_error> { let message = btc_message::RawNetworkMessage { magic: network_id_to_bytes(self.runtime.network_id), - payload: payload, + payload, }; self.with_socket(|ref mut sock| { @@ -245,7 +245,7 @@ impl BitcoinIndexer { let payload = btc_message_network::VersionMessage { version: btc_constants::PROTOCOL_VERSION, services: 0, - timestamp: timestamp, + timestamp, receiver: remote_address, sender: sender_address, nonce: self.runtime.version_nonce, diff --git a/stackslib/src/burnchains/bitcoin/spv.rs b/stackslib/src/burnchains/bitcoin/spv.rs index 82cbb7b7f6..f60f90d9e8 100644 --- a/stackslib/src/burnchains/bitcoin/spv.rs +++ b/stackslib/src/burnchains/bitcoin/spv.rs @@ -167,9 +167,9 @@ impl SpvClient { start_block_height: start_block, end_block_height: end_block, cur_block_height: start_block, - network_id: network_id, - readwrite: readwrite, - reverse_order: reverse_order, + network_id, + readwrite, + reverse_order, headers_db: conn, check_txcount: true, }; @@ -197,9 +197,9 @@ impl SpvClient { start_block_height: start_block, end_block_height: end_block, cur_block_height: start_block, - network_id: network_id, - readwrite: readwrite, - reverse_order: reverse_order, + network_id, + readwrite, + reverse_order, headers_db: conn, check_txcount: true, }; diff --git a/stackslib/src/burnchains/db.rs b/stackslib/src/burnchains/db.rs index d5f1e18804..bd300f290e 100644 --- a/stackslib/src/burnchains/db.rs +++ b/stackslib/src/burnchains/db.rs @@ -132,7 +132,7 @@ impl FromRow for BlockCommitMetadata { block_height, vtxindex, affirmation_id, - anchor_block: anchor_block, + anchor_block, anchor_block_descendant, }) } @@ -1106,7 +1106,7 @@ impl BurnchainDB { pub fn tx_begin<'a>(&'a mut self) -> Result, BurnchainError> { let sql_tx = tx_begin_immediate(&mut self.conn)?; - Ok(BurnchainDBTransaction { sql_tx: sql_tx }) + Ok(BurnchainDBTransaction { sql_tx }) } fn inner_get_canonical_chain_tip( diff --git a/stackslib/src/burnchains/tests/affirmation.rs b/stackslib/src/burnchains/tests/affirmation.rs index 8876f3d1aa..12cfd1aac9 100644 --- a/stackslib/src/burnchains/tests/affirmation.rs +++ b/stackslib/src/burnchains/tests/affirmation.rs @@ -249,8 +249,8 @@ pub fn make_simple_key_register( memo: vec![01, 02, 03, 04, 05], txid: next_txid(), - vtxindex: vtxindex, - block_height: block_height, + vtxindex, + block_height, burn_header_hash: burn_header_hash.clone(), } } diff --git a/stackslib/src/burnchains/tests/db.rs b/stackslib/src/burnchains/tests/db.rs index f14243d049..6c474bba44 100644 --- a/stackslib/src/burnchains/tests/db.rs +++ b/stackslib/src/burnchains/tests/db.rs @@ -545,7 +545,7 @@ pub fn make_simple_block_commit( txid: next_txid(), vtxindex: 0, - block_height: block_height, + block_height, burn_parent_modulus: ((block_height - 1) % BURN_BLOCK_MINED_AT_MODULUS) as u8, burn_header_hash: burn_header.block_hash.clone(), }; diff --git a/stackslib/src/burnchains/tests/mod.rs b/stackslib/src/burnchains/tests/mod.rs index c8543b1142..0beb8e5a9d 100644 --- a/stackslib/src/burnchains/tests/mod.rs +++ b/stackslib/src/burnchains/tests/mod.rs @@ -74,9 +74,9 @@ impl BurnchainBlockHeader { ) -> BurnchainBlockHeader { BurnchainBlockHeader { block_height: parent_sn.block_height + 1, - block_hash: block_hash, + block_hash, parent_block_hash: parent_sn.burn_header_hash.clone(), - num_txs: num_txs, + num_txs, timestamp: get_epoch_time_secs(), } } @@ -375,7 +375,7 @@ impl TestBurnchainBlock { burn_header_hash, }), ], - fork_id: fork_id, + fork_id, timestamp: get_epoch_time_secs(), } } @@ -724,7 +724,7 @@ impl TestBurnchainFork { tip_index_root: start_index_root.clone(), blocks: vec![], pending_blocks: vec![], - fork_id: fork_id, + fork_id, } } diff --git a/stackslib/src/chainstate/burn/db/sortdb.rs b/stackslib/src/chainstate/burn/db/sortdb.rs index e399121e07..8dcf30b325 100644 --- a/stackslib/src/chainstate/burn/db/sortdb.rs +++ b/stackslib/src/chainstate/burn/db/sortdb.rs @@ -225,14 +225,14 @@ impl FromRow for LeaderKeyRegisterOp { let memo = memo_bytes.to_vec(); let leader_key_row = LeaderKeyRegisterOp { - txid: txid, - vtxindex: vtxindex, - block_height: block_height, - burn_header_hash: burn_header_hash, - - consensus_hash: consensus_hash, - public_key: public_key, - memo: memo, + txid, + vtxindex, + block_height, + burn_header_hash, + + consensus_hash, + public_key, + memo, }; Ok(leader_key_row) @@ -4536,8 +4536,8 @@ impl SortitionDB { burn_block_height: chain_tip.block_height, burn_block_hash: chain_tip.burn_header_hash, burn_stable_block_height: stable_block_height, - burn_stable_block_hash: burn_stable_block_hash, - last_burn_block_hashes: last_burn_block_hashes, + burn_stable_block_hash, + last_burn_block_hashes, rc_consensus_hash: chain_tip.canonical_stacks_tip_consensus_hash, }) } @@ -7073,7 +7073,7 @@ pub mod tests { .unwrap(), ) .unwrap(), - vtxindex: vtxindex, + vtxindex, block_height: block_height + 1, burn_header_hash: BurnchainHeaderHash([0x01; 32]), }; @@ -7152,7 +7152,7 @@ pub mod tests { .unwrap(), ) .unwrap(), - vtxindex: vtxindex, + vtxindex, block_height: block_height + 1, burn_header_hash: BurnchainHeaderHash([0x01; 32]), }; @@ -7192,7 +7192,7 @@ pub mod tests { .unwrap(), ) .unwrap(), - vtxindex: vtxindex, + vtxindex, block_height: block_height + 2, burn_parent_modulus: ((block_height + 1) % BURN_BLOCK_MINED_AT_MODULUS) as u8, burn_header_hash: BurnchainHeaderHash([0x03; 32]), @@ -7376,7 +7376,7 @@ pub mod tests { .unwrap(), ) .unwrap(), - vtxindex: vtxindex, + vtxindex, block_height: block_height + 2, burn_header_hash: BurnchainHeaderHash([0x03; 32]), }; @@ -7871,7 +7871,7 @@ pub mod tests { .unwrap(), ) .unwrap(), - vtxindex: vtxindex, + vtxindex, block_height: block_height + 1, burn_header_hash: BurnchainHeaderHash([0x01; 32]), }; @@ -7911,7 +7911,7 @@ pub mod tests { .unwrap(), ) .unwrap(), - vtxindex: vtxindex, + vtxindex, block_height: block_height + 2, burn_parent_modulus: ((block_height + 1) % BURN_BLOCK_MINED_AT_MODULUS) as u8, burn_header_hash: BurnchainHeaderHash([0x03; 32]), @@ -7995,7 +7995,7 @@ pub mod tests { let mut snapshot_with_sortition = BlockSnapshot { accumulated_coinbase_ustx: 0, pox_valid: true, - block_height: block_height, + block_height, burn_header_timestamp: get_epoch_time_secs(), burn_header_hash: BurnchainHeaderHash::from_bytes(&[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -8719,7 +8719,7 @@ pub mod tests { 0, 0, 0, 0, 0, 0, 0, i as u8, ]) .unwrap(), - total_burn: total_burn, + total_burn, sortition: false, sortition_hash: SortitionHash([(i as u8); 32]), winning_block_txid: Txid([(i as u8); 32]), @@ -8796,7 +8796,7 @@ pub mod tests { 0, 0, 0, 0, 0, 0, 0, i as u8, ]) .unwrap(), - total_burn: total_burn, + total_burn, sortition: true, sortition_hash: SortitionHash([(i as u8); 32]), winning_block_txid: Txid([(i as u8); 32]), @@ -10087,7 +10087,7 @@ pub mod tests { .unwrap(), ) .unwrap(), - vtxindex: vtxindex, + vtxindex, block_height: block_height + 1, burn_header_hash: BurnchainHeaderHash([0x01; 32]), }; diff --git a/stackslib/src/chainstate/burn/operations/leader_block_commit.rs b/stackslib/src/chainstate/burn/operations/leader_block_commit.rs index a752131668..cf85a02829 100644 --- a/stackslib/src/chainstate/burn/operations/leader_block_commit.rs +++ b/stackslib/src/chainstate/burn/operations/leader_block_commit.rs @@ -102,7 +102,7 @@ impl LeaderBlockCommitOp { ) -> LeaderBlockCommitOp { LeaderBlockCommitOp { sunset_burn: 0, - block_height: block_height, + block_height, burn_parent_modulus: if block_height > 0 { u8::try_from((block_height - 1) % BURN_BLOCK_MINED_AT_MODULUS) .expect("FATAL: unreachable: unable to form u8 from 3-bit number") @@ -117,7 +117,7 @@ impl LeaderBlockCommitOp { parent_block_ptr: 0, parent_vtxindex: 0, memo: vec![0x00], - burn_fee: burn_fee, + burn_fee, input: input.clone(), block_header_hash: block_header_hash.clone(), commit_outs: vec![], @@ -147,12 +147,12 @@ impl LeaderBlockCommitOp { LeaderBlockCommitOp { sunset_burn: 0, new_seed: new_seed.clone(), - key_block_ptr: key_block_ptr, - key_vtxindex: key_vtxindex, + key_block_ptr, + key_vtxindex, parent_block_ptr: parent_block_height, - parent_vtxindex: parent_vtxindex, + parent_vtxindex, memo: vec![], - burn_fee: burn_fee, + burn_fee, input: input.clone(), block_header_hash: block_header_hash.clone(), commit_outs: vec![], @@ -458,7 +458,7 @@ impl LeaderBlockCommitOp { treatment: Vec::new(), txid: tx.txid(), vtxindex: tx.vtxindex(), - block_height: block_height, + block_height, burn_header_hash: block_hash.clone(), }) } @@ -1777,10 +1777,10 @@ mod tests { apparent_sender: BurnchainSigner("mgbpit8FvkVJ9kuXY8QSM5P7eibnhcEMBk".to_string()), txid: Txid::from_hex("502f3e5756de7e1bdba8c713cd2daab44adb5337d14ff668fdc57cc27d67f0d4").unwrap(), - vtxindex: vtxindex, - block_height: block_height, + vtxindex, + block_height, burn_parent_modulus: ((block_height - 1) % BURN_BLOCK_MINED_AT_MODULUS) as u8, - burn_header_hash: burn_header_hash, + burn_header_hash, treatment: vec![], }) }, OpFixture { diff --git a/stackslib/src/chainstate/burn/operations/leader_key_register.rs b/stackslib/src/chainstate/burn/operations/leader_key_register.rs index 5608b6739d..a0406544f1 100644 --- a/stackslib/src/chainstate/burn/operations/leader_key_register.rs +++ b/stackslib/src/chainstate/burn/operations/leader_key_register.rs @@ -163,7 +163,7 @@ impl LeaderKeyRegisterOp { txid: tx.txid(), vtxindex: tx.vtxindex(), - block_height: block_height, + block_height, burn_header_hash: block_hash.clone(), }) } @@ -287,8 +287,8 @@ pub mod tests { memo: vec![01, 02, 03, 04, 05], txid: Txid::from_bytes_be(&hex_bytes("1bfa831b5fc56c858198acb8e77e5863c1e9d8ac26d49ddb914e24d8d4083562").unwrap()).unwrap(), - vtxindex: vtxindex, - block_height: block_height, + vtxindex, + block_height, burn_header_hash: burn_header_hash.clone(), }) }, @@ -301,9 +301,9 @@ pub mod tests { memo: vec![], txid: Txid::from_bytes_be(&hex_bytes("2fbf8d5be32dce49790d203ba59acbb0929d5243413174ff5d26a5c6f23dea65").unwrap()).unwrap(), - vtxindex: vtxindex, - block_height: block_height, - burn_header_hash: burn_header_hash, + vtxindex, + block_height, + burn_header_hash, }) }, OpFixture { diff --git a/stackslib/src/chainstate/burn/operations/stack_stx.rs b/stackslib/src/chainstate/burn/operations/stack_stx.rs index c4c54b9737..67de678659 100644 --- a/stackslib/src/chainstate/burn/operations/stack_stx.rs +++ b/stackslib/src/chainstate/burn/operations/stack_stx.rs @@ -145,7 +145,7 @@ impl PreStxOp { } Ok(PreStxOp { - output: output, + output, txid: tx.txid(), vtxindex: tx.vtxindex(), block_height, @@ -689,7 +689,7 @@ mod tests { txid: Txid([0; 32]), vtxindex: 0, opcode: Opcodes::StackStx as u8, - data: data, + data, data_amt: 0, inputs: vec![BitcoinTxInputStructured { keys: vec![], diff --git a/stackslib/src/chainstate/burn/sortition.rs b/stackslib/src/chainstate/burn/sortition.rs index ff71b0cf10..2187cb736c 100644 --- a/stackslib/src/chainstate/burn/sortition.rs +++ b/stackslib/src/chainstate/burn/sortition.rs @@ -254,12 +254,12 @@ impl BlockSnapshot { debug!("SORTITION({}): NO BLOCK CHOSEN", block_height); Ok(BlockSnapshot { - block_height: block_height, + block_height, burn_header_hash: block_hash, burn_header_timestamp: block_header.timestamp, parent_burn_header_hash: parent_block_hash, consensus_hash: ch, - ops_hash: ops_hash, + ops_hash, total_burn: burn_total, sortition: false, sortition_hash: sortition_hash.clone(), diff --git a/stackslib/src/chainstate/nakamoto/tests/mod.rs b/stackslib/src/chainstate/nakamoto/tests/mod.rs index 94ef81c077..3f107ed1cf 100644 --- a/stackslib/src/chainstate/nakamoto/tests/mod.rs +++ b/stackslib/src/chainstate/nakamoto/tests/mod.rs @@ -2586,7 +2586,7 @@ fn valid_vote_transaction() { post_conditions: vec![], payload: TransactionPayload::ContractCall(TransactionContractCall { address: contract_addr, - contract_name: contract_name, + contract_name, function_name: SIGNERS_VOTING_FUNCTION_NAME.into(), function_args: valid_function_args, }), diff --git a/stackslib/src/chainstate/stacks/address.rs b/stackslib/src/chainstate/stacks/address.rs index c3706a2565..438dd17b9b 100644 --- a/stackslib/src/chainstate/stacks/address.rs +++ b/stackslib/src/chainstate/stacks/address.rs @@ -525,7 +525,7 @@ impl StacksAddressExtensions for StacksAddress { let version = to_c32_version_byte(btc_version) .expect("Failed to decode Bitcoin version byte to Stacks version byte"); StacksAddress { - version: version, + version, bytes: addr.bytes.clone(), } } diff --git a/stackslib/src/chainstate/stacks/auth.rs b/stackslib/src/chainstate/stacks/auth.rs index 06cf64d037..58bd2ea9f4 100644 --- a/stackslib/src/chainstate/stacks/auth.rs +++ b/stackslib/src/chainstate/stacks/auth.rs @@ -558,12 +558,12 @@ impl StacksMessageCodec for SinglesigSpendingCondition { } Ok(SinglesigSpendingCondition { - signer: signer, - nonce: nonce, - tx_fee: tx_fee, - hash_mode: hash_mode, - key_encoding: key_encoding, - signature: signature, + signer, + nonce, + tx_fee, + hash_mode, + key_encoding, + signature, }) } } @@ -593,7 +593,7 @@ impl SinglesigSpendingCondition { SinglesigHashMode::P2WPKH => C32_ADDRESS_VERSION_MAINNET_MULTISIG, }; StacksAddress { - version: version, + version, bytes: self.signer.clone(), } } @@ -604,7 +604,7 @@ impl SinglesigSpendingCondition { SinglesigHashMode::P2WPKH => C32_ADDRESS_VERSION_TESTNET_MULTISIG, }; StacksAddress { - version: version, + version, bytes: self.signer.clone(), } } diff --git a/stackslib/src/chainstate/stacks/block.rs b/stackslib/src/chainstate/stacks/block.rs index 85bfcc5576..8a1b337734 100644 --- a/stackslib/src/chainstate/stacks/block.rs +++ b/stackslib/src/chainstate/stacks/block.rs @@ -156,8 +156,8 @@ impl StacksBlockHeader { total_work: total_work.clone(), proof: proof.clone(), parent_block: parent_header_hash, - parent_microblock: parent_microblock, - parent_microblock_sequence: parent_microblock_sequence, + parent_microblock, + parent_microblock_sequence, tx_merkle_root: tx_merkle_root.clone(), state_index_root: state_index_root.clone(), microblock_pubkey_hash: microblock_pubkey_hash.clone(), @@ -887,10 +887,7 @@ impl StacksMicroblock { let merkle_tree = MerkleTree::::new(&txids); let tx_merkle_root = merkle_tree.root(); let header = StacksMicroblockHeader::first_unsigned(parent_block_hash, &tx_merkle_root); - StacksMicroblock { - header: header, - txs: txs, - } + StacksMicroblock { header, txs } } pub fn from_parent_unsigned( @@ -911,10 +908,7 @@ impl StacksMicroblock { } }; - Some(StacksMicroblock { - header: header, - txs: txs, - }) + Some(StacksMicroblock { header, txs }) } pub fn sign(&mut self, privk: &StacksPrivateKey) -> Result<(), net_error> { @@ -1005,7 +999,7 @@ mod test { burn: 123, work: 456, }, - proof: proof, + proof, parent_block: FIRST_STACKS_BLOCK_HASH.clone(), parent_microblock: BlockHeaderHash([1u8; 32]), parent_microblock_sequence: 3, @@ -1183,7 +1177,7 @@ mod test { version: 0x12, sequence: 0x34, prev_block: EMPTY_MICROBLOCK_PARENT_HASH.clone(), - tx_merkle_root: tx_merkle_root, + tx_merkle_root, signature: MessageSignature([ 0x00, 0x35, 0x44, 0x45, 0xa1, 0xdc, 0x98, 0xa1, 0xbd, 0x27, 0x98, 0x4d, 0xbe, 0x69, 0x97, 0x9a, 0x5c, 0xd7, 0x78, 0x86, 0xb4, 0xd9, 0x13, 0x4a, 0xf5, 0xc4, @@ -1216,10 +1210,7 @@ mod test { txs.consensus_serialize(&mut tx_bytes).unwrap(); block_bytes.append(&mut tx_bytes); - let mblock = StacksMicroblock { - header: header, - txs: txs, - }; + let mblock = StacksMicroblock { header, txs }; check_codec_and_corruption::(&mblock, &block_bytes); } diff --git a/stackslib/src/chainstate/stacks/db/accounts.rs b/stackslib/src/chainstate/stacks/db/accounts.rs index bf84cc1362..42682ea7c8 100644 --- a/stackslib/src/chainstate/stacks/db/accounts.rs +++ b/stackslib/src/chainstate/stacks/db/accounts.rs @@ -976,9 +976,9 @@ impl StacksChainState { address: child_address, recipient: child_recipient, coinbase: coinbase_reward, - tx_fees_anchored: tx_fees_anchored, + tx_fees_anchored, tx_fees_streamed_produced: 0, - tx_fees_streamed_confirmed: tx_fees_streamed_confirmed, + tx_fees_streamed_confirmed, vtxindex: participant.vtxindex, }; diff --git a/stackslib/src/chainstate/stacks/db/blocks.rs b/stackslib/src/chainstate/stacks/db/blocks.rs index 233a9d5978..968c587cd1 100644 --- a/stackslib/src/chainstate/stacks/db/blocks.rs +++ b/stackslib/src/chainstate/stacks/db/blocks.rs @@ -2007,8 +2007,8 @@ impl StacksChainState { Ok(BlocksInvData { bitlen: u16::try_from(block_bits.len()) .expect("FATAL: unreachable: more than 2^16 block bits"), - block_bitvec: block_bitvec, - microblocks_bitvec: microblocks_bitvec, + block_bitvec, + microblocks_bitvec, }) } @@ -2130,8 +2130,8 @@ impl StacksChainState { Ok(BlocksInvData { bitlen: u16::try_from(block_bits.len()) .expect("FATAL: block bits has more than 2^16 members"), - block_bitvec: block_bitvec, - microblocks_bitvec: microblocks_bitvec, + block_bitvec, + microblocks_bitvec, }) } @@ -2917,7 +2917,7 @@ impl StacksChainState { let extended_header = ExtendedStacksHeader { consensus_hash: header_info.consensus_hash, - header: header, + header, parent_block_id: parent_index_block_hash, }; Ok(extended_header) @@ -7180,15 +7180,12 @@ pub mod test { let header = StacksMicroblockHeader { version: 0x12, sequence: initial_seq + (i as u16), - prev_block: prev_block, - tx_merkle_root: tx_merkle_root, + prev_block, + tx_merkle_root, signature: MessageSignature([0u8; 65]), }; - let mut mblock = StacksMicroblock { - header: header, - txs: txs, - }; + let mut mblock = StacksMicroblock { header, txs }; mblock.sign(privk).unwrap(); microblocks.push(mblock); diff --git a/stackslib/src/chainstate/stacks/db/mod.rs b/stackslib/src/chainstate/stacks/db/mod.rs index ffdea5a7dd..b64815ed62 100644 --- a/stackslib/src/chainstate/stacks/db/mod.rs +++ b/stackslib/src/chainstate/stacks/db/mod.rs @@ -1869,18 +1869,18 @@ impl StacksChainState { let clarity_state = ClarityInstance::new(mainnet, chain_id, vm_state); let mut chainstate = StacksChainState { - mainnet: mainnet, - chain_id: chain_id, - clarity_state: clarity_state, + mainnet, + chain_id, + clarity_state, nakamoto_staging_blocks_conn, - state_index: state_index, + state_index, blocks_path: blocks_path_root, clarity_state_index_path: clarity_state_index_marf, - clarity_state_index_root: clarity_state_index_root, + clarity_state_index_root, root_path: path_str.to_string(), unconfirmed_state: None, fault_injection: StacksChainStateFaults::new(), - marf_opts: marf_opts, + marf_opts, }; let mut receipts = vec![]; diff --git a/stackslib/src/chainstate/stacks/db/transactions.rs b/stackslib/src/chainstate/stacks/db/transactions.rs index 3df99ea886..143cb5524f 100644 --- a/stackslib/src/chainstate/stacks/db/transactions.rs +++ b/stackslib/src/chainstate/stacks/db/transactions.rs @@ -250,7 +250,7 @@ impl StacksTransactionReceipt { transaction: tx.into(), events: vec![], post_condition_aborted: false, - result: result, + result, stx_burned: 0, contract_analysis: None, execution_cost: cost, @@ -449,10 +449,10 @@ impl StacksChainState { txid: tx.txid(), principal: payer_account.principal.clone(), is_origin: false, - quiet: quiet, + quiet, }; if !quiet { - warn!("{}", &e); + warn!("{e}"); } return Err((e, (origin_account, payer_account))); } @@ -470,10 +470,10 @@ impl StacksChainState { txid: tx.txid(), principal: origin_account.principal.clone(), is_origin: true, - quiet: quiet, + quiet, }; if !quiet { - warn!("{}", &e); + warn!("{e}"); } return Err((e, (origin_account, payer_account))); } @@ -8247,10 +8247,10 @@ pub mod test { version: 0x12, sequence: seq, prev_block: parent_block, - tx_merkle_root: tx_merkle_root, + tx_merkle_root, signature: MessageSignature([0u8; 65]), }, - txs: txs, + txs, }; mblock.sign(block_privk).unwrap(); mblock diff --git a/stackslib/src/chainstate/stacks/db/unconfirmed.rs b/stackslib/src/chainstate/stacks/db/unconfirmed.rs index 6f7a9fe9ea..a871b98944 100644 --- a/stackslib/src/chainstate/stacks/db/unconfirmed.rs +++ b/stackslib/src/chainstate/stacks/db/unconfirmed.rs @@ -189,7 +189,7 @@ impl UnconfirmedState { unconfirmed_chain_tip: unconfirmed_tip, clarity_inst: clarity_instance, mined_txs: UnconfirmedTxMap::new(), - cost_so_far: cost_so_far, + cost_so_far, bytes_so_far: 0, last_mblock: None, diff --git a/stackslib/src/chainstate/stacks/index/marf.rs b/stackslib/src/chainstate/stacks/index/marf.rs index a4082627fd..14e8643819 100644 --- a/stackslib/src/chainstate/stacks/index/marf.rs +++ b/stackslib/src/chainstate/stacks/index/marf.rs @@ -1145,7 +1145,7 @@ impl MARF { /// Instantiate the MARF from a TrieFileStorage instance pub fn from_storage(storage: TrieFileStorage) -> MARF { MARF { - storage: storage, + storage, open_chain_tip: None, } } diff --git a/stackslib/src/chainstate/stacks/index/node.rs b/stackslib/src/chainstate/stacks/index/node.rs index da9fc8bbd2..33580f2e2e 100644 --- a/stackslib/src/chainstate/stacks/index/node.rs +++ b/stackslib/src/chainstate/stacks/index/node.rs @@ -231,9 +231,9 @@ impl TriePtr { #[inline] pub fn new(id: u8, chr: u8, ptr: u32) -> TriePtr { TriePtr { - id: id, - chr: chr, - ptr: ptr, + id, + chr, + ptr, back_block: 0, } } @@ -308,10 +308,10 @@ impl TriePtr { let back_block = u32::from_be_bytes([bytes[6], bytes[7], bytes[8], bytes[9]]); TriePtr { - id: id, - chr: chr, - ptr: ptr, - back_block: back_block, + id, + chr, + ptr, + back_block, } } } @@ -781,7 +781,7 @@ impl TrieNode256 { } TrieNode256 { path: node4.path.clone(), - ptrs: ptrs, + ptrs, } } @@ -794,7 +794,7 @@ impl TrieNode256 { } TrieNode256 { path: node48.path.clone(), - ptrs: ptrs, + ptrs, } } } @@ -1191,7 +1191,7 @@ impl TrieNode for TrieLeaf { } Ok(TrieLeaf { - path: path, + path, data: MARFValue(leaf_data), }) } diff --git a/stackslib/src/chainstate/stacks/index/storage.rs b/stackslib/src/chainstate/stacks/index/storage.rs index 6e7ca815c9..d4a9bbe86c 100644 --- a/stackslib/src/chainstate/stacks/index/storage.rs +++ b/stackslib/src/chainstate/stacks/index/storage.rs @@ -422,8 +422,8 @@ impl TrieRAM { /// Inner method to instantiate a TrieRAM from existing Trie data. fn from_data(block_header: T, data: Vec<(TrieNodeType, TrieHash)>, parent: T) -> TrieRAM { TrieRAM { - data: data, - block_header: block_header, + data, + block_header, readonly: false, read_count: 0, @@ -439,7 +439,7 @@ impl TrieRAM { is_moved: false, - parent: parent, + parent, } } @@ -1469,8 +1469,8 @@ impl TrieFileStorage { trie_ancestor_hash_bytes_cache: None, - readonly: readonly, - unconfirmed: unconfirmed, + readonly, + unconfirmed, }, // used in testing in order to short-circuit block-height lookups @@ -1536,9 +1536,9 @@ impl TrieFileStorage { // TODO: borrow self.uncommitted_writes; don't copy them let ret = TrieFileStorage { db_path: self.db_path.clone(), - db: db, + db, blobs, - cache: cache, + cache, bench: TrieBenchmark::new(), hash_calculation_mode: self.hash_calculation_mode, @@ -1605,9 +1605,9 @@ impl<'a, T: MarfTrieId> TrieStorageTransaction<'a, T> { // TODO: borrow self.uncommitted_writes; don't copy them let ret = TrieFileStorage { db_path: self.db_path.to_string(), - db: db, - blobs: blobs, - cache: cache, + db, + blobs, + cache, bench: TrieBenchmark::new(), hash_calculation_mode: self.hash_calculation_mode, diff --git a/stackslib/src/chainstate/stacks/miner.rs b/stackslib/src/chainstate/stacks/miner.rs index 082e9c374c..014c9be53f 100644 --- a/stackslib/src/chainstate/stacks/miner.rs +++ b/stackslib/src/chainstate/stacks/miner.rs @@ -903,7 +903,7 @@ impl<'a> StacksMicroblockBuilder<'a> { next_microblock_header.verify(&miner_pubkey_hash).unwrap(); Ok(StacksMicroblock { header: next_microblock_header, - txs: txs, + txs, }) } @@ -1509,11 +1509,11 @@ impl StacksBlockBuilder { total_anchored_fees: 0, total_confirmed_streamed_fees: 0, total_streamed_fees: 0, - bytes_so_far: bytes_so_far, + bytes_so_far, anchored_done: false, parent_consensus_hash: parent_chain_tip.consensus_hash.clone(), parent_header_hash: header.parent_block.clone(), - header: header, + header, parent_microblock_hash: parent_chain_tip .microblock_tail .as_ref() @@ -1524,7 +1524,7 @@ impl StacksBlockBuilder { ), // will be updated miner_privkey: StacksPrivateKey::new(), // caller should overwrite this, or refrain from mining microblocks miner_payouts: None, - miner_id: miner_id, + miner_id, } } diff --git a/stackslib/src/chainstate/stacks/mod.rs b/stackslib/src/chainstate/stacks/mod.rs index fd370a8b12..c23f293082 100644 --- a/stackslib/src/chainstate/stacks/mod.rs +++ b/stackslib/src/chainstate/stacks/mod.rs @@ -1626,7 +1626,7 @@ pub mod test { parent_block: BlockHeaderHash([5u8; 32]), parent_microblock: BlockHeaderHash([6u8; 32]), parent_microblock_sequence: 4, - tx_merkle_root: tx_merkle_root, + tx_merkle_root, state_index_root: TrieHash([8u8; 32]), microblock_pubkey_hash: Hash160([9u8; 20]), }; @@ -1736,7 +1736,7 @@ pub mod test { header.sign(&privk).unwrap(); StacksMicroblock { - header: header, + header, txs: txs_mblock, } } diff --git a/stackslib/src/chainstate/stacks/tests/mod.rs b/stackslib/src/chainstate/stacks/tests/mod.rs index 9a6a84507e..148f37edf2 100644 --- a/stackslib/src/chainstate/stacks/tests/mod.rs +++ b/stackslib/src/chainstate/stacks/tests/mod.rs @@ -203,9 +203,9 @@ impl TestMinerTrace { points: Vec, ) -> TestMinerTrace { TestMinerTrace { - points: points, - burn_node: burn_node, - miners: miners, + points, + burn_node, + miners, } } @@ -288,7 +288,7 @@ impl TestStacksNode { let chainstate = instantiate_chainstate_with_balances(mainnet, chain_id, test_name, initial_balances); TestStacksNode { - chainstate: chainstate, + chainstate, prev_keys: vec![], key_ops: HashMap::new(), anchored_blocks: vec![], @@ -304,7 +304,7 @@ impl TestStacksNode { pub fn open(mainnet: bool, chain_id: u32, test_name: &str) -> TestStacksNode { let chainstate = open_chainstate(mainnet, chain_id, test_name); TestStacksNode { - chainstate: chainstate, + chainstate, prev_keys: vec![], key_ops: HashMap::new(), anchored_blocks: vec![], @@ -319,7 +319,7 @@ impl TestStacksNode { pub fn from_chainstate(chainstate: StacksChainState) -> TestStacksNode { TestStacksNode { - chainstate: chainstate, + chainstate, prev_keys: vec![], key_ops: HashMap::new(), anchored_blocks: vec![], @@ -356,7 +356,7 @@ impl TestStacksNode { new_test_name, ); TestStacksNode { - chainstate: chainstate, + chainstate, prev_keys: self.prev_keys.clone(), key_ops: self.key_ops.clone(), anchored_blocks: self.anchored_blocks.clone(), diff --git a/stackslib/src/chainstate/stacks/transaction.rs b/stackslib/src/chainstate/stacks/transaction.rs index c45b212b68..b1ad0a1d33 100644 --- a/stackslib/src/chainstate/stacks/transaction.rs +++ b/stackslib/src/chainstate/stacks/transaction.rs @@ -722,13 +722,13 @@ impl StacksTransaction { }; StacksTransaction { - version: version, + version, chain_id: 0, - auth: auth, - anchor_mode: anchor_mode, + auth, + anchor_mode, post_condition_mode: TransactionPostConditionMode::Deny, post_conditions: vec![], - payload: payload, + payload, } } diff --git a/stackslib/src/clarity_cli.rs b/stackslib/src/clarity_cli.rs index f23be191ff..a9880ea858 100644 --- a/stackslib/src/clarity_cli.rs +++ b/stackslib/src/clarity_cli.rs @@ -547,7 +547,7 @@ impl CLIHeadersDB { let conn = create_or_open_db(&cli_db_path); let mut db = CLIHeadersDB { db_path: db_path.to_string(), - conn: conn, + conn, }; if instantiate { @@ -567,7 +567,7 @@ impl CLIHeadersDB { let conn = create_or_open_db(&cli_db_path); let db = CLIHeadersDB { db_path: db_path.to_string(), - conn: conn, + conn, }; Ok(db) diff --git a/stackslib/src/clarity_vm/clarity.rs b/stackslib/src/clarity_vm/clarity.rs index a5497cea24..e4856e803e 100644 --- a/stackslib/src/clarity_vm/clarity.rs +++ b/stackslib/src/clarity_vm/clarity.rs @@ -190,7 +190,7 @@ impl<'a, 'b> ClarityBlockConnection<'a, 'b> { cost_track: Some(LimitedCostTracker::new_free()), mainnet: false, chain_id: CHAIN_ID_TESTNET, - epoch: epoch, + epoch, } } diff --git a/stackslib/src/net/api/getheaders.rs b/stackslib/src/net/api/getheaders.rs index fc585fd2e9..d0ae36a0bb 100644 --- a/stackslib/src/net/api/getheaders.rs +++ b/stackslib/src/net/api/getheaders.rs @@ -90,7 +90,7 @@ impl StacksHeaderStream { index_block_hash: tip.clone(), offset: 0, total_bytes: 0, - num_headers: num_headers, + num_headers, end_of_stream: false, corked: false, chainstate_db: db, diff --git a/stackslib/src/net/api/getmicroblocks_indexed.rs b/stackslib/src/net/api/getmicroblocks_indexed.rs index 43a3a73e04..4a1b310ae0 100644 --- a/stackslib/src/net/api/getmicroblocks_indexed.rs +++ b/stackslib/src/net/api/getmicroblocks_indexed.rs @@ -94,8 +94,8 @@ impl StacksIndexedMicroblockStream { Ok(StacksIndexedMicroblockStream { microblock_hash: mblock_info.microblock_hash, - parent_index_block_hash: parent_index_block_hash, - num_items_buf: num_items_buf, + parent_index_block_hash, + num_items_buf, num_items_ptr: 0, chainstate_db: chainstate.reopen_db()?, }) diff --git a/stackslib/src/net/api/gettransaction_unconfirmed.rs b/stackslib/src/net/api/gettransaction_unconfirmed.rs index 9a76ee002b..9628817b40 100644 --- a/stackslib/src/net/api/gettransaction_unconfirmed.rs +++ b/stackslib/src/net/api/gettransaction_unconfirmed.rs @@ -130,7 +130,7 @@ impl RPCRequestHandler for RPCGetTransactionUnconfirmedRequestHandler { return Ok(UnconfirmedTransactionResponse { status: UnconfirmedTransactionStatus::Microblock { block_hash: mblock_hash, - seq: seq, + seq, }, tx: to_hex(&transaction.serialize_to_vec()), }); diff --git a/stackslib/src/net/asn.rs b/stackslib/src/net/asn.rs index f38c6c54d4..c28e82484b 100644 --- a/stackslib/src/net/asn.rs +++ b/stackslib/src/net/asn.rs @@ -214,9 +214,9 @@ impl ASEntry4 { let asn = asn_opt.unwrap(); Ok(Some(ASEntry4 { - prefix: prefix, - mask: mask, - asn: asn, + prefix, + mask, + asn, org: 0, // TODO })) } diff --git a/stackslib/src/net/atlas/mod.rs b/stackslib/src/net/atlas/mod.rs index 45100d984b..c382aa618d 100644 --- a/stackslib/src/net/atlas/mod.rs +++ b/stackslib/src/net/atlas/mod.rs @@ -229,7 +229,7 @@ impl AttachmentInstance { metadata, contract_id: contract_id.clone(), tx_id, - canonical_stacks_tip_height: canonical_stacks_tip_height, + canonical_stacks_tip_height, }; return Some(instance); } diff --git a/stackslib/src/net/chat.rs b/stackslib/src/net/chat.rs index 1d8e5d10d2..8601700ff5 100644 --- a/stackslib/src/net/chat.rs +++ b/stackslib/src/net/chat.rs @@ -136,7 +136,7 @@ pub struct NeighborStats { impl NeighborStats { pub fn new(outbound: bool) -> NeighborStats { NeighborStats { - outbound: outbound, + outbound, first_contact_time: 0, last_contact_time: 0, last_send_time: 0, @@ -164,7 +164,7 @@ impl NeighborStats { /// message, or failed to do so (indicated by `success`). pub fn add_healthpoint(&mut self, success: bool) -> () { let hp = NeighborHealthPoint { - success: success, + success, time: get_epoch_time_secs(), }; self.healthpoints.push_back(hp); @@ -236,7 +236,7 @@ impl NeighborStats { } else { let info = RelayStats { num_messages: 1, - num_bytes: num_bytes, + num_bytes, last_seen: get_epoch_time_secs(), }; self.relayed_messages.insert(addr.clone(), info); @@ -427,8 +427,8 @@ impl NeighborKey { handshake_data: &HandshakeData, ) -> NeighborKey { NeighborKey { - peer_version: peer_version, - network_id: network_id, + peer_version, + network_id, addrbytes: handshake_data.addrbytes.clone(), port: handshake_data.port, } @@ -436,8 +436,8 @@ impl NeighborKey { pub fn from_socketaddr(peer_version: u32, network_id: u32, addr: &SocketAddr) -> NeighborKey { NeighborKey { - peer_version: peer_version, - network_id: network_id, + peer_version, + network_id, addrbytes: PeerAddress::from_socketaddr(addr), port: addr.port(), } @@ -1202,7 +1202,7 @@ impl ConversationP2P { let natpunch_data = NatPunchData { addrbytes: self.peer_addrbytes.clone(), port: self.peer_port, - nonce: nonce, + nonce, }; let msg = StacksMessage::from_chain_view( self.version, @@ -3347,7 +3347,7 @@ mod test { network_id: 0, chain_name: "bitcoin".to_string(), network_name: "testnet".to_string(), - working_dir: format!("/tmp/stacks-test-databases-{}", test_name), + working_dir: format!("/tmp/stacks-test-databases-{test_name}"), consensus_hash_lifetime: 24, stable_confirmations: 7, first_block_height: 12300, diff --git a/stackslib/src/net/codec.rs b/stackslib/src/net/codec.rs index bd8154e414..c3dd63b1d0 100644 --- a/stackslib/src/net/codec.rs +++ b/stackslib/src/net/codec.rs @@ -65,8 +65,8 @@ impl Preamble { payload_len: u32, ) -> Preamble { Preamble { - peer_version: peer_version, - network_id: network_id, + peer_version, + network_id, seq: 0, burn_block_height: block_height, burn_block_hash: burn_block_hash.clone(), @@ -74,7 +74,7 @@ impl Preamble { burn_stable_block_hash: stable_burn_block_hash.clone(), additional_data: 0, signature: MessageSignature::empty(), - payload_len: payload_len, + payload_len, } } @@ -234,8 +234,8 @@ impl StacksMessageCodec for GetBlocksInv { } Ok(GetBlocksInv { - consensus_hash: consensus_hash, - num_blocks: num_blocks, + consensus_hash, + num_blocks, }) } } @@ -435,10 +435,7 @@ impl StacksMessageCodec for PoxInvData { } let pox_bitvec: Vec = read_next_exact::<_, u8>(fd, bitvec_len(bitlen).into())?; - Ok(PoxInvData { - bitlen: bitlen, - pox_bitvec: pox_bitvec, - }) + Ok(PoxInvData { bitlen, pox_bitvec }) } } @@ -454,9 +451,7 @@ impl StacksMessageCodec for BlocksAvailableData { fd, BLOCKS_AVAILABLE_MAX_LEN, )?; - Ok(BlocksAvailableData { - available: available, - }) + Ok(BlocksAvailableData { available }) } } @@ -624,14 +619,14 @@ impl HandshakeData { }; HandshakeData { - addrbytes: addrbytes, - port: port, + addrbytes, + port, services: local_peer.services, node_public_key: StacksPublicKeyBuffer::from_public_key( &Secp256k1PublicKey::from_private(&local_peer.private_key), ), expire_block_height: local_peer.private_key_expire, - data_url: data_url, + data_url, } } } @@ -675,7 +670,7 @@ impl HandshakeAcceptData { pub fn new(local_peer: &LocalPeer, heartbeat_interval: u32) -> HandshakeAcceptData { HandshakeAcceptData { handshake: HandshakeData::from_local_peer(local_peer), - heartbeat_interval: heartbeat_interval, + heartbeat_interval, } } } @@ -1384,7 +1379,7 @@ impl StacksMessage { 0, ); StacksMessage { - preamble: preamble, + preamble, relayers: vec![], payload: message, } @@ -1414,7 +1409,7 @@ impl StacksMessage { peer_version: self.preamble.peer_version, network_id: self.preamble.network_id, addrbytes: addrbytes.clone(), - port: port, + port, } } @@ -1573,8 +1568,8 @@ impl ProtocolFamily for StacksP2P { let (relayers, payload) = StacksMessage::deserialize_body(&mut cursor)?; let message = StacksMessage { preamble: preamble.clone(), - relayers: relayers, - payload: payload, + relayers, + payload, }; Ok((message, cursor.position() as usize)) } diff --git a/stackslib/src/net/connection.rs b/stackslib/src/net/connection.rs index 0e58adb36e..ac86240e48 100644 --- a/stackslib/src/net/connection.rs +++ b/stackslib/src/net/connection.rs @@ -63,7 +63,7 @@ impl ReceiverNotify

{ ReceiverNotify { expected_seq: seq, receiver_input: input, - ttl: ttl, + ttl, } } @@ -104,7 +104,7 @@ impl NetworkReplyHandle

{ receiver_output: Some(output), request_pipe_write: Some(write), deadline: 0, - socket_event_id: socket_event_id, + socket_event_id, } } @@ -113,7 +113,7 @@ impl NetworkReplyHandle

{ receiver_output: None, request_pipe_write: Some(write), deadline: 0, - socket_event_id: socket_event_id, + socket_event_id, } } @@ -1084,7 +1084,7 @@ impl ConnectionOutbox

{ pub fn new(outbox_maxlen: usize) -> ConnectionOutbox

{ ConnectionOutbox { outbox: VecDeque::with_capacity(outbox_maxlen), - outbox_maxlen: outbox_maxlen, + outbox_maxlen, pending_message_fd: None, socket_out_buf: vec![], socket_out_ptr: 0, @@ -1301,7 +1301,7 @@ impl NetworkConnection

{ public_key_opt: Option, ) -> NetworkConnection

{ NetworkConnection { - protocol: protocol, + protocol, options: (*options).clone(), inbox: ConnectionInbox::new(options.inbox_maxlen, public_key_opt), @@ -1867,7 +1867,7 @@ mod test { &BurnchainHeaderHash([0x11; 32]), 12339, &BurnchainHeaderHash([0x22; 32]), - StacksMessageType::Ping(PingData { nonce: nonce }), + StacksMessageType::Ping(PingData { nonce }), ); let privkey = Secp256k1PrivateKey::new(); ping.sign(request_id, &privkey).unwrap(); diff --git a/stackslib/src/net/db.rs b/stackslib/src/net/db.rs index ff6b5a9a05..3eecd7cbc9 100644 --- a/stackslib/src/net/db.rs +++ b/stackslib/src/net/db.rs @@ -162,15 +162,15 @@ impl LocalPeer { ); LocalPeer { - network_id: network_id, - parent_network_id: parent_network_id, + network_id, + parent_network_id, nonce: my_nonce, private_key: pkey, private_key_expire: key_expire, addrbytes: addr, - port: port, - services: services as u16, - data_url: data_url, + port, + services, + data_url, public_ip_address: None, stacker_dbs, } @@ -237,15 +237,15 @@ impl FromRow for LocalPeer { }; Ok(LocalPeer { - network_id: network_id, - parent_network_id: parent_network_id, + network_id, + parent_network_id, private_key: privkey, nonce: nonce_buf, private_key_expire: privkey_expire, - addrbytes: addrbytes, - port: port, - services: services, - data_url: data_url, + addrbytes, + port, + services, + data_url, public_ip_address: None, stacker_dbs, }) @@ -289,20 +289,20 @@ impl FromRow for Neighbor { Ok(Neighbor { addr: NeighborKey { - peer_version: peer_version, - network_id: network_id, - addrbytes: addrbytes, - port: port, + peer_version, + network_id, + addrbytes, + port, }, - public_key: public_key, + public_key, expire_block: expire_block_height, - last_contact_time: last_contact_time, - asn: asn, - org: org, - allowed: allowed, - denied: denied, - in_degree: in_degree, - out_degree: out_degree, + last_contact_time, + asn, + org, + allowed, + denied, + in_degree, + out_degree, }) } } @@ -668,10 +668,7 @@ impl PeerDB { let conn = sqlite_open(path, open_flags, false)?; - let mut db = PeerDB { - conn: conn, - readwrite: readwrite, - }; + let mut db = PeerDB { conn, readwrite }; if create_flag { // instantiate! @@ -753,10 +750,7 @@ impl PeerDB { let conn = sqlite_open(path, open_flags, true)?; - let db = PeerDB { - conn: conn, - readwrite: readwrite, - }; + let db = PeerDB { conn, readwrite }; Ok(db) } @@ -773,10 +767,7 @@ impl PeerDB { }; let conn = sqlite_open(path, open_flags, true)?; - let db = PeerDB { - conn: conn, - readwrite: readwrite, - }; + let db = PeerDB { conn, readwrite }; Ok(db) } @@ -794,7 +785,7 @@ impl PeerDB { let conn = Connection::open_in_memory().map_err(|e| db_error::SqliteError(e))?; let mut db = PeerDB { - conn: conn, + conn, readwrite: true, }; @@ -1246,7 +1237,7 @@ impl PeerDB { // we're preemptively allowing let nk = NeighborKey { peer_version: 0, - network_id: network_id, + network_id, addrbytes: peer_addr.clone(), port: peer_port, }; @@ -1292,7 +1283,7 @@ impl PeerDB { // we're preemptively denying let nk = NeighborKey { peer_version: 0, - network_id: network_id, + network_id, addrbytes: peer_addr.clone(), port: peer_port, }; diff --git a/stackslib/src/net/dns.rs b/stackslib/src/net/dns.rs index aedb73bd62..b07413ea27 100644 --- a/stackslib/src/net/dns.rs +++ b/stackslib/src/net/dns.rs @@ -43,9 +43,9 @@ pub struct DNSRequest { impl DNSRequest { pub fn new(host: String, port: u16, timeout: u128) -> DNSRequest { DNSRequest { - host: host, - port: port, - timeout: timeout, + host, + port, + timeout, } } @@ -76,15 +76,12 @@ pub struct DNSResponse { impl DNSResponse { pub fn new(request: DNSRequest, result: Result, String>) -> DNSResponse { - DNSResponse { - request: request, - result: result, - } + DNSResponse { request, result } } pub fn error(request: DNSRequest, errstr: String) -> DNSResponse { DNSResponse { - request: request, + request, result: Err(errstr), } } @@ -122,7 +119,7 @@ impl DNSResolver { queries: VecDeque::new(), inbound: socket_chan_rx, outbound: dns_chan_tx, - max_inflight: max_inflight, + max_inflight, hardcoded: HashMap::new(), }; (resolver, client) diff --git a/stackslib/src/net/download/epoch2x.rs b/stackslib/src/net/download/epoch2x.rs index c57d9d19bc..a4387cbc92 100644 --- a/stackslib/src/net/download/epoch2x.rs +++ b/stackslib/src/net/download/epoch2x.rs @@ -112,14 +112,14 @@ impl BlockRequestKey { canonical_stacks_tip_height: u64, ) -> BlockRequestKey { BlockRequestKey { - neighbor: neighbor, - data_url: data_url, - consensus_hash: consensus_hash, - anchor_block_hash: anchor_block_hash, - index_block_hash: index_block_hash, - parent_block_header: parent_block_header, - parent_consensus_hash: parent_consensus_hash, - sortition_height: sortition_height, + neighbor, + data_url, + consensus_hash, + anchor_block_hash, + index_block_hash, + parent_block_header, + parent_consensus_hash, + sortition_height, download_start: get_epoch_time_secs(), kind, canonical_stacks_tip_height, @@ -267,13 +267,13 @@ impl BlockDownloader { finished_scan_at: 0, last_inv_update_at: 0, - max_inflight_requests: max_inflight_requests, + max_inflight_requests, blocks_to_try: HashMap::new(), microblocks_to_try: HashMap::new(), parsed_urls: HashMap::new(), dns_lookups: HashMap::new(), - dns_timeout: dns_timeout, + dns_timeout, getblock_requests: HashMap::new(), getmicroblocks_requests: HashMap::new(), @@ -285,7 +285,7 @@ impl BlockDownloader { broken_neighbors: vec![], blocked_urls: HashMap::new(), - download_interval: download_interval, + download_interval, requested_blocks: HashMap::new(), requested_microblocks: HashMap::new(), } diff --git a/stackslib/src/net/http/request.rs b/stackslib/src/net/http/request.rs index 9231071e18..6535f4a14a 100644 --- a/stackslib/src/net/http/request.rs +++ b/stackslib/src/net/http/request.rs @@ -66,13 +66,13 @@ impl HttpRequestPreamble { keep_alive: bool, ) -> HttpRequestPreamble { HttpRequestPreamble { - version: version, - verb: verb, + version, + verb, path_and_query_str, host: PeerHost::from_host_port(hostname, port), content_type: None, content_length: None, - keep_alive: keep_alive, + keep_alive, headers: BTreeMap::new(), } } @@ -98,7 +98,7 @@ impl HttpRequestPreamble { ) -> HttpRequestPreamble { HttpRequestPreamble { version: HttpVersion::Http11, - verb: verb, + verb, path_and_query_str, host: peerhost, content_type: None, @@ -443,14 +443,14 @@ impl StacksMessageCodec for HttpRequestPreamble { }; Ok(HttpRequestPreamble { - version: version, - verb: verb, + version, + verb, path_and_query_str, host: peerhost.unwrap(), - content_type: content_type, - content_length: content_length, - keep_alive: keep_alive, - headers: headers, + content_type, + content_length, + keep_alive, + headers, }) } } diff --git a/stackslib/src/net/http/response.rs b/stackslib/src/net/http/response.rs index 77bcaa730f..c23097398b 100644 --- a/stackslib/src/net/http/response.rs +++ b/stackslib/src/net/http/response.rs @@ -159,12 +159,12 @@ impl HttpResponsePreamble { keep_alive: bool, ) -> HttpResponsePreamble { HttpResponsePreamble { - client_http_version: client_http_version, - status_code: status_code, - reason: reason, - keep_alive: keep_alive, + client_http_version, + status_code, + reason, + keep_alive, content_length: content_length_opt, - content_type: content_type, + content_type, headers: BTreeMap::new(), } } @@ -590,12 +590,12 @@ impl StacksMessageCodec for HttpResponsePreamble { Ok(HttpResponsePreamble { client_http_version, - status_code: status_code, - reason: reason, - keep_alive: keep_alive, + status_code, + reason, + keep_alive, content_type: content_type.unwrap_or(HttpContentType::Bytes), // per the RFC - content_length: content_length, - headers: headers, + content_length, + headers, }) } } diff --git a/stackslib/src/net/inv/epoch2x.rs b/stackslib/src/net/inv/epoch2x.rs index bbdd8f68ae..f1393a34c4 100644 --- a/stackslib/src/net/inv/epoch2x.rs +++ b/stackslib/src/net/inv/epoch2x.rs @@ -82,7 +82,7 @@ impl PeerBlocksInv { num_sortitions: 0, num_reward_cycles: 0, last_updated_at: 0, - first_block_height: first_block_height, + first_block_height, } } @@ -96,13 +96,13 @@ impl PeerBlocksInv { ) -> PeerBlocksInv { assert_eq!(block_inv.len(), microblocks_inv.len()); PeerBlocksInv { - block_inv: block_inv, - microblocks_inv: microblocks_inv, - num_sortitions: num_sortitions, - num_reward_cycles: num_reward_cycles, - pox_inv: pox_inv, + block_inv, + microblocks_inv, + num_sortitions, + num_reward_cycles, + pox_inv, last_updated_at: get_epoch_time_secs(), - first_block_height: first_block_height, + first_block_height, } } @@ -541,7 +541,7 @@ impl NeighborBlockStats { is_bootstrap_peer: bool, ) -> NeighborBlockStats { NeighborBlockStats { - nk: nk, + nk, inv: PeerBlocksInv::empty(first_block_height), pox_reward_cycle: 0, block_reward_cycle: 0, @@ -558,7 +558,7 @@ impl NeighborBlockStats { learned_data: false, learned_data_height: u64::MAX, scans: 0, - is_bootstrap_peer: is_bootstrap_peer, + is_bootstrap_peer, } } @@ -983,11 +983,11 @@ impl InvState { InvState { block_stats: HashMap::new(), - request_timeout: request_timeout, - first_block_height: first_block_height, + request_timeout, + first_block_height, last_change_at: 0, - sync_interval: sync_interval, + sync_interval, hint_learned_data: false, hint_learned_data_height: u64::MAX, diff --git a/stackslib/src/net/mod.rs b/stackslib/src/net/mod.rs index 4af4d2a397..4cca6fc4bb 100644 --- a/stackslib/src/net/mod.rs +++ b/stackslib/src/net/mod.rs @@ -1384,8 +1384,8 @@ impl NeighborKey { na: &NeighborAddress, ) -> NeighborKey { NeighborKey { - peer_version: peer_version, - network_id: network_id, + peer_version, + network_id, addrbytes: na.addrbytes.clone(), port: na.port, } @@ -1558,9 +1558,9 @@ impl NetworkResult { attachments: vec![], synced_transactions: vec![], stacker_db_sync_results: vec![], - num_state_machine_passes: num_state_machine_passes, - num_inv_sync_passes: num_inv_sync_passes, - num_download_passes: num_download_passes, + num_state_machine_passes, + num_inv_sync_passes, + num_download_passes, num_connected_peers, burn_height, coinbase_height, @@ -2639,7 +2639,7 @@ pub mod test { private_key_expire: start_block + conn_opts.private_key_lifetime, initial_neighbors: vec![], asn4_entries: vec![], - burnchain: burnchain, + burnchain, connection_opts: conn_opts, server_port: 32000, http_port: 32001, @@ -2651,7 +2651,7 @@ pub mod test { test_name: "".into(), initial_balances: vec![], initial_lockups: vec![], - spending_account: spending_account, + spending_account, setup_code: "".into(), epochs: None, check_pox_invariants: None, @@ -3204,15 +3204,15 @@ pub mod test { peer_network.local_peer = local_peer; TestPeer { - config: config, + config, network: peer_network, sortdb: Some(sortdb), miner, stacks_node: Some(stacks_node), - relayer: relayer, + relayer, mempool: Some(mempool), - chainstate_path: chainstate_path, - coord: coord, + chainstate_path, + coord, indexer: Some(indexer), malleablized_blocks: vec![], mine_malleablized_blocks: true, diff --git a/stackslib/src/net/neighbors/neighbor.rs b/stackslib/src/net/neighbors/neighbor.rs index 617860063e..4a8b7baf18 100644 --- a/stackslib/src/net/neighbors/neighbor.rs +++ b/stackslib/src/net/neighbors/neighbor.rs @@ -35,7 +35,7 @@ impl Neighbor { Neighbor { addr: key.clone(), public_key: pubk.clone(), - expire_block: expire_block, + expire_block, last_contact_time: 0, allowed: 0, denied: 0, diff --git a/stackslib/src/net/poll.rs b/stackslib/src/net/poll.rs index 0362745f90..a4c2c46465 100644 --- a/stackslib/src/net/poll.rs +++ b/stackslib/src/net/poll.rs @@ -74,9 +74,9 @@ impl NetworkState { let events = mio::Events::with_capacity(event_capacity); Ok(NetworkState { - poll: poll, - events: events, - event_capacity: event_capacity, + poll, + events, + event_capacity, servers: vec![], count: 1, event_map: HashMap::new(), diff --git a/stackslib/src/net/relay.rs b/stackslib/src/net/relay.rs index b93171916c..c8fecd9515 100644 --- a/stackslib/src/net/relay.rs +++ b/stackslib/src/net/relay.rs @@ -3208,7 +3208,7 @@ impl PeerNetwork { let idx_bhh = index_block_hash.clone(); let payload = MicroblocksData { index_anchor_block: index_block_hash, - microblocks: microblocks, + microblocks, }; let message = match self.sign_for_neighbor(recipient, StacksMessageType::Microblocks(payload)) { diff --git a/stackslib/src/net/tests/relay/epoch2x.rs b/stackslib/src/net/tests/relay/epoch2x.rs index f4fc8d9eb8..13e9f928d8 100644 --- a/stackslib/src/net/tests/relay/epoch2x.rs +++ b/stackslib/src/net/tests/relay/epoch2x.rs @@ -934,7 +934,7 @@ fn push_microblocks( ); let msg = StacksMessageType::Microblocks(MicroblocksData { index_anchor_block: StacksBlockHeader::make_index_block_hash(&consensus_hash, &block_hash), - microblocks: microblocks, + microblocks, }); push_message(peer, dest, relay_hints, msg) } @@ -955,7 +955,7 @@ fn broadcast_microblocks( ); let msg = StacksMessageType::Microblocks(MicroblocksData { index_anchor_block: StacksBlockHeader::make_index_block_hash(&consensus_hash, &block_hash), - microblocks: microblocks, + microblocks, }); broadcast_message(peer, relay_hints, msg) } diff --git a/stackslib/src/util_lib/bloom.rs b/stackslib/src/util_lib/bloom.rs index d1632f0b14..bd9706fd59 100644 --- a/stackslib/src/util_lib/bloom.rs +++ b/stackslib/src/util_lib/bloom.rs @@ -373,7 +373,7 @@ impl BloomCounter { Ok(BloomCounter { hasher, table_name: table_name.to_string(), - num_bins: num_bins, + num_bins, num_hashes, counts_rowid: counts_rowid as u32, }) diff --git a/stackslib/src/util_lib/db.rs b/stackslib/src/util_lib/db.rs index 53f597daa2..6c1306afcf 100644 --- a/stackslib/src/util_lib/db.rs +++ b/stackslib/src/util_lib/db.rs @@ -804,7 +804,7 @@ impl<'a, C: Clone, T: MarfTrieId> IndexDBTx<'a, C, T> { IndexDBTx { _index: Some(tx), block_linkage: None, - context: context, + context, } }