From 623b2a5342352a8083d04e94904063fefbf9c9ea Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 21:32:47 +0000 Subject: [PATCH 01/28] clippy: fix all current clippy lints --- src/blech32/decode.rs | 6 +++--- src/block.rs | 2 +- src/pset/mod.rs | 4 ++-- src/script.rs | 4 ++-- src/transaction.rs | 6 +++--- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/blech32/decode.rs b/src/blech32/decode.rs index b73c80d1..45a31d3d 100644 --- a/src/blech32/decode.rs +++ b/src/blech32/decode.rs @@ -104,7 +104,7 @@ impl<'s> UncheckedHrpstring<'s> { let ret = UncheckedHrpstring { hrp: Hrp::parse(hrp)?, - data: data[1..].as_bytes(), // Skip the separator. + data: &data.as_bytes()[1..], // Skip the separator. }; Ok(ret) @@ -221,7 +221,7 @@ impl<'s> CheckedHrpstring<'s> { /// Converts the ASCII bytes representing field elements to the respective field elements, then /// converts the stream of field elements to a stream of bytes. #[inline] - pub fn byte_iter(&self) -> ByteIter { + pub fn byte_iter(&self) -> ByteIter<'_> { ByteIter { iter: AsciiToFe32Iter { iter: self.data.iter().copied() }.fes_to_bytes() } } @@ -393,7 +393,7 @@ impl<'s> SegwitHrpstring<'s> { /// /// Use `self.witness_version()` to get the witness version. #[inline] - pub fn byte_iter(&self) -> ByteIter { + pub fn byte_iter(&self) -> ByteIter<'_> { ByteIter { iter: AsciiToFe32Iter { iter: self.data.iter().copied() }.fes_to_bytes() } } } diff --git a/src/block.rs b/src/block.rs index 0ab9c623..e6728976 100644 --- a/src/block.rs +++ b/src/block.rs @@ -727,7 +727,7 @@ mod tests { } else { panic!("Current block dynafed params not compact"); } - if let dynafed::Params::Null { .. } = proposed { + if let dynafed::Params::Null = proposed { /* pass */ } else { panic!("Proposed block dynafed params not compact"); diff --git a/src/pset/mod.rs b/src/pset/mod.rs index 2bafb503..9f5e8f67 100644 --- a/src/pset/mod.rs +++ b/src/pset/mod.rs @@ -402,8 +402,8 @@ impl PartiallySignedTransaction { // collect input factors let inp_secrets = inp_txout_sec - .iter() - .map(|(_i, sec)| (sec.value, sec.asset_bf, sec.value_bf)) + .values() + .map(|sec| (sec.value, sec.asset_bf, sec.value_bf)) .collect::>(); Ok((inp_secrets, blind_out_indices)) diff --git a/src/script.rs b/src/script.rs index 49180a11..025bf5a8 100644 --- a/src/script.rs +++ b/src/script.rs @@ -451,7 +451,7 @@ impl Script { /// it as a slice using `script[..]` or convert it to a vector using `into_bytes()`. /// /// To force minimal pushes, use [Script::instructions_minimal]. - pub fn instructions(&self) -> Instructions { + pub fn instructions(&self) -> Instructions<'_> { Instructions { data: &self.0[..], enforce_minimal: false, @@ -460,7 +460,7 @@ impl Script { /// Iterate over the script in the form of `Instruction`s while enforcing /// minimal pushes. - pub fn instructions_minimal(&self) -> Instructions { + pub fn instructions_minimal(&self) -> Instructions<'_> { Instructions { data: &self.0[..], enforce_minimal: true, diff --git a/src/transaction.rs b/src/transaction.rs index f5973e84..55e30563 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -602,7 +602,7 @@ impl TxIn { /// Extracts witness data from a pegin. Will return `None` if any data /// cannot be parsed. The combination of `is_pegin()` returning `true` /// and `pegin_data()` returning `None` indicates an invalid transaction. - pub fn pegin_data(&self) -> Option { + pub fn pegin_data(&self) -> Option> { self.pegin_prevout().and_then(|p| { PeginData::from_pegin_witness(&self.witness.pegin_witness, p).ok() }) @@ -777,7 +777,7 @@ impl TxOut { /// If this output is a pegout, returns the destination genesis block, /// the destination script pubkey, and any additional data - pub fn pegout_data(&self) -> Option { + pub fn pegout_data(&self) -> Option> { // Must be NULLDATA if !self.is_null_data() { return None; @@ -797,7 +797,7 @@ impl TxOut { // Parse destination scriptpubkey let script_pubkey = bitcoin::ScriptBuf::from(iter.next()?.ok()?.push_bytes()?.to_owned()); - if script_pubkey.len() == 0 { + if script_pubkey.is_empty() { return None; } From 396e1d66d6563441cfb3bfde006910104eec112d Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 21:29:23 +0000 Subject: [PATCH 02/28] bump msrv to 1.63.0; fix new clippy lints --- .github/workflows/rust.yml | 4 ++-- Cargo.toml | 6 ++++++ clippy.toml | 2 +- src/confidential.rs | 28 ++++++---------------------- src/dynafed.rs | 9 ++------- 5 files changed, 17 insertions(+), 32 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index b1b5fe76..b5176e6f 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -49,7 +49,7 @@ jobs: run: ./contrib/test.sh MSRV: - name: Test - 1.56.1 toolchain + name: Test - 1.63.0 toolchain runs-on: ubuntu-latest strategy: fail-fast: false @@ -57,7 +57,7 @@ jobs: - name: Checkout Crate uses: actions/checkout@v3 - name: Checkout Toolchain - uses: dtolnay/rust-toolchain@1.56.1 + uses: dtolnay/rust-toolchain@1.63.0 - name: Running test script env: DO_DOCS: false diff --git a/Cargo.toml b/Cargo.toml index 12029a50..95cd1078 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,3 +57,9 @@ name = "tx" [workspace] members = ["elementsd-tests"] exclude = ["fuzz"] + +[lints.clippy] +# Exclude lints we don't think are valuable. +needless_question_mark = "allow" # https://github.com/rust-bitcoin/rust-bitcoin/pull/2134 +manual_range_contains = "allow" # More readable than clippy's format. +uninlined_format_args = "allow" # This is a subjective style choice. diff --git a/clippy.toml b/clippy.toml index 56ce04e4..b3c3a24c 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1 +1 @@ -msrv = "1.56.1" +msrv = "1.63.0" diff --git a/src/confidential.rs b/src/confidential.rs index ba6c8543..555f63ee 100644 --- a/src/confidential.rs +++ b/src/confidential.rs @@ -33,9 +33,10 @@ use crate::encode::{self, Decodable, Encodable}; use crate::issuance::AssetId; /// A CT commitment to an amount -#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)] +#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)] pub enum Value { /// No value + #[default] Null, /// Value is explicitly encoded Explicit(u64), @@ -133,12 +134,6 @@ impl fmt::Display for Value { } } -impl Default for Value { - fn default() -> Self { - Value::Null - } -} - impl Encodable for Value { fn consensus_encode(&self, mut s: S) -> Result { match *self { @@ -252,9 +247,10 @@ impl<'de> Deserialize<'de> for Value { } /// A CT commitment to an asset -#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)] +#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)] pub enum Asset { /// No value + #[default] Null, /// Asset entropy is explicitly encoded Explicit(AssetId), @@ -360,13 +356,6 @@ impl fmt::Display for Asset { } } -impl Default for Asset { - fn default() -> Self { - Asset::Null - } -} - - impl Encodable for Asset { fn consensus_encode(&self, mut s: S) -> Result { match *self { @@ -481,9 +470,10 @@ impl<'de> Deserialize<'de> for Asset { } /// A CT commitment to an output nonce (i.e. a public key) -#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)] +#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)] pub enum Nonce { /// No value + #[default] Null, /// There should be no such thing as an "explicit nonce", but Elements will deserialize /// such a thing (and insists that its size be 32 bytes). So we stick a 32-byte type here @@ -618,12 +608,6 @@ impl fmt::Display for Nonce { } } -impl Default for Nonce { - fn default() -> Self { - Nonce::Null - } -} - impl Encodable for Nonce { fn consensus_encode(&self, mut s: S) -> Result { match *self { diff --git a/src/dynafed.rs b/src/dynafed.rs index 2c402825..6a217595 100644 --- a/src/dynafed.rs +++ b/src/dynafed.rs @@ -216,9 +216,10 @@ impl Decodable for FullParams { } /// Dynamic federations parameters, as encoded in a block header -#[derive(Clone, Eq, Hash, PartialEq, PartialOrd, Ord)] +#[derive(Clone, Default, Eq, Hash, PartialEq, PartialOrd, Ord)] pub enum Params { /// Null entry, used to signal "no vote" as a proposal + #[default] Null, /// Compact params where the fedpeg data and extension space /// are not included, and are assumed to be equal to the values @@ -398,12 +399,6 @@ impl Params { } } -impl Default for Params { - fn default() -> Params { - Params::Null - } -} - #[cfg(feature = "serde")] impl<'de> Deserialize<'de> for Params { fn deserialize>(d: D) -> Result { From 113897d53f0b79bd892103cab0706963a2f79605 Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 21:38:20 +0000 Subject: [PATCH 03/28] clippy: fix bool_to_int_with_if lint Convert a bool to 64 with `from` rather than a manual conversion. --- src/transaction.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/transaction.rs b/src/transaction.rs index 55e30563..b12f50b7 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -832,7 +832,7 @@ impl TxOut { /// Extracts the minimum value from the rangeproof, if there is one, or returns 0. pub fn minimum_value(&self) -> u64 { - let min_value = if self.script_pubkey.is_op_return() { 0 } else { 1 }; + let min_value = u64::from(self.script_pubkey.is_op_return()); match self.value { confidential::Value::Null => min_value, From dbd8821c4d731f3806deccabb7486205ddbfb1a4 Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 21:49:37 +0000 Subject: [PATCH 04/28] clippy: fix the cast_lossless lint This one is about casts that are totally unnecessary. --- src/address.rs | 2 +- src/ext.rs | 8 ++++---- src/opcodes.rs | 4 ++-- src/pset/elip100.rs | 2 +- src/script.rs | 4 ++-- src/taproot.rs | 2 +- src/transaction.rs | 2 +- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/address.rs b/src/address.rs index e4b5fda3..5cad806a 100644 --- a/src/address.rs +++ b/src/address.rs @@ -430,7 +430,7 @@ impl Address { version: witver, program: ref witprog, } => script::Builder::new() - .push_int(witver.to_u8() as i64) + .push_int(i64::from(witver.to_u8())) .push_slice(witprog), } .into_script() diff --git a/src/ext.rs b/src/ext.rs index b7c1c543..b293db3a 100644 --- a/src/ext.rs +++ b/src/ext.rs @@ -100,7 +100,7 @@ impl WriteExt for W { } #[inline] fn emit_bool(&mut self, v: bool) -> Result<(), io::Error> { - self.write_all(&[v as u8]) + self.write_all(&[u8::from(v)]) } #[inline] fn emit_slice(&mut self, v: &[u8]) -> Result { @@ -177,7 +177,7 @@ impl ReadExt for R { if x < 0x10000 { Err(encode::Error::NonMinimalVarInt) } else { - Ok(x as u64) + Ok(u64::from(x)) } } 0xFD => { @@ -185,10 +185,10 @@ impl ReadExt for R { if x < 0xFD { Err(encode::Error::NonMinimalVarInt) } else { - Ok(x as u64) + Ok(u64::from(x)) } } - n => Ok(n as u64), + n => Ok(u64::from(n)), } } } diff --git a/src/opcodes.rs b/src/opcodes.rs index e09dbc46..8ae4490c 100644 --- a/src/opcodes.rs +++ b/src/opcodes.rs @@ -836,11 +836,11 @@ impl All { // 16 opcodes of PushNum class (op, _) if op.code >= OP_PUSHNUM_1.code && op.code <= OP_PUSHNUM_16.code => { - Class::PushNum(1 + self.code as i32 - OP_PUSHNUM_1.code as i32) + Class::PushNum(1 + i32::from(self.code) - i32::from(OP_PUSHNUM_1.code)) }, // 76 opcodes of PushBytes class - (op, _) if op.code <= OP_PUSHBYTES_75.code => Class::PushBytes(self.code as u32), + (op, _) if op.code <= OP_PUSHBYTES_75.code => Class::PushBytes(u32::from(self.code)), // opcodes of Ordinary class: 61 for Legacy and 60 for TapScript context (_, _) => Class::Ordinary(Ordinary::try_from_all(self).unwrap()), diff --git a/src/pset/elip100.rs b/src/pset/elip100.rs index 0e8cb3ae..2cc514e4 100644 --- a/src/pset/elip100.rs +++ b/src/pset/elip100.rs @@ -187,7 +187,7 @@ impl TokenMetadata { pub fn serialize(&self) -> Vec { let mut result = vec![]; - result.push(self.issuance_blinded as u8); + result.push(u8::from(self.issuance_blinded)); self.asset_id .consensus_encode(&mut result) diff --git a/src/script.rs b/src/script.rs index 025bf5a8..d99894d9 100644 --- a/src/script.rs +++ b/src/script.rs @@ -199,7 +199,7 @@ pub fn read_scriptint(v: &[u8]) -> Result { if len > 4 { return Err(Error::NumericOverflow); } let (mut ret, sh) = v.iter() - .fold((0, 0), |(acc, sh), n| (acc + ((*n as i64) << sh), sh + 8)); + .fold((0, 0), |(acc, sh), n| (acc + ((i64::from(*n)) << sh), sh + 8)); if v[len - 1] & 0x80 != 0 { ret &= (1 << (sh - 1)) - 1; ret = -ret; @@ -745,7 +745,7 @@ impl Builder { // We can special-case -1, 1-16 if data == -1 || (data >= 1 && data <= 16) { let opcode = opcodes::All::from( - (data - 1 + opcodes::OP_TRUE.into_u8() as i64) as u8 + (data - 1 + i64::from(opcodes::OP_TRUE.into_u8())) as u8 ); self.push_opcode(opcode) } diff --git a/src/taproot.rs b/src/taproot.rs index 2fb03d1f..d1fb38e7 100644 --- a/src/taproot.rs +++ b/src/taproot.rs @@ -167,7 +167,7 @@ impl TaprootSpendInfo { { let mut node_weights = BinaryHeap::<(Reverse, NodeInfo)>::new(); for (p, leaf) in script_weights { - node_weights.push((Reverse(p as u64), NodeInfo::new_leaf_with_ver(leaf, LeafVersion::default()))); + node_weights.push((Reverse(u64::from(p)), NodeInfo::new_leaf_with_ver(leaf, LeafVersion::default()))); } if node_weights.is_empty() { return Err(TaprootBuilderError::IncompleteTree); diff --git a/src/transaction.rs b/src/transaction.rs index b12f50b7..a2ad511b 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -615,7 +615,7 @@ impl TxIn { /// Obtain the outpoint flag corresponding to this input pub fn outpoint_flag(&self) -> u8 { - ((self.is_pegin as u8) << 6 ) | ((self.has_issuance() as u8) << 7) + (u8::from(self.is_pegin) << 6) | (u8::from(self.has_issuance()) << 7) } /// Compute the issuance asset ids from this [`TxIn`]. This function does not check From 0eb9aa6ac0801598373066548876c2c27f5fdf1a Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 21:54:11 +0000 Subject: [PATCH 05/28] clippy: fix cloned_instead_of_copied lint --- src/script.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/script.rs b/src/script.rs index d99894d9..7f54be5c 100644 --- a/src/script.rs +++ b/src/script.rs @@ -787,7 +787,7 @@ impl Builder { _ => panic!("tried to put a 4bn+ sized object into a script!") } // Then push the raw bytes - self.0.extend(data.iter().cloned()); + self.0.extend(data.iter().copied()); self.1 = None; self } @@ -957,24 +957,24 @@ mod test { script = script.push_int(4); comp.push(84u8); assert_eq!(&script[..], &comp[..]); script = script.push_int(-1); comp.push(79u8); assert_eq!(&script[..], &comp[..]); // forced scriptint - script = script.push_scriptint(4); comp.extend([1u8, 4].iter().cloned()); assert_eq!(&script[..], &comp[..]); + script = script.push_scriptint(4); comp.extend([1u8, 4].iter().copied()); assert_eq!(&script[..], &comp[..]); // big ints - script = script.push_int(17); comp.extend([1u8, 17].iter().cloned()); assert_eq!(&script[..], &comp[..]); - script = script.push_int(10000); comp.extend([2u8, 16, 39].iter().cloned()); assert_eq!(&script[..], &comp[..]); + script = script.push_int(17); comp.extend([1u8, 17].iter().copied()); assert_eq!(&script[..], &comp[..]); + script = script.push_int(10000); comp.extend([2u8, 16, 39].iter().copied()); assert_eq!(&script[..], &comp[..]); // notice the sign bit set here, hence the extra zero/128 at the end - script = script.push_int(10000000); comp.extend([4u8, 128, 150, 152, 0].iter().cloned()); assert_eq!(&script[..], &comp[..]); - script = script.push_int(-10000000); comp.extend([4u8, 128, 150, 152, 128].iter().cloned()); assert_eq!(&script[..], &comp[..]); + script = script.push_int(10000000); comp.extend([4u8, 128, 150, 152, 0].iter().copied()); assert_eq!(&script[..], &comp[..]); + script = script.push_int(-10000000); comp.extend([4u8, 128, 150, 152, 128].iter().copied()); assert_eq!(&script[..], &comp[..]); // data - script = script.push_slice(b"NRA4VR"); comp.extend([6u8, 78, 82, 65, 52, 86, 82].iter().cloned()); assert_eq!(&script[..], &comp[..]); + script = script.push_slice(b"NRA4VR"); comp.extend([6u8, 78, 82, 65, 52, 86, 82].iter().copied()); assert_eq!(&script[..], &comp[..]); // keys let keystr = "21032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af"; let key = PublicKey::from_str(&keystr[2..]).unwrap(); - script = script.push_key(&key); comp.extend(Vec::from_hex(keystr).unwrap().iter().cloned()); assert_eq!(&script[..], &comp[..]); + script = script.push_key(&key); comp.extend(Vec::from_hex(keystr).unwrap().iter().copied()); assert_eq!(&script[..], &comp[..]); let keystr = "41042e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af191923a2964c177f5b5923ae500fca49e99492d534aa3759d6b25a8bc971b133"; let key = PublicKey::from_str(&keystr[2..]).unwrap(); - script = script.push_key(&key); comp.extend(Vec::from_hex(keystr).unwrap().iter().cloned()); assert_eq!(&script[..], &comp[..]); + script = script.push_key(&key); comp.extend(Vec::from_hex(keystr).unwrap().iter().copied()); assert_eq!(&script[..], &comp[..]); // opcodes script = script.push_opcode(opcodes::all::OP_CHECKSIG); comp.push(0xACu8); assert_eq!(&script[..], &comp[..]); From 3f1204639a402c9bff5ca0880f372eb96aa77745 Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 22:17:41 +0000 Subject: [PATCH 06/28] clippy: fix default_trait_access lint As a matter of style, I don't like Default::default because it creates an object without specifying what type it has. --- src/fast_merkle_root.rs | 2 +- src/pset/map/global.rs | 6 ++--- src/pset/map/input.rs | 53 +++++++++++++++++++++++++++++++++++++++-- src/pset/map/output.rs | 4 ++-- src/pset/serialize.rs | 2 +- src/transaction.rs | 6 ++--- 6 files changed, 61 insertions(+), 12 deletions(-) diff --git a/src/fast_merkle_root.rs b/src/fast_merkle_root.rs index 098bbde1..4d88ea81 100644 --- a/src/fast_merkle_root.rs +++ b/src/fast_merkle_root.rs @@ -29,7 +29,7 @@ fn sha256midstate(left: &[u8], right: &[u8]) -> sha256::Midstate { /// Note that the merkle root calculated with this method is not the same as the /// one computed by a normal SHA256(d) merkle root. pub fn fast_merkle_root(leaves: &[[u8; 32]]) -> sha256::Midstate { - let mut result_hash = Default::default(); + let mut result_hash = sha256::Midstate::default(); // Implementation based on ComputeFastMerkleRoot method in Elements Core. if leaves.is_empty() { return result_hash; diff --git a/src/pset/map/global.rs b/src/pset/map/global.rs index bb6ddc64..7daf72a1 100644 --- a/src/pset/map/global.rs +++ b/src/pset/map/global.rs @@ -206,7 +206,7 @@ impl Map for Global { } fn get_pairs(&self) -> Result, encode::Error> { - let mut rv: Vec = Default::default(); + let mut rv: Vec = Vec::default(); let TxData { version, @@ -368,9 +368,9 @@ impl_psetmap_consensus_encoding!(Global); impl Decodable for Global { fn consensus_decode(mut d: D) -> Result { let mut version: Option = None; - let mut unknowns: BTreeMap> = Default::default(); + let mut unknowns: BTreeMap> = BTreeMap::new(); let mut xpub_map: BTreeMap = - Default::default(); + BTreeMap::new(); let mut proprietary = BTreeMap::new(); let mut scalars = Vec::new(); diff --git a/src/pset/map/input.rs b/src/pset/map/input.rs index 0ab407b6..cd351a18 100644 --- a/src/pset/map/input.rs +++ b/src/pset/map/input.rs @@ -317,7 +317,56 @@ pub struct Input { impl Default for Input { fn default() -> Self { - Self { non_witness_utxo: Default::default(), witness_utxo: Default::default(), partial_sigs: Default::default(), sighash_type: Default::default(), redeem_script: Default::default(), witness_script: Default::default(), bip32_derivation: Default::default(), final_script_sig: Default::default(), final_script_witness: Default::default(), ripemd160_preimages: Default::default(), sha256_preimages: Default::default(), hash160_preimages: Default::default(), hash256_preimages: Default::default(), previous_txid: Txid::all_zeros(), previous_output_index: Default::default(), sequence: Default::default(), required_time_locktime: Default::default(), required_height_locktime: Default::default(), tap_key_sig: Default::default(), tap_script_sigs: Default::default(), tap_scripts: Default::default(), tap_key_origins: Default::default(), tap_internal_key: Default::default(), tap_merkle_root: Default::default(), issuance_value_amount: Default::default(), issuance_value_comm: Default::default(), issuance_value_rangeproof: Default::default(), issuance_keys_rangeproof: Default::default(), pegin_tx: Default::default(), pegin_txout_proof: Default::default(), pegin_genesis_hash: Default::default(), pegin_claim_script: Default::default(), pegin_value: Default::default(), pegin_witness: Default::default(), issuance_inflation_keys: Default::default(), issuance_inflation_keys_comm: Default::default(), issuance_blinding_nonce: Default::default(), issuance_asset_entropy: Default::default(), in_utxo_rangeproof: Default::default(), in_issuance_blind_value_proof: Default::default(), in_issuance_blind_inflation_keys_proof: Default::default(), amount: Default::default(), blind_value_proof: Default::default(), asset: Default::default(), blind_asset_proof: Default::default(), blinded_issuance: Default::default(), proprietary: Default::default(), unknown: Default::default() } + Self { + non_witness_utxo: None, + witness_utxo: None, + partial_sigs: BTreeMap::new(), + sighash_type: None, + redeem_script: None, + witness_script: None, + bip32_derivation: BTreeMap::new(), + final_script_sig: None, + final_script_witness: None, + ripemd160_preimages: BTreeMap::new(), + sha256_preimages: BTreeMap::new(), + hash160_preimages: BTreeMap::new(), + hash256_preimages: BTreeMap::new(), + previous_txid: Txid::all_zeros(), + previous_output_index: 0, + sequence: None, + required_time_locktime: None, + required_height_locktime: None, + tap_key_sig: None, + tap_script_sigs: BTreeMap::new(), + tap_scripts: BTreeMap::new(), + tap_key_origins: BTreeMap::new(), + tap_internal_key: None, + tap_merkle_root: None, + issuance_value_amount: None, + issuance_value_comm: None, + issuance_value_rangeproof: None, + issuance_keys_rangeproof: None, + pegin_tx: None, + pegin_txout_proof: None, + pegin_genesis_hash: None, + pegin_claim_script: None, + pegin_value: None, + pegin_witness: None, + issuance_inflation_keys: None, + issuance_inflation_keys_comm: None, + issuance_blinding_nonce: None, + issuance_asset_entropy: None, + in_utxo_rangeproof: None, + in_issuance_blind_value_proof: None, + in_issuance_blind_inflation_keys_proof: None, + amount: None, + blind_value_proof: None, + asset: None, + blind_asset_proof: None, + blinded_issuance: None, + proprietary: BTreeMap::new(), + unknown: BTreeMap::new(), + } } } @@ -783,7 +832,7 @@ impl Map for Input { } fn get_pairs(&self) -> Result, encode::Error> { - let mut rv: Vec = Default::default(); + let mut rv: Vec = Vec::default(); impl_pset_get_pair! { rv.push(self.non_witness_utxo as ) diff --git a/src/pset/map/output.rs b/src/pset/map/output.rs index ad8df6ff..c636571a 100644 --- a/src/pset/map/output.rs +++ b/src/pset/map/output.rs @@ -199,7 +199,7 @@ impl Output { amount: Some(amount), blinding_key, asset: Some(asset), - ..Default::default() + ..Self::default() } } @@ -407,7 +407,7 @@ impl Map for Output { } fn get_pairs(&self) -> Result, encode::Error> { - let mut rv: Vec = Default::default(); + let mut rv: Vec = Vec::default(); impl_pset_get_pair! { rv.push(self.redeem_script as ) diff --git a/src/pset/serialize.rs b/src/pset/serialize.rs index 87062d55..a38db623 100644 --- a/src/pset/serialize.rs +++ b/src/pset/serialize.rs @@ -182,7 +182,7 @@ impl Deserialize for KeySource { }; let fprint: Fingerprint = Fingerprint::from(prefix); - let mut dpath: Vec = Default::default(); + let mut dpath: Vec = Vec::default(); let mut d = &bytes[4..]; while !d.is_empty() { diff --git a/src/transaction.rs b/src/transaction.rs index a2ad511b..a373310d 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -502,12 +502,12 @@ pub struct TxIn { impl Default for TxIn { fn default() -> Self { Self { - previous_output: Default::default(), // same as in rust-bitcoin + previous_output: OutPoint::default(), // same as in rust-bitcoin is_pegin: false, script_sig: Script::new(), sequence: Sequence::MAX, // same as in rust-bitcoin - asset_issuance: Default::default(), - witness: Default::default() + asset_issuance: AssetIssuance::default(), + witness: TxInWitness::default() } } } From ad2eaac7c5370539fdda3a142408f80b73c42203 Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 22:41:55 +0000 Subject: [PATCH 07/28] clippy: fix `doc_markdown` lint This one has a huge diff, and there's still a ton of work to do to clean up these docs, but it should be a big improvement. --- src/address.rs | 2 +- src/blind.rs | 39 ++++++------ src/confidential.rs | 18 +++--- src/dynafed.rs | 24 ++++---- src/encode.rs | 2 +- src/error.rs | 2 +- src/hash_types.rs | 2 +- src/internal_macros.rs | 2 +- src/issuance.rs | 6 +- src/locktime.rs | 6 +- src/opcodes.rs | 132 ++++++++++++++++++++--------------------- src/pset/elip100.rs | 6 +- src/pset/elip102.rs | 8 +-- src/pset/error.rs | 6 +- src/pset/map/global.rs | 16 ++--- src/pset/map/input.rs | 90 ++++++++++++++-------------- src/pset/map/output.rs | 40 ++++++------- src/pset/mod.rs | 10 ++-- src/pset/raw.rs | 4 +- src/schnorr.rs | 2 +- src/script.rs | 12 ++-- src/serde_utils.rs | 10 ++-- src/sighash.rs | 26 ++++---- src/taproot.rs | 42 ++++++------- src/transaction.rs | 4 +- 25 files changed, 256 insertions(+), 255 deletions(-) diff --git a/src/address.rs b/src/address.rs index 5cad806a..2c123f88 100644 --- a/src/address.rs +++ b/src/address.rs @@ -534,7 +534,7 @@ impl Address { } /// Parse the address using the given parameters. - /// When using the built-in parameters, you can use [FromStr]. + /// When using the built-in parameters, you can use [`FromStr`]. pub fn parse_with_params( s: &str, params: &'static AddressParams, diff --git a/src/blind.rs b/src/blind.rs index 650fcd74..bd42c24a 100644 --- a/src/blind.rs +++ b/src/blind.rs @@ -39,7 +39,7 @@ pub enum TxOutError { UnExpectedNullValue, /// Unexpected Null asset UnExpectedNullAsset, - /// Money should be between 0 and 21_000_000 + /// Money should be between 0 and `21_000_000` MoneyOutofRange, /// Zero value explicit txout with non-provably unspendable script NonUnspendableZeroValue, @@ -90,7 +90,7 @@ pub enum VerificationError { RangeProofError(usize, secp256k1_zkp::Error), /// Missing Range Proof RangeProofMissing(usize), - /// Verification of SurjectionProof failed + /// Verification of `SurjectionProof` failed SurjectionProofError(usize, secp256k1_zkp::Error), /// Surjection Proof verification error SurjectionProofVerificationError(usize), @@ -165,7 +165,7 @@ pub enum ConfidentialTxOutError { NoBlindingKeyInAddress, /// Error originated in `secp256k1_zkp`. Upstream(secp256k1_zkp::Error), - /// General TxOut errors + /// General `TxOut` errors TxOutError(usize, TxOutError), /// Expected Explicit Asset for blinding ExpectedExplicitAsset, @@ -264,7 +264,7 @@ impl TxOutSecrets { /// Gets the surjection inputs from [`TxOutSecrets`]. /// - /// Returns a tuple (assetid, blind_factor, generator) if the blinds are + /// Returns a tuple `(assetid, blind_factor, generator)` if the blinds are /// consistent with asset commitment /// Otherwise, returns an error pub fn surjection_inputs(&self, secp: &Secp256k1) -> (Generator, Tag, Tweak) { @@ -327,7 +327,7 @@ impl SurjectionInput { } /// Handy method to convert [`SurjectionInput`] into a surjection target - /// that can be used while creating a new [SurjectionProof]. + /// that can be used while creating a new [`SurjectionProof`]. /// /// Only errors when the input asset is Null. pub fn surjection_target( @@ -405,8 +405,8 @@ impl Value { /// /// # Returns: /// - /// A pair of blinded value, nonce and corresponding proof as ([`Value`], [`Nonce`], [`RangeProof`]) - /// The nonce here refers to public key corresponding to the input `ephemeral_sk` + /// * A pair of blinded value, nonce and corresponding proof as ([`Value`], [`Nonce`], [`RangeProof`]) + /// * The nonce here refers to public key corresponding to the input `ephemeral_sk` pub fn blind( self, secp: &Secp256k1, @@ -424,7 +424,8 @@ impl Value { Ok((value_commit, nonce, rangeproof)) } - /// Blinds with the given shared_secret(instead of computing it via ECDH) + /// Blinds with the given `shared_secret` (instead of computing it via ECDH). + /// /// This is useful while blinding assets as there is no counter party to provide /// the blinding key. pub fn blind_with_shared_secret( @@ -466,7 +467,7 @@ impl TxOut { pub const RANGEPROOF_EXP_SHIFT: i32 = 0; /// Rangeproof Minimum private bits pub const RANGEPROOF_MIN_PRIV_BITS: u8 = 52; - /// Maximum explicit amount in a bitcoin TxOut + /// Maximum explicit amount in a bitcoin `TxOut` pub const MAX_MONEY: u64 = 21_000_000 * 100_000_000; /// Creates a new confidential output that is **not** the last one in the transaction. @@ -474,7 +475,7 @@ impl TxOut { /// Inputs for issuances must be provided in the followed by inputs for input asset. /// /// For example, if the second input contains non-null issuance and re-issuance tokens, - /// the `spent_utxo_secrets` should be of the form [inp_1, inp_2, inp_2_issue, inp2_reissue,...] + /// the `spent_utxo_secrets` should be of the form [`inp_1`, `inp_2`, `inp_2_issue`, `inp2_reissue`,...] /// /// If the issuance or re-issuance is null, it should not be added to `spent_utxo_secrets` /// @@ -571,7 +572,7 @@ impl TxOut { Ok(txout) } - /// Convert a explicit TxOut into a Confidential TxOut. + /// Convert a explicit `TxOut` into a Confidential `TxOut`. /// The blinding key is provided by the blinder parameter. /// The initial value of nonce is ignored and is set to the ECDH pubkey /// sampled by the sender. @@ -653,7 +654,7 @@ impl TxOut { /// /// Inputs for issuances must be provided in the followed by inputs for input asset. /// For example, if the second input contains non-null issuance and re-issuance tokens, - /// the `spent_utxo_secrets` should be of the form [inp_1, inp_2, inp_2_issue, inp2_reissue,...] + /// the `spent_utxo_secrets` should be of the form [`inp_1`, `inp_2`, `inp_2_issue`, `inp2_reissue`,...] /// If the issuance or re-issuance is null, it should not be added to `spent_utxo_secrets` /// /// # Returns: @@ -693,7 +694,7 @@ impl TxOut { Ok((txout, out_abf, out_vbf, ephemeral_sk)) } - /// Similar to [TxOut::new_last_confidential], but allows specifying the asset blinding factor + /// Similar to [`TxOut::new_last_confidential`], but allows specifying the asset blinding factor /// and the ephemeral key. The value-blinding factor is computed adaptively #[allow(clippy::too_many_arguments)] pub fn with_secrets_last( @@ -892,7 +893,7 @@ impl TxIn { /// Blind issuances for this [`TxIn`]. Asset amount and token amount must be /// set in [`AssetIssuance`](crate::AssetIssuance) field for this input /// - /// Returns (issuance_blinding_factor, issue_blind_sec_key, token_blinding_factor, token_blind_sec_key) + /// Returns (`issuance_blinding_factor`, `issue_blind_sec_key`, `token_blinding_factor`, `token_blind_sec_key`) pub fn blind_issuances( &mut self, secp: &Secp256k1, @@ -937,9 +938,9 @@ impl Transaction { /// equation for Confidential transactions holds. /// i.e Sum of inputs = Sum of outputs + fees. /// And the corresponding surjection/rangeproofs are correct. - /// For checking of surjection proofs and amounts, spent_utxos parameter + /// For checking of surjection proofs and amounts, `spent_utxos` parameter /// should contain information about the prevouts. Note that the order of - /// spent_utxos should be consistent with transaction inputs. + /// `spent_utxos` should be consistent with transaction inputs. /// ## Examples /// /// ``` @@ -1200,9 +1201,9 @@ pub enum BlindError { TooFewBlindingOutputs, /// All outputs must be explicit asset/amounts MustHaveAllExplicitTxOuts, - /// General TxOut errors + /// General `TxOut` errors ConfidentialTxOutError(ConfidentialTxOutError), - /// No Issuances to blind in this TxIn + /// No Issuances to blind in this `TxIn` NoIssuanceToBlind, /// Zero Value Blinding not allowed ZeroValueBlindingNotAllowed, @@ -1278,7 +1279,7 @@ pub trait BlindValueProofs: Sized { } impl BlindValueProofs for RangeProof { - /// Outputs a `[RangeProof]` that blinded value_commit + /// Outputs a [`RangeProof`] that blinded `value_commit` /// corresponds to explicit value fn blind_value_proof( rng: &mut R, diff --git a/src/confidential.rs b/src/confidential.rs index 555f63ee..1fbf5ea1 100644 --- a/src/confidential.rs +++ b/src/confidential.rs @@ -100,7 +100,7 @@ impl Value { } /// Returns the explicit inner value. - /// Returns [None] if [Value::is_explicit] returns false. + /// Returns [None] if [`Value::is_explicit`] returns false. pub fn explicit(&self) -> Option { match *self { Value::Explicit(i) => Some(i), @@ -109,7 +109,7 @@ impl Value { } /// Returns the confidential commitment in case of a confidential value. - /// Returns [None] if [Value::is_confidential] returns false. + /// Returns [None] if [`Value::is_confidential`] returns false. pub fn commitment(&self) -> Option { match *self { Value::Confidential(i) => Some(i), @@ -302,7 +302,7 @@ impl Asset { } /// Returns the explicit inner value. - /// Returns [None] if [Asset::is_explicit] returns false. + /// Returns [None] if [`Asset::is_explicit`] returns false. pub fn explicit(&self) -> Option { match *self { Asset::Explicit(i) => Some(i), @@ -311,7 +311,7 @@ impl Asset { } /// Returns the confidential commitment in case of a confidential value. - /// Returns [None] if [Asset::is_confidential] returns false. + /// Returns [None] if [`Asset::is_confidential`] returns false. pub fn commitment(&self) -> Option { match *self { Asset::Confidential(i) => Some(i), @@ -494,7 +494,7 @@ impl Nonce { Self::with_ephemeral_sk(secp, ephemeral_sk, receiver_blinding_pk) } - /// Similar to [Nonce::new_confidential], but with a given `ephemeral_sk` + /// Similar to [`Nonce::new_confidential`], but with a given `ephemeral_sk` /// instead of sampling it from rng. pub fn with_ephemeral_sk( secp: &Secp256k1, @@ -569,7 +569,7 @@ impl Nonce { } /// Returns the explicit inner value. - /// Returns [None] if [Nonce::is_explicit] returns false. + /// Returns [None] if [`Nonce::is_explicit`] returns false. pub fn explicit(&self) -> Option<[u8; 32]> { match *self { Nonce::Explicit(i) => Some(i), @@ -578,7 +578,7 @@ impl Nonce { } /// Returns the confidential commitment in case of a confidential value. - /// Returns [None] if [Nonce::is_confidential] returns false. + /// Returns [None] if [`Nonce::is_confidential`] returns false. pub fn commitment(&self) -> Option { match *self { Nonce::Confidential(i) => Some(i), @@ -740,7 +740,7 @@ impl AssetBlindingFactor { self.0 } - /// Get a unblinded/zero AssetBlinding factor + /// Get a unblinded/zero `AssetBlinding` factor pub fn zero() -> Self { AssetBlindingFactor(ZERO_TWEAK) } @@ -907,7 +907,7 @@ impl ValueBlindingFactor { self.0 } - /// Get a unblinded/zero AssetBlinding factor + /// Get a unblinded/zero `AssetBlinding` factor pub fn zero() -> Self { ValueBlindingFactor(ZERO_TWEAK) } diff --git a/src/dynafed.rs b/src/dynafed.rs index 6a217595..bd78eab6 100644 --- a/src/dynafed.rs +++ b/src/dynafed.rs @@ -96,7 +96,7 @@ pub struct FullParams { } impl FullParams { - /// Construct a set of FullParams + /// Construct a set of `FullParams` pub fn new( signblockscript: Script, signblock_witness_limit: u32, @@ -131,7 +131,7 @@ impl FullParams { crate::fast_merkle_root::fast_merkle_root(&leaves[..]) } - /// Calculate the root of this [FullParams]. + /// Calculate the root of this [`FullParams`]. pub fn calculate_root(&self) -> sha256::Midstate { fn serialize_hash(obj: &E) -> sha256d::Hash { let mut engine = sha256d::Hash::engine(); @@ -162,7 +162,7 @@ impl FullParams { } } - /// Format for [fmt::Debug]. + /// Format for [`fmt::Debug`]. fn fmt_debug(&self, f: &mut fmt::Formatter, name: &'static str) -> fmt::Result { let mut s = f.debug_struct(name); s.field("signblockscript", &HexBytes(&self.signblockscript[..])); @@ -253,7 +253,7 @@ impl fmt::Debug for Params { } impl Params { - /// Check whether this is [Params::Null]. + /// Check whether this is [`Params::Null`]. pub fn is_null(&self) -> bool { match *self { Params::Null => true, @@ -262,7 +262,7 @@ impl Params { } } - /// Check whether this is [Params::Compact]. + /// Check whether this is [`Params::Compact`]. pub fn is_compact(&self) -> bool { match *self { Params::Null => false, @@ -271,7 +271,7 @@ impl Params { } } - /// Check whether this is [Params::Full]. + /// Check whether this is [`Params::Full`]. pub fn is_full(&self) -> bool { match *self { Params::Null => false, @@ -280,7 +280,7 @@ impl Params { } } - /// Get the signblockscript. Is [None] for [Params::Null] params. + /// Get the signblockscript. Is [None] for [`Params::Null`] params. pub fn signblockscript(&self) -> Option<&Script> { match *self { Params::Null => None, @@ -289,7 +289,7 @@ impl Params { } } - /// Get the signblock_witness_limit. Is [None] for [Params::Null] params. + /// Get the `signblock_witness_limit`. Is [None] for [`Params::Null`] params. pub fn signblock_witness_limit(&self) -> Option { match *self { Params::Null => None, @@ -298,7 +298,7 @@ impl Params { } } - /// Get the fedpeg_program. Is [None] for non-[Params::Full] params. + /// Get the `fedpeg_program`. Is [None] for non-[`Params::Full`] params. pub fn fedpeg_program(&self) -> Option<&bitcoin::ScriptBuf> { match *self { Params::Null => None, @@ -307,7 +307,7 @@ impl Params { } } - /// Get the fedpegscript. Is [None] for non-[Params::Full] params. + /// Get the fedpegscript. Is [None] for non-[`Params::Full`] params. pub fn fedpegscript(&self) -> Option<&Vec> { match *self { Params::Null => None, @@ -316,7 +316,7 @@ impl Params { } } - /// Get the extension_space. Is [None] for non-[Params::Full] params. + /// Get the `extension_space`. Is [None] for non-[`Params::Full`] params. pub fn extension_space(&self) -> Option<&Vec>> { match *self { Params::Null => None, @@ -325,7 +325,7 @@ impl Params { } } - /// Get the elided_root. Is [None] for non-[Params::Compact] params. + /// Get the `elided_root`. Is [None] for non-[`Params::Compact`] params. pub fn elided_root(&self) -> Option<&sha256::Midstate> { match *self { Params::Null => None, diff --git a/src/encode.rs b/src/encode.rs index 08735f10..39cfb2dc 100644 --- a/src/encode.rs +++ b/src/encode.rs @@ -59,7 +59,7 @@ pub enum Error { HexError(crate::hex::Error), /// Got a time-based locktime when expecting a height-based one, or vice-versa BadLockTime(crate::LockTime), - /// VarInt was encoded in a non-minimal way. + /// `VarInt` was encoded in a non-minimal way. NonMinimalVarInt, } diff --git a/src/error.rs b/src/error.rs index 0d56617f..6957ee8a 100644 --- a/src/error.rs +++ b/src/error.rs @@ -2,7 +2,7 @@ pub use crate::parse::ParseIntError; -/// Impls std::error::Error for the specified type with appropriate attributes, possibly returning +/// Impls `std::error::Error` for the specified type with appropriate attributes, possibly returning /// source. macro_rules! impl_std_error { // No source available diff --git a/src/hash_types.rs b/src/hash_types.rs index 8220dd7f..6231c34b 100644 --- a/src/hash_types.rs +++ b/src/hash_types.rs @@ -15,7 +15,7 @@ //! File defines types for hashes used throughout the library. //! //! These types are needed in order -//! to avoid mixing data of the same hash format (like SHA256d) but of different meaning +//! to avoid mixing data of the same hash format (like `SHA256d`) but of different meaning //! (transaction id, block hash etc). use crate::hashes::{hash160, hash_newtype, sha256, sha256d, Hash}; diff --git a/src/internal_macros.rs b/src/internal_macros.rs index 1936c6c2..aa4c0337 100644 --- a/src/internal_macros.rs +++ b/src/internal_macros.rs @@ -211,7 +211,7 @@ macro_rules! serde_string_impl { }; } -/// A combination of serde_struct_impl and serde_string_impl where string is +/// A combination of `serde_struct_impl` and `serde_string_impl` where string is /// used for human-readable serialization and struct is used for /// non-human-readable serialization. macro_rules! serde_struct_human_string_impl { diff --git a/src/issuance.rs b/src/issuance.rs index de478e7b..87688a72 100644 --- a/src/issuance.rs +++ b/src/issuance.rs @@ -75,17 +75,17 @@ impl AssetId { 0x3d, 0x1c, 0x04, 0xed, 0xe9, 0x79, 0x02, 0x6f, ])); - /// Create an [AssetId] from its inner type. + /// Create an [`AssetId`] from its inner type. pub const fn from_inner(midstate: sha256::Midstate) -> AssetId { AssetId(midstate) } - /// Convert the [AssetId] into its inner type. + /// Convert the [`AssetId`] into its inner type. pub fn into_inner(self) -> sha256::Midstate { self.0 } - /// Copies a byte slice into an AssetId object + /// Copies a byte slice into an `AssetId` object pub fn from_slice(sl: &[u8]) -> Result { sha256::Midstate::from_slice(sl).map(AssetId) } diff --git a/src/locktime.rs b/src/locktime.rs index 5ffddf8c..e06786ef 100644 --- a/src/locktime.rs +++ b/src/locktime.rs @@ -11,7 +11,7 @@ // If not, see . // -//! Provides type [`LockTime`] that implements the logic around nLockTime/OP_CHECKLOCKTIMEVERIFY. +//! Provides type [`LockTime`] that implements the logic around `nLockTime/OP_CHECKLOCKTIMEVERIFY`. //! //! There are two types of lock time: lock-by-blockheight and lock-by-blocktime, distinguished by //! whether `LockTime < LOCKTIME_THRESHOLD`. @@ -45,7 +45,7 @@ pub const LOCK_TIME_THRESHOLD: u32 = 500_000_000; /// A lock time value, representing either a block height or a UNIX timestamp (seconds since epoch). /// /// Used for transaction lock time (`nLockTime` in Bitcoin Core and [`crate::Transaction::lock_time`] -/// in this library) and also for the argument to opcode 'OP_CHECKLOCKTIMEVERIFY`. +/// in this library) and also for the argument to opcode `OP_CHECKLOCKTIMEVERIFY`. /// /// ### Relevant BIPs /// @@ -100,7 +100,7 @@ impl LockTime { /// transaction with nLocktime==0 is able to be included immediately in any block. pub const ZERO: LockTime = LockTime::Blocks(Height(0)); - /// Constructs a `LockTime` from an nLockTime value or the argument to OP_CHEKCLOCKTIMEVERIFY. + /// Constructs a `LockTime` from an nLockTime value or the argument to `OP_CHEKCLOCKTIMEVERIFY`. /// /// # Examples /// diff --git a/src/opcodes.rs b/src/opcodes.rs index 8ae4490c..ef5cc9ca 100644 --- a/src/opcodes.rs +++ b/src/opcodes.rs @@ -198,7 +198,7 @@ pub mod all { pub const OP_PUSHDATA4: All = All {code: 0x4e}; /// Push the array `[0x81]` onto the stack pub const OP_PUSHNUM_NEG1: All = All {code: 0x4f}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RESERVED: All = All {code: 0x50}; /// Push the array `[0x01]` onto the stack pub const OP_PUSHNUM_1: All = All {code: 0x51}; @@ -234,7 +234,7 @@ pub mod all { pub const OP_PUSHNUM_16: All = All {code: 0x60}; /// Does nothing pub const OP_NOP: All = All {code: 0x61}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_VER: All = All {code: 0x62}; /// Pop and execute the next statements if a nonzero element was popped pub const OP_IF: All = All {code: 0x63}; @@ -244,8 +244,8 @@ pub mod all { pub const OP_VERIF: All = All {code: 0x65}; /// Fail the script unconditionally, does not even need to be executed pub const OP_VERNOTIF: All = All {code: 0x66}; - /// Execute statements if those after the previous OP_IF were not, and vice-versa. - /// If there is no previous OP_IF, this acts as a RETURN. + /// Execute statements if those after the previous `OP_IF` were not, and vice-versa. + /// If there is no previous `OP_IF`, this acts as a RETURN. pub const OP_ELSE: All = All {code: 0x67}; /// Pop and execute the next statements if a zero element was popped pub const OP_ENDIF: All = All {code: 0x68}; @@ -264,10 +264,10 @@ pub mod all { /// Duplicates the two three stack items as ABC -> ABCABC pub const OP_3DUP: All = All {code: 0x6f}; /// Copies the two stack items of items two spaces back to - /// the front, as xxAB -> ABxxAB + /// the front, as xxAB -> `ABxxAB` pub const OP_2OVER: All = All {code: 0x70}; /// Moves the two stack items four spaces back to the front, - /// as xxxxAB -> ABxxxx + /// as xxxxAB -> `ABxxxx` pub const OP_2ROT: All = All {code: 0x71}; /// Swaps the top two pairs, as ABCD -> CDAB pub const OP_2SWAP: All = All {code: 0x72}; @@ -281,7 +281,7 @@ pub mod all { pub const OP_DUP: All = All {code: 0x76}; /// Drops the second-to-top stack item pub const OP_NIP: All = All {code: 0x77}; - /// Copies the second-to-top stack item, as xA -> AxA + /// Copies the second-to-top stack item, as xA -> `AxA` pub const OP_OVER: All = All {code: 0x78}; /// Pop the top stack element as N. Copy the Nth stack element to the top pub const OP_PICK: All = All {code: 0x79}; @@ -315,9 +315,9 @@ pub mod all { pub const OP_EQUAL: All = All {code: 0x87}; /// Returns success if the inputs are exactly equal, failure otherwise pub const OP_EQUALVERIFY: All = All {code: 0x88}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RESERVED1: All = All {code: 0x89}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RESERVED2: All = All {code: 0x8a}; /// Increment the top stack element in place pub const OP_1ADD: All = All {code: 0x8b}; @@ -415,19 +415,19 @@ pub mod all { /// Does nothing pub const OP_NOP10: All = All {code: 0xb9}; // Every other opcode acts as OP_RETURN - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_CHECKSIGADD: All = All {code: 0xba}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_187: All = All {code: 0xbb}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_188: All = All {code: 0xbc}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_189: All = All {code: 0xbd}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_190: All = All {code: 0xbe}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_191: All = All {code: 0xbf}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_192: All = All {code: 0xc0}; /// Check a signature on a given hash with a given public key pub const OP_CHECKSIGFROMSTACK: All = All {code: 0xc1}; @@ -447,20 +447,20 @@ pub mod all { /// and finally pushes a SHA256 hash value after adding the bytestring /// and completing the padding pub const OP_SHA256FINALIZE: All = All {code: 0xc6}; - /// Pop a CScriptNum input index idx and push the outpoint as a tuple. + /// Pop a `CScriptNum` input index idx and push the outpoint as a tuple. /// - /// First push the txid(32) of the prev_out, followed by a 4 byte push of - /// vout followed by a push for the outpoint_flag(1) + /// First push the txid(32) of the `prev_out`, followed by a 4 byte push of + /// vout followed by a push for the `outpoint_flag(1)` pub const OP_INSPECTINPUTOUTPOINT: All = All {code: 0xc7}; - /// Pop a CScriptNum input index idx and push the nAsset onto the stack as two elements. + /// Pop a `CScriptNum` input index idx and push the nAsset onto the stack as two elements. /// /// The first push the assetID(32), followed by the prefix(1) pub const OP_INSPECTINPUTASSET: All = All {code: 0xc8}; - /// Pop a CScriptNum input index idx and push the nValue as a tuple, + /// Pop a `CScriptNum` input index idx and push the nValue as a tuple, /// /// value(8 byte LE, 32) followed by prefix(1), pub const OP_INSPECTINPUTVALUE: All = All {code: 0xc9}; - /// Pop a CScriptNum input index idx and push the following depending the type of scriptPubkey: + /// Pop a `CScriptNum` input index idx and push the following depending the type of scriptPubkey: /// /// - If the scriptPubKey is not a native segwit program, push a single sha256 /// hash of the scriptPubKey on stack top. Next, push a CScriptNum(-1) to @@ -468,52 +468,52 @@ pub mod all { /// - If the scriptPubKey is a native segwit program, push the witness program(2-40) /// followed by a push for segwit version(0-1). pub const OP_INSPECTINPUTSCRIPTPUBKEY: All = All {code: 0xca}; - /// Pop a CScriptNum input index idx and push the nSequence(4) as little-endian number. + /// Pop a `CScriptNum` input index idx and push the nSequence(4) as little-endian number. pub const OP_INSPECTINPUTSEQUENCE: All = All {code: 0xcb}; - /// Pop a CScriptNum input index idx and push the assetIssuance information if the asset has issuance, + /// Pop a `CScriptNum` input index idx and push the assetIssuance information if the asset has issuance, /// otherwise push an empty vector. /// /// Refer to the [spec](https://github.com/ElementsProject/elements/blob/master/doc/tapscript_opcodes.md) /// for details pub const OP_INSPECTINPUTISSUANCE: All = All {code: 0xcc}; - /// Pushes the current input index as CScriptNum. This can be used in conjunction with + /// Pushes the current input index as `CScriptNum`. This can be used in conjunction with /// input introspection opcodes for inspecting current input. pub const OP_PUSHCURRENTINPUTINDEX: All = All {code: 0xcd}; - /// Pop a CScriptNum input index idx and push the nAsset as a tuple, + /// Pop a `CScriptNum` input index idx and push the nAsset as a tuple, /// first push the assetID(32), followed by the prefix(1) pub const OP_INSPECTOUTPUTASSET: All = All {code: 0xce}; - /// Pop a CScriptNum input index idx and push the nValue as a tuple, + /// Pop a `CScriptNum` input index idx and push the nValue as a tuple, /// value(8 byte LE, 32) followed by prefix pub const OP_INSPECTOUTPUTVALUE: All = All {code: 0xcf}; - /// Pop a CScriptNum input index idx and push the nNonce(33) onto the stack. + /// Pop a `CScriptNum` input index idx and push the nNonce(33) onto the stack. /// If the nonce is null, push an empty vector onto the stack pub const OP_INSPECTOUTPUTNONCE: All = All {code: 0xd0}; - /// Pop a CScriptNum input index idx and push the scriptPubkey onto the stack. + /// Pop a `CScriptNum` input index idx and push the scriptPubkey onto the stack. /// Similar to [`OP_INSPECTINPUTSCRIPTPUBKEY`], for this output. pub const OP_INSPECTOUTPUTSCRIPTPUBKEY: All = All {code: 0xd1}; /// Push the nVersion(4) as little-endian. pub const OP_INSPECTVERSION: All = All {code: 0xd2}; /// Push the nLockTime(4) as little-endian. pub const OP_INSPECTLOCKTIME: All = All {code: 0xd3}; - /// Push the number of inputs as CScriptNum + /// Push the number of inputs as `CScriptNum` pub const OP_INSPECTNUMINPUTS: All = All {code: 0xd4}; - /// Push the number of outputs as CScriptNum + /// Push the number of outputs as `CScriptNum` pub const OP_INSPECTNUMOUTPUTS: All = All {code: 0xd5}; /// Push the transaction weight (8) as little-endian pub const OP_TXWEIGHT: All = All {code: 0xd6}; /// Pop the first number(8 byte LE) as b followed another pop for a(8 byte LE). /// - /// Push a + b onto the stack. Push 1 CScriptNum if there is no overflow. + /// Push a + b onto the stack. Push 1 `CScriptNum` if there is no overflow. /// Refer to the spec for details when dealing with overflow. pub const OP_ADD64: All = All {code: 0xd7}; /// Pop the first number(8 byte LE) as b followed another pop for a(8 byte LE). /// - /// Push a - b onto the stack. Push 1 CScriptNum if there is no overflow. + /// Push a - b onto the stack. Push 1 `CScriptNum` if there is no overflow. /// Refer to the spec for details when dealing with overflow. pub const OP_SUB64: All = All {code: 0xd8}; /// Pop the first number(8 byte LE) as b followed another pop for a(8 byte LE). /// - /// Push a*b onto the stack. Push 1 CScriptNum if there is no overflow. + /// Push a*b onto the stack. Push 1 `CScriptNum` if there is no overflow. /// Refer to the spec for details when dealing with overflow. pub const OP_MUL64: All = All {code: 0xd9}; /// Pop the first number(8 byte LE) as b followed another pop for a(8 byte LE). @@ -522,12 +522,12 @@ pub mod all { /// stack followed by quotient(a//b) onto the stack. /// /// If b==0 or a = -263 && b = -1, treat as overflow. - /// Push 1 CScriptNum if there is no overflow. + /// Push 1 `CScriptNum` if there is no overflow. /// Refer to the spec for details when dealing with overflow. pub const OP_DIV64: All = All {code: 0xda}; /// Pop the first number(8 byte LE) as a and pushes -a on the stack top. /// - /// If the number is -2^63 treat as overflow, otherwise push CScriptNum 1 to indicate no overflow. + /// If the number is -2^63 treat as overflow, otherwise push `CScriptNum` 1 to indicate no overflow. /// Refer to the spec for details when dealing with overflow. pub const OP_NEG64: All = All {code: 0xdb}; /// Pop the first number(8 byte LE) as b followed another pop for a(8 byte LE). Push a < b. @@ -545,9 +545,9 @@ pub mod all { /// Pop the first number(8 byte LE) as b followed another pop for a(8 byte LE). Push a >= b. /// Note that this operation cannot fail pub const OP_GREATERTHANOREQUAL64: All = All {code: 0xdf}; - /// Pop the stack as minimal CScriptNum, push 8 byte signed LE corresponding to that number. + /// Pop the stack as minimal `CScriptNum`, push 8 byte signed LE corresponding to that number. pub const OP_SCRIPTNUMTOLE64: All = All {code: 0xe0}; - /// Pop the stack as a 8 byte signed LE. Convert to CScriptNum and push it, abort on fail. + /// Pop the stack as a 8 byte signed LE. Convert to `CScriptNum` and push it, abort on fail. /// /// Please check the range of the operand before calling the opcode. pub const OP_LE64TOSCRIPTNUM: All = All {code: 0xe1}; @@ -576,57 +576,57 @@ pub mod all { /// /// Abort if Q != P + k*G where G is the generator for secp256k1. pub const OP_TWEAKVERIFY: All = All {code: 0xe4}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_229: All = All {code: 0xe5}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_230: All = All {code: 0xe6}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_231: All = All {code: 0xe7}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_232: All = All {code: 0xe8}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_233: All = All {code: 0xe9}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_234: All = All {code: 0xea}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_235: All = All {code: 0xeb}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_236: All = All {code: 0xec}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_237: All = All {code: 0xed}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_238: All = All {code: 0xee}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_239: All = All {code: 0xef}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_240: All = All {code: 0xf0}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_241: All = All {code: 0xf1}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_242: All = All {code: 0xf2}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_243: All = All {code: 0xf3}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_244: All = All {code: 0xf4}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_245: All = All {code: 0xf5}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_246: All = All {code: 0xf6}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_247: All = All {code: 0xf7}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_248: All = All {code: 0xf8}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_249: All = All {code: 0xf9}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_250: All = All {code: 0xfa}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_251: All = All {code: 0xfb}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_252: All = All {code: 0xfc}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_253: All = All {code: 0xfd}; - /// Synonym for OP_RETURN + /// Synonym for `OP_RETURN` pub const OP_RETURN_254: All = All {code: 0xfe}; /// Invalid opcode pub const OP_INVALIDOPCODE: All = All {code: 0xff}; @@ -881,9 +881,9 @@ impl serde::Serialize for All { pub static OP_FALSE: All = all::OP_PUSHBYTES_0; /// Number 1 is also TRUE pub static OP_TRUE: All = all::OP_PUSHNUM_1; -/// previously called OP_NOP2 +/// previously called `OP_NOP2` pub static OP_NOP2: All = all::OP_CLTV; -/// previously called OP_NOP3 +/// previously called `OP_NOP3` pub static OP_NOP3: All = all::OP_CSV; /// Broad categories of opcodes with similar behavior diff --git a/src/pset/elip100.rs b/src/pset/elip100.rs index 2cc514e4..7b22fe7c 100644 --- a/src/pset/elip100.rs +++ b/src/pset/elip100.rs @@ -44,7 +44,7 @@ impl PartiallySignedTransaction { } /// Get contract information from the PSET, returns None if there are no information regarding - /// the given `asset_id`` in the PSET + /// the given `asset_id` in the PSET pub fn get_asset_metadata( &self, asset_id: AssetId, @@ -72,7 +72,7 @@ impl PartiallySignedTransaction { } /// Get token information from the PSET, returns None if there are no information regarding - /// the given `token_id`` in the PSET + /// the given `token_id` in the PSET pub fn get_token_metadata( &self, token_id: AssetId @@ -171,7 +171,7 @@ impl TokenMetadata { Self { asset_id, issuance_blinded } } - /// Returns the asset_id + /// Returns the `asset_id` pub fn asset_id(&self) -> &AssetId { &self.asset_id } diff --git a/src/pset/elip102.rs b/src/pset/elip102.rs index 295c69ef..c1b0df1e 100644 --- a/src/pset/elip102.rs +++ b/src/pset/elip102.rs @@ -2,7 +2,7 @@ //! An implementation of ELIP0102 as defined in //! //! -//! ELIP0102 defines how to encode the extra data for LiquiDEX in a PSET. +//! ELIP0102 defines how to encode the extra data for `LiquiDEX` in a PSET. //! use crate::pset::{ @@ -19,7 +19,7 @@ pub const PSBT_ELEMENTS_LIQUIDEX_IN_ABF: u8 = 0x00u8; /// Output Asset Blinding Factor keytype as defined in ELIP0102 pub const PSBT_ELEMENTS_LIQUIDEX_OUT_ABF: u8 = 0x00u8; -/// Prefix for PSET LiquiDEX extension as defined in ELIP0102 +/// Prefix for PSET `LiquiDEX` extension as defined in ELIP0102 pub const PSET_LIQUIDEX_PREFIX: &[u8] = b"pset_liquidex"; fn prop_key(keytype: u8) -> ProprietaryKey { @@ -30,7 +30,7 @@ fn prop_key(keytype: u8) -> ProprietaryKey { } } -/// ELIP0102 LiquiDEX extensions +/// ELIP0102 `LiquiDEX` extensions impl Input { /// Set Asset Blinding Factor pub fn set_abf(&mut self, abf: AssetBlindingFactor) { @@ -47,7 +47,7 @@ impl Input { } } -/// ELIP0102 LiquiDEX extensions +/// ELIP0102 `LiquiDEX` extensions impl Output { /// Set Asset Blinding Factor pub fn set_abf(&mut self, abf: AssetBlindingFactor) { diff --git a/src/pset/error.rs b/src/pset/error.rs index de180750..0cce0c61 100644 --- a/src/pset/error.rs +++ b/src/pset/error.rs @@ -66,7 +66,7 @@ pub enum Error { }, /// Unable to parse as a standard Sighash type. NonStandardSighashType(u32), - /// Parsing errors from bitcoin_hashes + /// Parsing errors from `bitcoin_hashes` HashParseError(hashes::FromSliceError), /// The pre-image must hash to the corresponding pset hash InvalidPreimageHashPair { @@ -232,9 +232,9 @@ impl From for Error { /// Ways that blinding a Partially Signed Transaction might fail. #[derive(Clone, PartialEq, Eq, Debug)] pub enum PsetBlindError { - /// Input TxOut len mismatch + /// Input `TxOut` len mismatch InputTxOutSecretLen, - /// Output TxOut len mismatch + /// Output `TxOut` len mismatch OutputTxOutSecretLen, /// Blinder index out of range BlinderIndexOutOfBounds(usize, usize), diff --git a/src/pset/map/global.rs b/src/pset/map/global.rs index 7daf72a1..acdec446 100644 --- a/src/pset/map/global.rs +++ b/src/pset/map/global.rs @@ -31,23 +31,23 @@ use secp256k1_zkp::Tweak; // (Not used in pset) Type: Unsigned Transaction PSET_GLOBAL_UNSIGNED_TX = 0x00 const PSET_GLOBAL_UNSIGNED_TX: u8 = 0x00; // -/// Type: Extended Public Key PSET_GLOBAL_XPUB = 0x01 +/// Type: Extended Public Key `PSET_GLOBAL_XPUB` = 0x01 const PSET_GLOBAL_XPUB: u8 = 0x01; -/// Type: Tx Version PSET_GLOBAL_TX_VERSION = 0x02 +/// Type: Tx Version `PSET_GLOBAL_TX_VERSION` = 0x02 const PSET_GLOBAL_TX_VERSION: u8 = 0x02; -/// Type: Fallback Locktime PSET_GLOBAL_FALLBACK_LOCKTIME = 0x03 +/// Type: Fallback Locktime `PSET_GLOBAL_FALLBACK_LOCKTIME` = 0x03 const PSET_GLOBAL_FALLBACK_LOCKTIME: u8 = 0x03; -/// Type: Tx Input Count PSET_GLOBAL_INPUT_COUNT = 0x04 +/// Type: Tx Input Count `PSET_GLOBAL_INPUT_COUNT` = 0x04 const PSET_GLOBAL_INPUT_COUNT: u8 = 0x04; -/// Type: Tx Output Count PSET_GLOBAL_OUTPUT_COUNT = 0x05 +/// Type: Tx Output Count `PSET_GLOBAL_OUTPUT_COUNT` = 0x05 const PSET_GLOBAL_OUTPUT_COUNT: u8 = 0x05; -/// Type: Transaction Modifiable Flags PSET_GLOBAL_TX_MODIFIABLE = 0x06 +/// Type: Transaction Modifiable Flags `PSET_GLOBAL_TX_MODIFIABLE` = 0x06 const PSET_GLOBAL_TX_MODIFIABLE: u8 = 0x06; -/// Type: Version Number PSET_GLOBAL_VERSION = 0xFB +/// Type: Version Number `PSET_GLOBAL_VERSION` = 0xFB const PSET_GLOBAL_VERSION: u8 = 0xFB; -/// Type: Proprietary Use Type PSET_GLOBAL_PROPRIETARY = 0xFC +/// Type: Proprietary Use Type `PSET_GLOBAL_PROPRIETARY` = 0xFC const PSET_GLOBAL_PROPRIETARY: u8 = 0xFC; /// Proprietary fields in elements diff --git a/src/pset/map/input.rs b/src/pset/map/input.rs index cd351a18..3e2bf74b 100644 --- a/src/pset/map/input.rs +++ b/src/pset/map/input.rs @@ -38,64 +38,64 @@ use secp256k1_zkp::{self, RangeProof, SurjectionProof, Tweak, ZERO_TWEAK}; use crate::{OutPoint, Sequence}; -/// Type: Non-Witness UTXO PSET_IN_NON_WITNESS_UTXO = 0x00 +/// Type: Non-Witness UTXO `PSET_IN_NON_WITNESS_UTXO` = 0x00 const PSET_IN_NON_WITNESS_UTXO: u8 = 0x00; -/// Type: Witness UTXO PSET_IN_WITNESS_UTXO = 0x01 +/// Type: Witness UTXO `PSET_IN_WITNESS_UTXO` = 0x01 const PSET_IN_WITNESS_UTXO: u8 = 0x01; -/// Type: Partial Signature PSET_IN_PARTIAL_SIG = 0x02 +/// Type: Partial Signature `PSET_IN_PARTIAL_SIG` = 0x02 const PSET_IN_PARTIAL_SIG: u8 = 0x02; -/// Type: Sighash Type PSET_IN_SIGHASH_TYPE = 0x03 +/// Type: Sighash Type `PSET_IN_SIGHASH_TYPE` = 0x03 const PSET_IN_SIGHASH_TYPE: u8 = 0x03; -/// Type: Redeem Script PSET_IN_REDEEM_SCRIPT = 0x04 +/// Type: Redeem Script `PSET_IN_REDEEM_SCRIPT` = 0x04 const PSET_IN_REDEEM_SCRIPT: u8 = 0x04; -/// Type: Witness Script PSET_IN_WITNESS_SCRIPT = 0x05 +/// Type: Witness Script `PSET_IN_WITNESS_SCRIPT` = 0x05 const PSET_IN_WITNESS_SCRIPT: u8 = 0x05; -/// Type: BIP 32 Derivation Path PSET_IN_BIP32_DERIVATION = 0x06 +/// Type: BIP 32 Derivation Path `PSET_IN_BIP32_DERIVATION` = 0x06 const PSET_IN_BIP32_DERIVATION: u8 = 0x06; -/// Type: Finalized scriptSig PSET_IN_FINAL_SCRIPTSIG = 0x07 +/// Type: Finalized scriptSig `PSET_IN_FINAL_SCRIPTSIG` = 0x07 const PSET_IN_FINAL_SCRIPTSIG: u8 = 0x07; -/// Type: Finalized scriptWitness PSET_IN_FINAL_SCRIPTWITNESS = 0x08 +/// Type: Finalized scriptWitness `PSET_IN_FINAL_SCRIPTWITNESS` = 0x08 const PSET_IN_FINAL_SCRIPTWITNESS: u8 = 0x08; -/// Type: RIPEMD160 preimage PSET_IN_RIPEMD160 = 0x0a +/// Type: RIPEMD160 preimage `PSET_IN_RIPEMD160` = 0x0a const PSET_IN_RIPEMD160: u8 = 0x0a; -/// Type: SHA256 preimage PSET_IN_SHA256 = 0x0b +/// Type: SHA256 preimage `PSET_IN_SHA256` = 0x0b const PSET_IN_SHA256: u8 = 0x0b; -/// Type: HASH160 preimage PSET_IN_HASH160 = 0x0c +/// Type: HASH160 preimage `PSET_IN_HASH160` = 0x0c const PSET_IN_HASH160: u8 = 0x0c; -/// Type: HASH256 preimage PSET_IN_HASH256 = 0x0d +/// Type: HASH256 preimage `PSET_IN_HASH256` = 0x0d const PSET_IN_HASH256: u8 = 0x0d; -/// Type: (Mandatory) Previous TXID PSET_IN_PREVIOUS_TXID = 0x0e +/// Type: (Mandatory) Previous TXID `PSET_IN_PREVIOUS_TXID` = 0x0e const PSET_IN_PREVIOUS_TXID: u8 = 0x0e; -/// Type: (Mandatory) Spent Output Index PSET_IN_OUTPUT_INDEX = 0x0f +/// Type: (Mandatory) Spent Output Index `PSET_IN_OUTPUT_INDEX` = 0x0f const PSET_IN_OUTPUT_INDEX: u8 = 0x0f; -/// Type: Sequence Number PSET_IN_SEQUENCE = 0x10 +/// Type: Sequence Number `PSET_IN_SEQUENCE` = 0x10 const PSET_IN_SEQUENCE: u8 = 0x10; -/// Type: Required Time-based Locktime PSET_IN_REQUIRED_TIME_LOCKTIME = 0x11 +/// Type: Required Time-based Locktime `PSET_IN_REQUIRED_TIME_LOCKTIME` = 0x11 const PSET_IN_REQUIRED_TIME_LOCKTIME: u8 = 0x11; -/// Type: Required Height-based Locktime PSET_IN_REQUIRED_HEIGHT_LOCKTIME = 0x12 +/// Type: Required Height-based Locktime `PSET_IN_REQUIRED_HEIGHT_LOCKTIME` = 0x12 const PSET_IN_REQUIRED_HEIGHT_LOCKTIME: u8 = 0x12; -/// Type: Schnorr Signature in Key Spend PSBT_IN_TAP_KEY_SIG = 0x13 +/// Type: Schnorr Signature in Key Spend `PSBT_IN_TAP_KEY_SIG` = 0x13 const PSBT_IN_TAP_KEY_SIG: u8 = 0x13; -/// Type: Schnorr Signature in Script Spend PSBT_IN_TAP_SCRIPT_SIG = 0x14 +/// Type: Schnorr Signature in Script Spend `PSBT_IN_TAP_SCRIPT_SIG` = 0x14 const PSBT_IN_TAP_SCRIPT_SIG: u8 = 0x14; -/// Type: Taproot Leaf Script PSBT_IN_TAP_LEAF_SCRIPT = 0x14 +/// Type: Taproot Leaf Script `PSBT_IN_TAP_LEAF_SCRIPT` = 0x14 const PSBT_IN_TAP_LEAF_SCRIPT: u8 = 0x15; -/// Type: Taproot Key BIP 32 Derivation Path PSBT_IN_TAP_BIP32_DERIVATION = 0x16 +/// Type: Taproot Key BIP 32 Derivation Path `PSBT_IN_TAP_BIP32_DERIVATION` = 0x16 const PSBT_IN_TAP_BIP32_DERIVATION: u8 = 0x16; -/// Type: Taproot Internal Key PSBT_IN_TAP_INTERNAL_KEY = 0x17 +/// Type: Taproot Internal Key `PSBT_IN_TAP_INTERNAL_KEY` = 0x17 const PSBT_IN_TAP_INTERNAL_KEY: u8 = 0x17; -/// Type: Taproot Merkle Root PSBT_IN_TAP_MERKLE_ROOT = 0x18 +/// Type: Taproot Merkle Root `PSBT_IN_TAP_MERKLE_ROOT` = 0x18 const PSBT_IN_TAP_MERKLE_ROOT: u8 = 0x18; -/// Type: Proprietary Use Type PSET_IN_PROPRIETARY = 0xFC +/// Type: Proprietary Use Type `PSET_IN_PROPRIETARY` = 0xFC const PSET_IN_PROPRIETARY: u8 = 0xFC; // Elements Proprietary types: /// Issuance Value: The explicit little endian 64-bit integer /// for the value of this issuance. This is mutually exclusive with -/// PSBT_ELEMENTS_IN_ISSUANCE_VALUE_COMMITMENT +/// `PSBT_ELEMENTS_IN_ISSUANCE_VALUE_COMMITMENT` const PSBT_ELEMENTS_IN_ISSUANCE_VALUE: u8 = 0x00; /// Issuance Value Commitment: The 33 byte Value Commitment. -/// This is mutually exclusive with PSBT_IN_ISSUANCE_VALUE. +/// This is mutually exclusive with `PSBT_IN_ISSUANCE_VALUE`. const PSBT_ELEMENTS_IN_ISSUANCE_VALUE_COMMITMENT: u8 = 0x01; /// Issuance Value Rangeproof: The rangeproof const PSBT_ELEMENTS_IN_ISSUANCE_VALUE_RANGEPROOF: u8 = 0x02; @@ -117,11 +117,11 @@ const PSBT_ELEMENTS_IN_PEG_IN_VALUE: u8 = 0x08; const PSBT_ELEMENTS_IN_PEG_IN_WITNESS: u8 = 0x09; /// Issuance Inflation Keys Amount: The value for the inflation keys output to /// set in this issuance. This is mutually exclusive with -/// PSBT_ELEMENTS_IN_ISSUANCE_INFLATION_KEYS_COMMITMENT. +/// `PSBT_ELEMENTS_IN_ISSUANCE_INFLATION_KEYS_COMMITMENT`. const PSBT_ELEMENTS_IN_ISSUANCE_INFLATION_KEYS: u8 = 0x0a; /// Issuance Inflation Keys Amount Commitment: The 33 byte commitment to the /// inflation keys output value in this issuance. This is mutually exclusive -/// with PSBT_ELEMENTS_IN_ISSUANCE_INFLATION_KEYS +/// with `PSBT_ELEMENTS_IN_ISSUANCE_INFLATION_KEYS` const PSBT_ELEMENTS_IN_ISSUANCE_INFLATION_KEYS_COMMITMENT: u8 = 0x0b; /// Issuance Blinding Nonce: The 32 byte asset blinding nonce. For new assets, /// must be 0. For reissuances, this is a revelation of the blinding factor for @@ -139,29 +139,29 @@ const PSBT_ELEMENTS_IN_ISSUANCE_ASSET_ENTROPY: u8 = 0x0d; /// the blinding factors for the UTXOs that they are involved in. const PSBT_ELEMENTS_IN_UTXO_RANGEPROOF: u8 = 0x0e; /// An explicit value rangeproof that proves that the value commitment in -/// PSBT_ELEMENTS_IN_ISSUANCE_VALUE_COMMITMENT matches the explicit value in -/// PSBT_ELEMENTS_IN_ISSUANCE_VALUE. If provided, PSBT_ELEMENTS_IN_ISSUANCE_VALUE_COMMITMENT +/// `PSBT_ELEMENTS_IN_ISSUANCE_VALUE_COMMITMENT` matches the explicit value in +/// `PSBT_ELEMENTS_IN_ISSUANCE_VALUE`. If provided, `PSBT_ELEMENTS_IN_ISSUANCE_VALUE_COMMITMENT` /// must be provided too. const PSBT_ELEMENTS_IN_ISSUANCE_BLIND_VALUE_PROOF: u8 = 0x0f; /// An explicit value rangeproof that proves that the value commitment in -/// PSBT_ELEMENTS_IN_ISSUANCE_INFLATION_KEYS_COMMITMENT matches the explicit value -/// in PSBT_ELEMENTS_IN_ISSUANCE_INFLATION_KEYS. If provided, -/// PSBT_ELEMENTS_IN_ISSUANCE_INFLATION_KEYS_COMMITMENT must be provided too. +/// `PSBT_ELEMENTS_IN_ISSUANCE_INFLATION_KEYS_COMMITMENT` matches the explicit value +/// in `PSBT_ELEMENTS_IN_ISSUANCE_INFLATION_KEYS`. If provided, +/// `PSBT_ELEMENTS_IN_ISSUANCE_INFLATION_KEYS_COMMITMENT` must be provided too. const PSBT_ELEMENTS_IN_ISSUANCE_BLIND_INFLATION_KEYS_PROOF: u8 = 0x10; /// The explicit value for the input being spent. If provided, -/// PSBT_ELEMENTS_IN_VALUE_PROOF must be provided too. +/// `PSBT_ELEMENTS_IN_VALUE_PROOF` must be provided too. const PSBT_ELEMENTS_IN_EXPLICIT_VALUE: u8 = 0x11; /// An explicit value rangeproof that proves that the value commitment in this -/// input's UTXO matches the explicit value in PSBT_ELEMENTS_IN_EXPLICIT_VALUE. -/// If provided, PSBT_ELEMENTS_IN_EXPLICIT_VALUE must be provided too. +/// input's UTXO matches the explicit value in `PSBT_ELEMENTS_IN_EXPLICIT_VALUE`. +/// If provided, `PSBT_ELEMENTS_IN_EXPLICIT_VALUE` must be provided too. const PSBT_ELEMENTS_IN_VALUE_PROOF: u8 = 0x12; /// The explicit asset for the input being spent. If provided, -/// PSBT_ELEMENTS_IN_ASSET_PROOF must be provided too. +/// `PSBT_ELEMENTS_IN_ASSET_PROOF` must be provided too. const PSBT_ELEMENTS_IN_EXPLICIT_ASSET: u8 = 0x13; /// An asset surjection proof with this input's asset as the only asset in the /// input set in order to prove that the asset commitment in the UTXO matches -/// the explicit asset in PSBT_ELEMENTS_IN_EXPLICIT_ASSET. If provided, -/// PSBT_ELEMENTS_IN_EXPLICIT_ASSET must be provided too. +/// the explicit asset in `PSBT_ELEMENTS_IN_EXPLICIT_ASSET`. If provided, +/// `PSBT_ELEMENTS_IN_EXPLICIT_ASSET` must be provided too. const PSBT_ELEMENTS_IN_ASSET_PROOF: u8 = 0x14; /// A boolean flag. 0x00 indicates the issuance should not be blinded, /// 0x01 indicates it should be. If not specified, assumed to be 0x01. @@ -174,11 +174,11 @@ const PSBT_ELEMENTS_IN_BLINDED_ISSUANCE: u8 = 0x15; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(crate = "actual_serde"))] pub struct Input { /// The non-witness transaction this input spends from. Should only be - /// [std::option::Option::Some] for inputs which spend non-segwit outputs or + /// [`std::option::Option::Some`] for inputs which spend non-segwit outputs or /// if it is unknown whether an input spends a segwit output. pub non_witness_utxo: Option, /// The transaction output this input spends from. Should only be - /// [std::option::Option::Some] for inputs which spend segwit outputs, + /// [`std::option::Option::Some`] for inputs which spend segwit outputs, /// including P2SH embedded ones. pub witness_utxo: Option, /// A map from public keys to their corresponding signature as would be @@ -264,7 +264,7 @@ pub struct Input { pub issuance_value_rangeproof: Option>, /// Issuance keys rangeproof pub issuance_keys_rangeproof: Option>, - /// Pegin Transaction. Should be a bitcoin::Transaction + /// Pegin Transaction. Should be a `bitcoin::Transaction` pub pegin_tx: Option, /// Pegin Transaction proof // TODO: Look for Merkle proof structs @@ -505,7 +505,7 @@ impl Input { } } - /// Create a pset input from TxIn + /// Create a pset input from `TxIn` pub fn from_txin(txin: TxIn) -> Self { let mut ret = Self::from_prevout(txin.previous_output); let has_issuance = txin.has_issuance(); @@ -542,7 +542,7 @@ impl Input { } /// Compute the issuance asset ids from pset. This function does not check - /// whether there is an issuance in this input. Returns (asset_id, token_id) + /// whether there is an issuance in this input. Returns (`asset_id`, `token_id`) pub fn issuance_ids(&self) -> (AssetId, AssetId) { let issue_nonce = self.issuance_blinding_nonce.unwrap_or(ZERO_TWEAK); let entropy = if issue_nonce == ZERO_TWEAK { diff --git a/src/pset/map/output.rs b/src/pset/map/output.rs index c636571a..b6470258 100644 --- a/src/pset/map/output.rs +++ b/src/pset/map/output.rs @@ -33,34 +33,34 @@ use crate::issuance; use crate::AssetId; use crate::TxOut; -/// Type: Redeem Script PSET_OUT_REDEEM_SCRIPT = 0x00 +/// Type: Redeem Script `PSET_OUT_REDEEM_SCRIPT` = 0x00 const PSET_OUT_REDEEM_SCRIPT: u8 = 0x00; -/// Type: Witness Script PSET_OUT_WITNESS_SCRIPT = 0x01 +/// Type: Witness Script `PSET_OUT_WITNESS_SCRIPT` = 0x01 const PSET_OUT_WITNESS_SCRIPT: u8 = 0x01; -/// Type: BIP 32 Derivation Path PSET_OUT_BIP32_DERIVATION = 0x02 +/// Type: BIP 32 Derivation Path `PSET_OUT_BIP32_DERIVATION` = 0x02 const PSET_OUT_BIP32_DERIVATION: u8 = 0x02; -/// Type: Output Amount PSET_OUT_AMOUNT = 0x03 +/// Type: Output Amount `PSET_OUT_AMOUNT` = 0x03 const PSET_OUT_AMOUNT: u8 = 0x03; -/// Type: Output Script PSET_OUT_SCRIPT = 0x04 +/// Type: Output Script `PSET_OUT_SCRIPT` = 0x04 const PSET_OUT_SCRIPT: u8 = 0x04; -/// Type: Taproot Internal Key PSBT_OUT_TAP_INTERNAL_KEY = 0x05 +/// Type: Taproot Internal Key `PSBT_OUT_TAP_INTERNAL_KEY` = 0x05 const PSBT_OUT_TAP_INTERNAL_KEY: u8 = 0x05; -/// Type: Taproot Tree PSBT_OUT_TAP_TREE = 0x06 +/// Type: Taproot Tree `PSBT_OUT_TAP_TREE` = 0x06 const PSBT_OUT_TAP_TREE: u8 = 0x06; -/// Type: Taproot Key BIP 32 Derivation Path PSBT_OUT_TAP_BIP32_DERIVATION = 0x07 +/// Type: Taproot Key BIP 32 Derivation Path `PSBT_OUT_TAP_BIP32_DERIVATION` = 0x07 const PSBT_OUT_TAP_BIP32_DERIVATION: u8 = 0x07; -/// Type: Proprietary Use Type PSET_IN_PROPRIETARY = 0xFC +/// Type: Proprietary Use Type `PSET_IN_PROPRIETARY` = 0xFC const PSET_OUT_PROPRIETARY: u8 = 0xFC; /// Elements /// The 33 byte Value Commitment for this output. This is mutually -/// exclusive with PSBT_OUT_VALUE. +/// exclusive with `PSBT_OUT_VALUE`. const PSBT_ELEMENTS_OUT_VALUE_COMMITMENT: u8 = 0x01; /// The explicit 32 byte asset tag for this output. This is mutually -/// exclusive with PSBT_ELEMENTS_OUT_ASSET_COMMITMENT. +/// exclusive with `PSBT_ELEMENTS_OUT_ASSET_COMMITMENT`. const PSBT_ELEMENTS_OUT_ASSET: u8 = 0x02; /// The 33 byte Asset Commitment for this output. This is mutually -/// exclusive with PSBT_ELEMENTS_OUT_ASSET. +/// exclusive with `PSBT_ELEMENTS_OUT_ASSET`. const PSBT_ELEMENTS_OUT_ASSET_COMMITMENT: u8 = 0x03; /// The rangeproof for the value of this output. const PSBT_ELEMENTS_OUT_VALUE_RANGEPROOF: u8 = 0x04; @@ -74,13 +74,13 @@ const PSBT_ELEMENTS_OUT_ECDH_PUBKEY: u8 = 0x07; /// whose owner should blind this output. const PSBT_ELEMENTS_OUT_BLINDER_INDEX: u8 = 0x08; /// An explicit value rangeproof that proves that the value commitment in -/// PSBT_ELEMENTS_OUT_VALUE_COMMITMENT matches the explicit value in PSBT_OUT_VALUE. -/// If provided, PSBT_ELEMENTS_OUT_VALUE_COMMITMENT must be provided too. +/// `PSBT_ELEMENTS_OUT_VALUE_COMMITMENT` matches the explicit value in `PSBT_OUT_VALUE`. +/// If provided, `PSBT_ELEMENTS_OUT_VALUE_COMMITMENT` must be provided too. const PSBT_ELEMENTS_OUT_BLIND_VALUE_PROOF: u8 = 0x09; /// An asset surjection proof with this output's asset as the only asset in the /// input set in order to prove that the asset commitment in -/// PSBT_ELEMENTS_OUT_ASSET_COMMITMENT matches the explicit asset in -/// PSBT_ELEMENTS_OUT_ASSET. If provided, PSBT_ELEMENTS_OUT_ASSET_COMMITMENT must +/// `PSBT_ELEMENTS_OUT_ASSET_COMMITMENT` matches the explicit asset in +/// `PSBT_ELEMENTS_OUT_ASSET`. If provided, `PSBT_ELEMENTS_OUT_ASSET_COMMITMENT` must /// be provided too. const PSBT_ELEMENTS_OUT_BLIND_ASSET_PROOF: u8 = 0x0a; @@ -204,7 +204,7 @@ impl Output { } /// Create a output from txout - /// If the txout it [TxOut::is_partially_blinded], then nonce of the txout + /// If the txout it [`TxOut::is_partially_blinded`], then nonce of the txout /// is treated as ecdh pubkey, otherwise the nonce of the txout is assumed to /// be receiver blinding key. /// This is to be used when the txout is not blinded. This sets @@ -267,13 +267,13 @@ impl Output { } } - /// IsBlinded from elements core + /// `IsBlinded` from elements core /// This indicates whether the output is marked for blinding pub fn is_marked_for_blinding(&self) -> bool { self.blinding_key.is_some() } - /// IsPartiallyBlinded from elements core + /// `IsPartiallyBlinded` from elements core pub fn is_partially_blinded(&self) -> bool { self.is_marked_for_blinding() && (self.amount_comm.is_some() @@ -283,7 +283,7 @@ impl Output { || self.ecdh_pubkey.is_some()) } - /// IsFullyBlinded from elements core + /// `IsFullyBlinded` from elements core pub fn is_fully_blinded(&self) -> bool { self.is_marked_for_blinding() && self.amount_comm.is_some() diff --git a/src/pset/mod.rs b/src/pset/mod.rs index 9f5e8f67..f2d8cec0 100644 --- a/src/pset/mod.rs +++ b/src/pset/mod.rs @@ -96,7 +96,7 @@ impl PartiallySignedTransaction { .collect(); Self { global, inputs, outputs } } - /// Create a PartiallySignedTransaction with zero inputs + /// Create a `PartiallySignedTransaction` with zero inputs /// zero outputs with a version 2 and tx version 2 pub fn new_v2() -> Self { PartiallySignedTransaction { @@ -274,7 +274,7 @@ impl PartiallySignedTransaction { } } - /// Extract the Transaction from a PartiallySignedTransaction by filling in + /// Extract the Transaction from a `PartiallySignedTransaction` by filling in /// the available signature information in place. pub fn extract_tx(&self) -> Result { // This should never trigger any error, should be panic here? @@ -463,8 +463,8 @@ impl PartiallySignedTransaction { /// should call the `blind_last` function which balances the blinding factors /// `inp_secrets` and must be consistent by [`Output`] `blinder_index` field /// For each output that is to be blinded, the following must be true - /// 1. The blinder_index must be set in pset output field - /// 2. the corresponding inp_secrets\[out.blinder_index\] must be present + /// 1. The `blinder_index` must be set in pset output field + /// 2. the corresponding `inp_secrets`\[`out.blinder_index`\] must be present /// /// Issuances and re-issuance inputs are not blinded. /// # Parameters @@ -569,7 +569,7 @@ impl PartiallySignedTransaction { /// This function balances the blinding factors with partial information about /// blinding inputs and scalars from [`Global`] scalars field. /// `inp_secrets` and `out_secrets` must be consistent by [`Output`] `blinder_index` field - /// For each output, the corresponding inp_secrets\[out.blinder_index\] must be present + /// For each output, the corresponding `inp_secrets`\[`out.blinder_index`\] must be present /// # Parameters /// /// * `inp_secrets`: [`TxOutSecrets`] corresponding to owned inputs. Use [`None`] for non-owned outputs diff --git a/src/pset/raw.rs b/src/pset/raw.rs index e29a145c..2a79528a 100644 --- a/src/pset/raw.rs +++ b/src/pset/raw.rs @@ -210,8 +210,8 @@ impl ProprietaryKey where Subtype: Copy + From + Into, { - /// Constructs [ProprietaryKey] from [Key]; returns - /// [Error::InvalidProprietaryKey] if `key` do not starts with 0xFC byte + /// Constructs [`ProprietaryKey`] from [Key]; returns + /// [`Error::InvalidProprietaryKey`] if `key` do not starts with 0xFC byte pub fn from_key(key: Key) -> Result { if key.type_value != 0xFC { return Err(Error::InvalidProprietaryKey); diff --git a/src/schnorr.rs b/src/schnorr.rs index 66b3bf07..5cd4526e 100644 --- a/src/schnorr.rs +++ b/src/schnorr.rs @@ -232,7 +232,7 @@ impl SchnorrSig { Ok(SchnorrSig { sig, hash_ty }) } - /// Serialize SchnorrSig + /// Serialize `SchnorrSig` pub fn to_vec(&self) -> Vec { // TODO: add support to serialize to a writer to SerializedSig let mut ser_sig = self.sig.as_ref().to_vec(); diff --git a/src/script.rs b/src/script.rs index 7f54be5c..28c93c05 100644 --- a/src/script.rs +++ b/src/script.rs @@ -431,14 +431,14 @@ impl Script { self.0[1] == opcodes::all::OP_PUSHBYTES_20.into_u8() } - /// Check if this is an OP_RETURN output + /// Check if this is an `OP_RETURN` output pub fn is_op_return (&self) -> bool { !self.0.is_empty() && (opcodes::All::from(self.0[0]) == opcodes::all::OP_RETURN) } /// Whether a script can be proven to have no satisfying input - /// In elements, is_provably_unspendable is consensus critical - /// matches the implementation of CScript::IsUnspendable() + /// In elements, `is_provably_unspendable` is consensus critical + /// matches the implementation of `CScript::IsUnspendable()` pub fn is_provably_unspendable(&self) -> bool { !self.0.is_empty() && opcodes::All::from(self.0[0]) == opcodes::all::OP_RETURN || self.len() > MAX_SCRIPT_SIZE @@ -450,7 +450,7 @@ impl Script { /// iterator will end. To instead iterate over the script as sequence of bytes, treat /// it as a slice using `script[..]` or convert it to a vector using `into_bytes()`. /// - /// To force minimal pushes, use [Script::instructions_minimal]. + /// To force minimal pushes, use [`Script::instructions_minimal`]. pub fn instructions(&self) -> Instructions<'_> { Instructions { data: &self.0[..], @@ -594,7 +594,7 @@ pub enum Instruction<'a> { } impl<'a> Instruction<'a> { - /// Get the opcode in case of [Instruction::Op]. + /// Get the opcode in case of [`Instruction::Op`]. pub fn op(&self) -> Option { if let Instruction::Op(o) = self { Some(*o) @@ -603,7 +603,7 @@ impl<'a> Instruction<'a> { } } - /// Get the push bytes in case of [Instruction::PushBytes]. + /// Get the push bytes in case of [`Instruction::PushBytes`]. pub fn push_bytes(&self) -> Option<&'a [u8]> { if let Instruction::PushBytes(p) = self { Some(p) diff --git a/src/serde_utils.rs b/src/serde_utils.rs index 74a98947..8e35b922 100644 --- a/src/serde_utils.rs +++ b/src/serde_utils.rs @@ -1,7 +1,7 @@ //! Module for special serde serializations. //! Copied from rust-bitcoin as is. pub mod btreemap_byte_values { - //! Module for serialization of BTreeMaps with hex byte values. + //! Module for serialization of `BTreeMaps` with hex byte values. #![allow(missing_docs)] // NOTE: This module can be exactly copied to use with HashMap. @@ -67,8 +67,8 @@ pub mod btreemap_byte_values { } pub mod btreemap_as_seq { - //! Module for serialization of BTreeMaps as lists of sequences because - //! serde_json will not serialize hashmaps with non-string keys be default. + //! Module for serialization of `BTreeMaps` as lists of sequences because + //! `serde_json` will not serialize hashmaps with non-string keys be default. #![allow(missing_docs)] // NOTE: This module can be exactly copied to use with HashMap. @@ -136,8 +136,8 @@ pub mod btreemap_as_seq { } pub mod btreemap_as_seq_byte_values { - //! Module for serialization of BTreeMaps as lists of sequences because - //! serde_json will not serialize hashmaps with non-string keys be default. + //! Module for serialization of `BTreeMaps` as lists of sequences because + //! `serde_json` will not serialize hashmaps with non-string keys be default. #![allow(missing_docs)] // NOTE: This module can be exactly copied to use with HashMap. diff --git a/src/sighash.rs b/src/sighash.rs index 9b263acf..68a8accc 100644 --- a/src/sighash.rs +++ b/src/sighash.rs @@ -123,7 +123,7 @@ pub enum Error { inputs_size: usize, }, - /// Using SIGHASH_SINGLE without a "corresponding output" (an output with the same index as the + /// Using `SIGHASH_SINGLE` without a "corresponding output" (an output with the same index as the /// input being verified) is a validation failure SingleWithoutCorrespondingOutput { /// Requested index @@ -202,7 +202,7 @@ impl Prevouts<'_, T> where T: Borrow { } impl<'s> ScriptPath<'s> { - /// Create a new ScriptPath structure + /// Create a new `ScriptPath` structure pub fn new(script: &'s Script, code_separator_pos: u32, leaf_version: u8) -> Self { ScriptPath { script, @@ -210,7 +210,7 @@ impl<'s> ScriptPath<'s> { leaf_version, } } - /// Create a new ScriptPath structure using default values for `code_separator_pos` and `leaf_version` + /// Create a new `ScriptPath` structure using default values for `code_separator_pos` and `leaf_version` pub fn with_defaults(script: &'s Script) -> Self { Self::new(script, 0xFFFFFFFFu32, 0xc4) } @@ -236,7 +236,7 @@ impl> SighashCache { /// Compute the sighash components from an unsigned transaction and auxiliary /// in a lazy manner when required. /// For the generated sighashes to be valid, no fields in the transaction may change except for - /// script_sig and witnesses. + /// `script_sig` and witnesses. pub fn new(tx: R) -> Self { SighashCache { tx, @@ -247,7 +247,7 @@ impl> SighashCache { } /// Encode the BIP341 signing data for any flag type into a given object implementing a - /// io::Write trait. + /// `io::Write` trait. #[allow(clippy::too_many_arguments)] pub fn taproot_encode_signing_data_to>( &mut self, @@ -491,9 +491,9 @@ impl> SighashCache { } /// Encode the BIP143 signing data for any flag type into a given object implementing a - /// std::io::Write trait. + /// `std::io::Write` trait. /// - /// *Warning* This does NOT attempt to support OP_CODESEPARATOR. In general + /// *Warning* This does NOT attempt to support `OP_CODESEPARATOR`. In general /// this would require evaluating `script_pubkey` to determine which separators /// get evaluated and which don't, which we don't have the information to /// determine. @@ -565,7 +565,7 @@ impl> SighashCache { } /// Compute the segwitv0(BIP143) style sighash for any flag type. - /// *Warning* This does NOT attempt to support OP_CODESEPARATOR. In general + /// *Warning* This does NOT attempt to support `OP_CODESEPARATOR`. In general /// this would require evaluating `script_pubkey` to determine which separators /// get evaluated and which don't, which we don't have the information to /// determine. @@ -588,10 +588,10 @@ impl> SighashCache { /// Encodes the signing data from which a signature hash for a given input index with a given /// sighash flag can be computed. To actually produce a scriptSig, this hash needs to be run - /// through an ECDSA signer, the SighashType appended to the resulting sig, and a script + /// through an ECDSA signer, the `SighashType` appended to the resulting sig, and a script /// written around this, but this is the general (and hard) part. /// - /// *Warning* This does NOT attempt to support OP_CODESEPARATOR. In general this would require + /// *Warning* This does NOT attempt to support `OP_CODESEPARATOR`. In general this would require /// evaluating `script_pubkey` to determine which separators get evaluated and which don't, /// which we don't have the information to determine. /// @@ -675,11 +675,11 @@ impl> SighashCache { /// Computes a signature hash for a given input index with a given sighash flag. /// To actually produce a scriptSig, this hash needs to be run through an - /// ECDSA signer, the SighashType appended to the resulting sig, and a + /// ECDSA signer, the `SighashType` appended to the resulting sig, and a /// script written around this, but this is the general (and hard) part. /// Does not take a mutable reference because it does not do any caching. /// - /// *Warning* This does NOT attempt to support OP_CODESEPARATOR. In general + /// *Warning* This does NOT attempt to support `OP_CODESEPARATOR`. In general /// this would require evaluating `script_pubkey` to determine which separators /// get evaluated and which don't, which we don't have the information to /// determine. @@ -814,7 +814,7 @@ impl> SighashCache { } impl> SighashCache { - /// When the SighashCache is initialized with a mutable reference to a transaction instead of a + /// When the `SighashCache` is initialized with a mutable reference to a transaction instead of a /// regular reference, this method is available to allow modification to the witnesses. /// /// This allows in-line signing such as diff --git a/src/taproot.rs b/src/taproot.rs index d1fb38e7..17a8c222 100644 --- a/src/taproot.rs +++ b/src/taproot.rs @@ -49,7 +49,7 @@ sha256t_hash_newtype! { impl TapTweakHash { /// Create a new BIP341 [`TapTweakHash`] from key and tweak - /// Produces H_taptweak(P||R) where P is internal key and R is the merkle root + /// Produces `H_taptweak(P||R)` where P is internal key and R is the merkle root pub fn from_key_and_tweak( internal_key: UntweakedPublicKey, merkle_root: Option, @@ -109,7 +109,7 @@ type ScriptMerkleProofMap = BTreeMap<(Script, LeafVersion), BTreeSet TapTweakHash { TapTweakHash::from_key_and_tweak(self.internal_key, self.merkle_root) } @@ -273,7 +273,7 @@ impl TaprootSpendInfo { /// Obtain a [`ControlBlock`] for particular script with the given version. /// Returns [`None`] if the script is not contained in the [`TaprootSpendInfo`] - /// If there are multiple ControlBlocks possible, this returns the shortest one. + /// If there are multiple `ControlBlocks` possible, this returns the shortest one. pub fn control_block(&self, script_ver: &(Script, LeafVersion)) -> Option { let merkle_branch_set = self.script_map.get(script_ver)?; // Choose the smallest one amongst the multiple script maps @@ -453,7 +453,7 @@ pub struct NodeInfo { } impl NodeInfo { - /// Creates a new NodeInfo with omitted/hidden info + /// Creates a new `NodeInfo` with omitted/hidden info pub fn new_hidden(hash: sha256::Hash) -> Self { Self { hash, @@ -461,7 +461,7 @@ impl NodeInfo { } } - /// Creates a new leaf with NodeInfo + /// Creates a new leaf with `NodeInfo` pub fn new_leaf_with_ver(script: Script, ver: LeafVersion) -> Self { let leaf = LeafInfo::new(script, ver); Self { @@ -470,7 +470,7 @@ impl NodeInfo { } } - /// Combines two NodeInfo's to create a new parent + /// Combines two `NodeInfo`'s to create a new parent pub fn combine(a: Self, b: Self) -> Result { let mut all_leaves = Vec::with_capacity(a.leaves.len() + b.leaves.len()); for mut a_leaf in a.leaves { @@ -584,8 +584,8 @@ impl TaprootMerkleBranch { } } - /// Create a MerkleProof from Vec<[`sha256::Hash`]>. Returns an error when - /// inner proof len is more than TAPROOT_CONTROL_MAX_NODE_COUNT (128) + /// Create a `MerkleProof` from Vec<[`sha256::Hash`]>. Returns an error when + /// inner proof len is more than `TAPROOT_CONTROL_MAX_NODE_COUNT` (128) pub fn from_inner(inner: Vec) -> Result { if inner.len() > TAPROOT_CONTROL_MAX_NODE_COUNT { Err(TaprootError::InvalidMerkleTreeDepth(inner.len())) @@ -615,14 +615,14 @@ pub struct ControlBlock { } impl ControlBlock { - /// Obtain a ControlBlock from slice. This is an extra witness element + /// Obtain a `ControlBlock` from slice. This is an extra witness element /// that provides the proof that taproot script pubkey is correctly computed /// with some specified leaf hash. This is the last element in /// taproot witness when spending a output via script path. /// /// # Errors: /// - If the control block size is not of the form 33 + 32m where - /// 0 <= m <= 128, InvalidControlBlock is returned + /// 0 <= m <= 128, `InvalidControlBlock` is returned pub fn from_slice(sl: &[u8]) -> Result { if sl.len() < TAPROOT_CONTROL_BASE_SIZE || (sl.len() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE != 0 @@ -644,7 +644,7 @@ impl ControlBlock { } /// Obtain the size of control block. Faster and more efficient than calling - /// serialize() followed by len(). Can be handy for fee estimation + /// `serialize()` followed by `len()`. Can be handy for fee estimation pub fn size(&self) -> usize { TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * self.merkle_branch.as_inner().len() } @@ -660,8 +660,8 @@ impl ControlBlock { } /// Serialize the control block. This would be required when - /// using ControlBlock as a witness element while spending an output via - /// script path. This serialization does not include the VarInt prefix that would be + /// using `ControlBlock` as a witness element while spending an output via + /// script path. This serialization does not include the `VarInt` prefix that would be /// applied when encoding this element as a witness. pub fn serialize(&self) -> Vec { let mut buf = Vec::with_capacity(self.size()); @@ -721,8 +721,8 @@ impl Default for LeafVersion { } impl LeafVersion { - /// Obtain LeafVersion from u8, will error when last bit of ver is even or - /// when ver is 0x50 (ANNEX_TAG) + /// Obtain `LeafVersion` from u8, will error when last bit of ver is even or + /// when ver is 0x50 (`ANNEX_TAG`) // Text from BIP341: // In order to support some forms of static analysis that rely on // being able to identify script spends without access to the output being @@ -740,7 +740,7 @@ impl LeafVersion { } } - /// Get the inner version from LeafVersion + /// Get the inner version from `LeafVersion` pub fn as_u8(&self) -> u8 { self.0 } @@ -813,7 +813,7 @@ pub enum TaprootError { InvalidControlBlockSize(usize), /// Invalid taproot internal key InvalidInternalKey(secp256k1_zkp::UpstreamError), - /// Empty TapTree + /// Empty `TapTree` EmptyTree, } diff --git a/src/transaction.rs b/src/transaction.rs index a373310d..403ab9fd 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -619,7 +619,7 @@ impl TxIn { } /// Compute the issuance asset ids from this [`TxIn`]. This function does not check - /// whether there is an issuance in this input. Returns (asset_id, token_id) + /// whether there is an issuance in this input. Returns (`asset_id`, `token_id`) pub fn issuance_ids(&self) -> (AssetId, AssetId) { let entropy = if self.asset_issuance.asset_blinding_nonce == ZERO_TWEAK { let contract_hash = @@ -749,7 +749,7 @@ impl TxOut { } } - /// Whether this data represents nulldata (OP_RETURN followed by pushes, + /// Whether this data represents nulldata (`OP_RETURN` followed by pushes, /// not necessarily minimal) pub fn is_null_data(&self) -> bool { let mut iter = self.script_pubkey.instructions(); From d2b998bb0bc0831e29a15de52fdd3ec2c15d6ec8 Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:58:49 +0000 Subject: [PATCH 08/28] clippy: fix explicit-iter-loop and explicit-into-iter-loop lints --- src/address.rs | 4 ++-- src/blind.rs | 2 +- src/confidential.rs | 2 +- src/pset/map/global.rs | 4 ++-- src/pset/map/input.rs | 4 ++-- src/pset/map/output.rs | 4 ++-- src/pset/mod.rs | 8 ++++---- src/pset/serialize.rs | 4 ++-- src/script.rs | 4 ++-- src/serde_utils.rs | 6 +++--- src/sighash.rs | 10 +++++----- src/taproot.rs | 2 +- src/transaction.rs | 2 +- 13 files changed, 28 insertions(+), 28 deletions(-) diff --git a/src/address.rs b/src/address.rs index 2c123f88..61bba5a6 100644 --- a/src/address.rs +++ b/src/address.rs @@ -692,7 +692,7 @@ impl FromStr for Address { let net_arr = [liq, ele, liq_test]; let prefix = find_prefix(s); - for net in net_arr.iter() { + for net in &net_arr { // Bech32. if match_prefix(prefix, net.bech_hrp) { return Address::from_bech32(s, false, net); @@ -712,7 +712,7 @@ impl FromStr for Address { } let p = data[0]; - for net in net_arr.iter() { + for net in &net_arr { if p == net.p2pkh_prefix || p == net.p2sh_prefix || p == net.blinded_prefix { return Address::from_base58(&data, net); } diff --git a/src/blind.rs b/src/blind.rs index bd42c24a..eb3252fc 100644 --- a/src/blind.rs +++ b/src/blind.rs @@ -1002,7 +1002,7 @@ impl Transaction { (inp.asset_issuance.amount, asset_id), (inp.asset_issuance.inflation_keys, token_id), ]; - for (amt, asset) in arr.iter() { + for (amt, asset) in &arr { match amt { Value::Null => continue, Value::Explicit(v) => { diff --git a/src/confidential.rs b/src/confidential.rs index 1fbf5ea1..3d874e68 100644 --- a/src/confidential.rs +++ b/src/confidential.rs @@ -598,7 +598,7 @@ impl fmt::Display for Nonce { match *self { Nonce::Null => f.write_str("null"), Nonce::Explicit(n) => { - for b in n.iter() { + for b in &n { write!(f, "{:02x}", b)?; } Ok(()) diff --git a/src/pset/map/global.rs b/src/pset/map/global.rs index acdec446..babad8af 100644 --- a/src/pset/map/global.rs +++ b/src/pset/map/global.rs @@ -276,14 +276,14 @@ impl Map for Global { rv.push_prop(self.elements_tx_modifiable_flag as ) } - for (key, value) in self.proprietary.iter() { + for (key, value) in &self.proprietary { rv.push(raw::Pair { key: key.to_key(), value: value.clone(), }); } - for (key, value) in self.unknown.iter() { + for (key, value) in &self.unknown { rv.push(raw::Pair { key: key.clone(), value: value.clone(), diff --git a/src/pset/map/input.rs b/src/pset/map/input.rs index 3e2bf74b..3dea9626 100644 --- a/src/pset/map/input.rs +++ b/src/pset/map/input.rs @@ -1029,14 +1029,14 @@ impl Map for Input { rv.push_prop(self.blinded_issuance as ) } - for (key, value) in self.proprietary.iter() { + for (key, value) in &self.proprietary { rv.push(raw::Pair { key: key.to_key(), value: value.clone(), }); } - for (key, value) in self.unknown.iter() { + for (key, value) in &self.unknown { rv.push(raw::Pair { key: key.clone(), value: value.clone(), diff --git a/src/pset/map/output.rs b/src/pset/map/output.rs index b6470258..6ed45f54 100644 --- a/src/pset/map/output.rs +++ b/src/pset/map/output.rs @@ -488,14 +488,14 @@ impl Map for Output { rv.push_prop(self.blind_asset_proof as ) } - for (key, value) in self.proprietary.iter() { + for (key, value) in &self.proprietary { rv.push(raw::Pair { key: key.to_key(), value: value.clone(), }); } - for (key, value) in self.unknown.iter() { + for (key, value) in &self.unknown { rv.push(raw::Pair { key: key.clone(), value: value.clone(), diff --git a/src/pset/mod.rs b/src/pset/mod.rs index f2d8cec0..f04d44f5 100644 --- a/src/pset/mod.rs +++ b/src/pset/mod.rs @@ -257,7 +257,7 @@ impl PartiallySignedTransaction { // changed by Updaters and Combiners, the sequence number in this unsigned // transaction must be set to 0 (not final, nor the sequence in PSBT_IN_SEQUENCE). // The lock time in this unsigned transaction must be computed as described previously. - for inp in tx.input.iter_mut() { + for inp in &mut tx.input { inp.sequence = Sequence::from_height(0); } Ok(tx.txid()) @@ -283,7 +283,7 @@ impl PartiallySignedTransaction { let mut inputs = vec![]; let mut outputs = vec![]; - for psetin in self.inputs.iter() { + for psetin in &self.inputs { let txin = TxIn { previous_output: OutPoint::new(psetin.previous_txid, psetin.previous_output_index), is_pegin: psetin.is_pegin(), @@ -308,7 +308,7 @@ impl PartiallySignedTransaction { inputs.push(txin); } - for out in self.outputs.iter() { + for out in &self.outputs { let txout = TxOut { asset: match (out.asset_comm, out.asset) { (Some(gen), _) => confidential::Asset::Confidential(gen), @@ -634,7 +634,7 @@ impl PartiallySignedTransaction { ValueBlindingFactor::last(secp, value, out_abf, &inp_secrets, &exp_out_secrets); // Add all the scalars - for value_diff in self.global.scalars.iter() { + for value_diff in &self.global.scalars { final_vbf += ValueBlindingFactor(*value_diff); } diff --git a/src/pset/serialize.rs b/src/pset/serialize.rs index a38db623..868d6ae2 100644 --- a/src/pset/serialize.rs +++ b/src/pset/serialize.rs @@ -166,7 +166,7 @@ impl Serialize for KeySource { rv.append(&mut self.0.to_bytes().to_vec()); - for cnum in self.1.into_iter() { + for cnum in &self.1 { rv.append(&mut serialize(&u32::from(*cnum))) } @@ -438,7 +438,7 @@ impl Serialize for TapTree { match (self.0.branch().len(), self.0.branch().last()) { (1, Some(Some(root))) => { let mut buf = Vec::new(); - for leaf_info in root.leaves.iter() { + for leaf_info in &root.leaves { // # Cast Safety: // // TaprootMerkleBranch can only have len atmost 128(TAPROOT_CONTROL_MAX_NODE_COUNT). diff --git a/src/script.rs b/src/script.rs index 28c93c05..2dab973a 100644 --- a/src/script.rs +++ b/src/script.rs @@ -1080,8 +1080,8 @@ mod test { assert_eq!(build_scriptint(256), vec![0, 1]); assert_eq!(build_scriptint(257), vec![1, 1]); assert_eq!(build_scriptint(511), vec![255, 1]); - for &i in [10, 100, 255, 256, 1000, 10000, 25000, 200000, 5000000, 1000000000, - (1 << 31) - 1, -((1 << 31) - 1)].iter() { + for &i in &[10, 100, 255, 256, 1000, 10000, 25000, 200000, 5000000, 1000000000, + (1 << 31) - 1, -((1 << 31) - 1)] { assert_eq!(Ok(i), read_scriptint(&build_scriptint(i))); assert_eq!(Ok(-i), read_scriptint(&build_scriptint(-i))); } diff --git a/src/serde_utils.rs b/src/serde_utils.rs index 8e35b922..cb865cb5 100644 --- a/src/serde_utils.rs +++ b/src/serde_utils.rs @@ -22,7 +22,7 @@ pub mod btreemap_byte_values { serde::Serialize::serialize(v, s) } else { let mut map = s.serialize_map(Some(v.len()))?; - for (key, value) in v.iter() { + for (key, value) in v { map.serialize_entry(key, &value.to_hex())?; } map.end() @@ -89,7 +89,7 @@ pub mod btreemap_as_seq { serde::Serialize::serialize(v, s) } else { let mut seq = s.serialize_seq(Some(v.len()))?; - for pair in v.iter() { + for pair in v { seq.serialize_element(&pair)?; } seq.end() @@ -175,7 +175,7 @@ pub mod btreemap_as_seq_byte_values { serde::Serialize::serialize(v, s) } else { let mut seq = s.serialize_seq(Some(v.len()))?; - for (key, value) in v.iter() { + for (key, value) in v { seq.serialize_element(&BorrowedPair(key, value))?; } seq.end() diff --git a/src/sighash.rs b/src/sighash.rs index 68a8accc..14440091 100644 --- a/src/sighash.rs +++ b/src/sighash.rs @@ -711,7 +711,7 @@ impl> SighashCache { common_cache.get_or_insert_with(|| { let mut enc_prevouts = sha256::Hash::engine(); let mut enc_sequences = sha256::Hash::engine(); - for txin in tx.input.iter() { + for txin in &tx.input { txin.previous_output .consensus_encode(&mut enc_prevouts) .unwrap(); @@ -722,14 +722,14 @@ impl> SighashCache { sequences: sha256::Hash::from_engine(enc_sequences), outputs: { let mut enc = sha256::Hash::engine(); - for txout in tx.output.iter() { + for txout in &tx.output { txout.consensus_encode(&mut enc).unwrap(); } sha256::Hash::from_engine(enc) }, issuances: { let mut enc = sha256::Hash::engine(); - for txin in tx.input.iter() { + for txin in &tx.input { if txin.has_issuance() { txin.asset_issuance.consensus_encode(&mut enc).unwrap(); } else { @@ -789,7 +789,7 @@ impl> SighashCache { .consensus_encode(&mut enc_script_pubkeys) .unwrap(); } - for inp in tx.input.iter() { + for inp in &tx.input { inp.outpoint_flag() .consensus_encode(&mut enc_outpoint_flags).unwrap(); inp.witness.amount_rangeproof @@ -798,7 +798,7 @@ impl> SighashCache { .consensus_encode(&mut enc_issuance_rangeproofs).unwrap(); } - for out in tx.output.iter() { + for out in &tx.output { out.witness.surjection_proof.consensus_encode(&mut enc_output_witnesses).unwrap(); out.witness.rangeproof.consensus_encode(&mut enc_output_witnesses).unwrap(); } diff --git a/src/taproot.rs b/src/taproot.rs index 17a8c222..cfea81e6 100644 --- a/src/taproot.rs +++ b/src/taproot.rs @@ -563,7 +563,7 @@ impl TaprootMerkleBranch { /// Serialize to a writer. Returns the number of bytes written pub fn encode(&self, mut writer: Write) -> io::Result { let mut written = 0; - for hash in self.0.iter() { + for hash in &self.0 { written += writer.write(hash.as_ref())?; } Ok(written) diff --git a/src/transaction.rs b/src/transaction.rs index 403ab9fd..8d2cd976 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -935,7 +935,7 @@ impl Transaction { pub fn discount_weight(&self) -> usize { let mut weight = self.scaled_size(4); - for out in self.output.iter() { + for out in &self.output { let rp_len = out.witness.rangeproof_len(); let sp_len = out.witness.surjectionproof_len(); let witness_weight = VarInt(sp_len as u64).size() + sp_len + VarInt(rp_len as u64).size() + rp_len; From 6db0383c3fb8caf41152531ecf4d18501eb8c4bd Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:41:04 +0000 Subject: [PATCH 09/28] clippy: fix if_not_else lint This one is a bit silly -- it complains if you do `if !x {} else {}` because it would supposedly be simpler to swap the if and the else. In fact, everywhere it triggers in this crate it *would* be an improvement, or at least neutral. So turn it on. In some cases we are using if-statements where we could instead use matches. --- src/address.rs | 12 +++---- src/confidential.rs | 30 +++++++++-------- src/issuance.rs | 10 +++--- src/pset/map/global.rs | 73 +++++++++++++++++++++--------------------- src/serde_utils.rs | 48 +++++++++++++-------------- src/sighash.rs | 12 +++---- 6 files changed, 90 insertions(+), 95 deletions(-) diff --git a/src/address.rs b/src/address.rs index 61bba5a6..155776f9 100644 --- a/src/address.rs +++ b/src/address.rs @@ -670,14 +670,10 @@ fn find_prefix(bech32: &str) -> &str { /// The first prefix can be mixed case, but the second one is expected in /// lower case. fn match_prefix(prefix_mixed: &str, target: Hrp) -> bool { - if target.len() != prefix_mixed.len() { - false - } else { - target - .lowercase_char_iter() - .zip(prefix_mixed.chars()) - .all(|(char_lower, char_mixed)| char_lower == char_mixed.to_ascii_lowercase()) - } + target.len() == prefix_mixed.len() && target + .lowercase_char_iter() + .zip(prefix_mixed.chars()) + .all(|(char_lower, char_mixed)| char_lower == char_mixed.to_ascii_lowercase()) } impl FromStr for Address { diff --git a/src/confidential.rs b/src/confidential.rs index 3d874e68..df358aa9 100644 --- a/src/confidential.rs +++ b/src/confidential.rs @@ -841,13 +841,14 @@ impl<'de> Deserialize<'de> for AssetBlindingFactor { where E: ::serde::de::Error, { - if v.len() != 32 { - Err(E::invalid_length(v.len(), &stringify!($len))) - } else { - let mut ret = [0; 32]; - ret.copy_from_slice(v); - let inner = Tweak::from_inner(ret).map_err(E::custom)?; - Ok(AssetBlindingFactor(inner)) + use core::convert::TryFrom; + + match <[u8; 32]>::try_from(v) { + Ok(ret) => { + let inner = Tweak::from_inner(ret).map_err(E::custom)?; + Ok(AssetBlindingFactor(inner)) + } + Err(_) => Err(E::invalid_length(v.len(), &stringify!($len))), } } } @@ -1044,13 +1045,14 @@ impl<'de> Deserialize<'de> for ValueBlindingFactor { where E: ::serde::de::Error, { - if v.len() != 32 { - Err(E::invalid_length(v.len(), &stringify!($len))) - } else { - let mut ret = [0; 32]; - ret.copy_from_slice(v); - let inner = Tweak::from_inner(ret).map_err(E::custom)?; - Ok(ValueBlindingFactor(inner)) + use core::convert::TryFrom; + + match <[u8; 32]>::try_from(v) { + Ok(ret) => { + let inner = Tweak::from_inner(ret).map_err(E::custom)?; + Ok(ValueBlindingFactor(inner)) + } + Err(_) => Err(E::invalid_length(v.len(), &stringify!($len))), } } } diff --git a/src/issuance.rs b/src/issuance.rs index 87688a72..d6387617 100644 --- a/src/issuance.rs +++ b/src/issuance.rs @@ -244,12 +244,10 @@ impl<'de> ::serde::Deserialize<'de> for AssetId { where E: ::serde::de::Error, { - if v.len() != 32 { - Err(E::invalid_length(v.len(), &stringify!($len))) - } else { - let mut ret = [0; 32]; - ret.copy_from_slice(v); - Ok(AssetId(sha256::Midstate::from_byte_array(ret))) + use core::convert::TryFrom; + match <[u8; 32]>::try_from(v) { + Ok(ret) => Ok(AssetId(sha256::Midstate::from_byte_array(ret))), + Err(_) => Err(E::invalid_length(v.len(), &stringify!($len))), } } } diff --git a/src/pset/map/global.rs b/src/pset/map/global.rs index babad8af..4405158f 100644 --- a/src/pset/map/global.rs +++ b/src/pset/map/global.rs @@ -169,11 +169,10 @@ impl Map for Global { if prop_key.is_pset_key() && prop_key.subtype == PSBT_ELEMENTS_GLOBAL_SCALAR { if raw_value.is_empty() && prop_key.key.len() == 32 { let scalar = Tweak::from_slice(&prop_key.key)?; - if !self.scalars.contains(&scalar) { - self.scalars.push(scalar); - } else { + if self.scalars.contains(&scalar) { return Err(Error::DuplicateKey(raw_key).into()); } + self.scalars.push(scalar); } else { return Err(Error::InvalidKey(raw_key))?; } @@ -415,41 +414,41 @@ impl Decodable for Global { } } PSET_GLOBAL_XPUB => { - if !raw_key.key.is_empty() { - let xpub = Xpub::decode(&raw_key.key) - .map_err(|_| encode::Error::ParseFailed( - "Can't deserialize Xpub from global XPUB key data" - ))?; - - if raw_value.is_empty() || raw_value.len() % 4 != 0 { - return Err(encode::Error::ParseFailed( - "Incorrect length of global xpub derivation data", - )); - } - - let child_count = raw_value.len() / 4 - 1; - let mut decoder = Cursor::new(raw_value); - let mut fingerprint = [0u8; 4]; - decoder.read_exact(&mut fingerprint[..])?; - let mut path = Vec::::with_capacity(child_count); - while let Ok(index) = u32::consensus_decode(&mut decoder) { - path.push(ChildNumber::from(index)) - } - let derivation = DerivationPath::from(path); - // Keys, according to BIP-174, must be unique - if xpub_map - .insert(xpub, (Fingerprint::from(fingerprint), derivation)) - .is_some() - { - return Err(encode::Error::ParseFailed( - "Repeated global xpub key", - )); - } - } else { + if raw_key.key.is_empty() { return Err(encode::Error::ParseFailed( "Xpub global key must contain serialized Xpub data", )); } + + let xpub = Xpub::decode(&raw_key.key) + .map_err(|_| encode::Error::ParseFailed( + "Can't deserialize Xpub from global XPUB key data" + ))?; + + if raw_value.is_empty() || raw_value.len() % 4 != 0 { + return Err(encode::Error::ParseFailed( + "Incorrect length of global xpub derivation data", + )); + } + + let child_count = raw_value.len() / 4 - 1; + let mut decoder = Cursor::new(raw_value); + let mut fingerprint = [0u8; 4]; + decoder.read_exact(&mut fingerprint[..])?; + let mut path = Vec::::with_capacity(child_count); + while let Ok(index) = u32::consensus_decode(&mut decoder) { + path.push(ChildNumber::from(index)) + } + let derivation = DerivationPath::from(path); + // Keys, according to BIP-174, must be unique + if xpub_map + .insert(xpub, (Fingerprint::from(fingerprint), derivation)) + .is_some() + { + return Err(encode::Error::ParseFailed( + "Repeated global xpub key", + )); + } } PSET_GLOBAL_VERSION => { impl_pset_insert_pair! { @@ -463,10 +462,10 @@ impl Decodable for Global { { if raw_value.is_empty() && prop_key.key.len() == 32 { let scalar = Tweak::from_slice(&prop_key.key)?; - if !scalars.contains(&scalar) { - scalars.push(scalar); - } else { + if scalars.contains(&scalar) { return Err(Error::DuplicateKey(raw_key).into()); + } else { + scalars.push(scalar); } } else { return Err(Error::InvalidKey(raw_key))?; diff --git a/src/serde_utils.rs b/src/serde_utils.rs index cb865cb5..0c9dd806 100644 --- a/src/serde_utils.rs +++ b/src/serde_utils.rs @@ -18,14 +18,14 @@ pub mod btreemap_byte_values { use serde::ser::SerializeMap; // Don't do anything special when not human readable. - if !s.is_human_readable() { - serde::Serialize::serialize(v, s) - } else { + if s.is_human_readable() { let mut map = s.serialize_map(Some(v.len()))?; for (key, value) in v { map.serialize_entry(key, &value.to_hex())?; } map.end() + } else { + serde::Serialize::serialize(v, s) } } @@ -58,10 +58,10 @@ pub mod btreemap_byte_values { } // Don't do anything special when not human readable. - if !d.is_human_readable() { - serde::Deserialize::deserialize(d) - } else { + if d.is_human_readable() { d.deserialize_map(Visitor(PhantomData)) + } else { + serde::Deserialize::deserialize(d) } } } @@ -85,14 +85,14 @@ pub mod btreemap_as_seq { use serde::ser::SerializeSeq; // Don't do anything special when not human readable. - if !s.is_human_readable() { - serde::Serialize::serialize(v, s) - } else { + if s.is_human_readable() { let mut seq = s.serialize_seq(Some(v.len()))?; for pair in v { seq.serialize_element(&pair)?; } seq.end() + } else { + serde::Serialize::serialize(v, s) } } @@ -127,10 +127,10 @@ pub mod btreemap_as_seq { } // Don't do anything special when not human readable. - if !d.is_human_readable() { - serde::Deserialize::deserialize(d) - } else { + if d.is_human_readable() { d.deserialize_seq(Visitor(PhantomData)) + } else { + serde::Deserialize::deserialize(d) } } } @@ -171,14 +171,14 @@ pub mod btreemap_as_seq_byte_values { use serde::ser::SerializeSeq; // Don't do anything special when not human readable. - if !s.is_human_readable() { - serde::Serialize::serialize(v, s) - } else { + if s.is_human_readable() { let mut seq = s.serialize_seq(Some(v.len()))?; for (key, value) in v { seq.serialize_element(&BorrowedPair(key, value))?; } seq.end() + } else { + serde::Serialize::serialize(v, s) } } @@ -211,10 +211,10 @@ pub mod btreemap_as_seq_byte_values { } // Don't do anything special when not human readable. - if !d.is_human_readable() { - serde::Deserialize::deserialize(d) - } else { + if d.is_human_readable() { d.deserialize_seq(Visitor(PhantomData)) + } else { + serde::Deserialize::deserialize(d) } } } @@ -230,10 +230,10 @@ pub mod hex_bytes { where T: serde::Serialize + AsRef<[u8]>, S: serde::Serializer { // Don't do anything special when not human readable. - if !s.is_human_readable() { - serde::Serialize::serialize(bytes, s) - } else { + if s.is_human_readable() { s.serialize_str(&bytes.as_ref().to_hex()) + } else { + serde::Serialize::serialize(bytes, s) } } @@ -267,10 +267,10 @@ pub mod hex_bytes { } // Don't do anything special when not human readable. - if !d.is_human_readable() { - serde::Deserialize::deserialize(d) - } else { + if d.is_human_readable() { d.deserialize_str(Visitor(::std::marker::PhantomData)) + } else { + serde::Deserialize::deserialize(d) } } } diff --git a/src/sighash.rs b/src/sighash.rs index 14440091..88718e4c 100644 --- a/src/sighash.rs +++ b/src/sighash.rs @@ -515,10 +515,10 @@ impl> SighashCache { self.tx.version.consensus_encode(&mut writer)?; - if !anyone_can_pay { - self.segwit_cache().prevouts.consensus_encode(&mut writer)?; - } else { + if anyone_can_pay { zero_hash.consensus_encode(&mut writer)?; + } else { + self.segwit_cache().prevouts.consensus_encode(&mut writer)?; } if !anyone_can_pay && sighash != EcdsaSighashType::Single && sighash != EcdsaSighashType::None { @@ -529,10 +529,10 @@ impl> SighashCache { // Elements: Push the hash issuance zero hash as required // If required implement for issuance, but not necessary as of now - if !anyone_can_pay { - self.segwit_cache().issuances.consensus_encode(&mut writer)?; - } else { + if anyone_can_pay { zero_hash.consensus_encode(&mut writer)?; + } else { + self.segwit_cache().issuances.consensus_encode(&mut writer)?; } // input specific values From 8abf2ba00920ba3700e5a375429f6176b83bcf2e Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 10/28] clippy: fix the `ignored_unit_patterns` lint Just style. --- examples/tx.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/tx.rs b/examples/tx.rs index ae7cd2f1..3144c3e7 100644 --- a/examples/tx.rs +++ b/examples/tx.rs @@ -32,7 +32,7 @@ fn main() { let res = tx.verify_tx_amt_proofs(&secp, &[txout]); match res { - Ok(_) => {} + Ok(()) => {} Err(e) => { panic!("{}", e); } From 90c4f38aec37b0086b2bcfb80689dd796e967a5c Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 11/28] clippy: fix the `items_after_statemnts` lint --- src/taproot.rs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/taproot.rs b/src/taproot.rs index cfea81e6..7b639ee1 100644 --- a/src/taproot.rs +++ b/src/taproot.rs @@ -867,18 +867,19 @@ mod tests{ #[test] fn test_midstates() { - // test that engine creation roundtrips - assert_eq!(tag_engine("TapLeaf/elements").midstate(), TapLeafTag::engine().midstate()); - assert_eq!(tag_engine("TapBranch/elements").midstate(), TapBranchTag::engine().midstate()); - assert_eq!(tag_engine("TapTweak/elements").midstate(), TapTweakTag::engine().midstate()); - assert_eq!(tag_engine("TapSighash/elements").midstate(), TapSighashTag::engine().midstate()); - // check that hash creation is the same as building into the same engine fn empty_hash(tag_name: &str) -> [u8; 32] { let mut e = tag_engine(tag_name); e.input(&[]); sha256::Hash::from_engine(e).to_byte_array() } + + // test that engine creation roundtrips + assert_eq!(tag_engine("TapLeaf/elements").midstate(), TapLeafTag::engine().midstate()); + assert_eq!(tag_engine("TapBranch/elements").midstate(), TapBranchTag::engine().midstate()); + assert_eq!(tag_engine("TapTweak/elements").midstate(), TapTweakTag::engine().midstate()); + assert_eq!(tag_engine("TapSighash/elements").midstate(), TapSighashTag::engine().midstate()); + assert_eq!(empty_hash("TapLeaf/elements"), TapLeafHash::hash(&[]).to_byte_array()); assert_eq!(empty_hash("TapBranch/elements"), TapNodeHash::hash(&[]).to_byte_array()); assert_eq!(empty_hash("TapTweak/elements"), TapTweakHash::hash(&[]).to_byte_array()); From b33901063daf288b4902ee805ac237435a6d5daa Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 12/28] clippy: fix many_single_char_names lint Just one test. Arguably I should've just whitelisted it. BUt I cleaned it up. --- src/taproot.rs | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/src/taproot.rs b/src/taproot.rs index 7b639ee1..205e9bf8 100644 --- a/src/taproot.rs +++ b/src/taproot.rs @@ -951,21 +951,24 @@ mod tests{ // / \ / \ // A B C / \ // D E - let a = Script::from_hex("51").unwrap(); - let b = Script::from_hex("52").unwrap(); - let c = Script::from_hex("53").unwrap(); - let d = Script::from_hex("54").unwrap(); - let e = Script::from_hex("55").unwrap(); - let builder = builder.add_leaf(2, a.clone()).unwrap(); - let builder = builder.add_leaf(2, b.clone()).unwrap(); - let builder = builder.add_leaf(2, c.clone()).unwrap(); - let builder = builder.add_leaf(3, d.clone()).unwrap(); - let builder = builder.add_leaf(3, e.clone()).unwrap(); + let scripts = [ + Script::from_hex("51").unwrap(), + Script::from_hex("52").unwrap(), + Script::from_hex("53").unwrap(), + Script::from_hex("54").unwrap(), + Script::from_hex("55").unwrap(), + ]; + let builder = builder + .add_leaf(2, scripts[0].clone()).unwrap() + .add_leaf(2, scripts[1].clone()).unwrap() + .add_leaf(2, scripts[2].clone()).unwrap() + .add_leaf(3, scripts[3].clone()).unwrap() + .add_leaf(3, scripts[4].clone()).unwrap(); let tree_info = builder.finalize(&secp, internal_key).unwrap(); let output_key = tree_info.output_key(); - for script in [a, b, c, d, e] { + for script in scripts { let ver_script = (script, LeafVersion::default()); let ctrl_block = tree_info.control_block(&ver_script).unwrap(); assert!(ctrl_block.verify_taproot_commitment(&secp, &output_key, &ver_script.0)) From 41cda57dc979eabdffe23e6541dec192a9b9156a Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 13/28] clippy: fix map_unwrap_or lint There is a `map_or` method that encapsulates the `.map().unwrap_or()` pattern. Use it to reduce the number of function calls the reader has to read. --- src/pset/map/input.rs | 12 ++++++++---- src/transaction.rs | 8 ++++---- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/pset/map/input.rs b/src/pset/map/input.rs index 3dea9626..f5ed3d39 100644 --- a/src/pset/map/input.rs +++ b/src/pset/map/input.rs @@ -479,8 +479,10 @@ impl Input { /// If the `sighash_type` field is set to a non-standard ECDSA sighash value. pub fn ecdsa_hash_ty(&self) -> Option { self.sighash_type - .map(|sighash_type| sighash_type.ecdsa_hash_ty()) - .unwrap_or(Some(EcdsaSighashType::All)) + .map_or( + Some(EcdsaSighashType::All), + |sighash_type| sighash_type.ecdsa_hash_ty(), + ) } /// Obtains the [`SchnorrSighashType`] for this input if one is specified. If no sighash type is @@ -491,8 +493,10 @@ impl Input { /// If the `sighash_type` field is set to a invalid Schnorr sighash value. pub fn schnorr_hash_ty(&self) -> Option { self.sighash_type - .map(|sighash_type| sighash_type.schnorr_hash_ty()) - .unwrap_or(Some(SchnorrSighashType::Default)) + .map_or( + Some(SchnorrSighashType::Default), + |sighash_type| sighash_type.schnorr_hash_ty(), + ) } /// Create a psbt input from prevout diff --git a/src/transaction.rs b/src/transaction.rs index 8d2cd976..b004309e 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -668,12 +668,12 @@ impl TxOutWitness { /// The rangeproof len if is present, otherwise 0 pub fn rangeproof_len(&self) -> usize { - self.rangeproof.as_ref().map(|prf| prf.len()).unwrap_or(0) + self.rangeproof.as_ref().map_or(0, |prf| prf.len()) } /// The surjection proof len if is present, otherwise 0 pub fn surjectionproof_len(&self) -> usize { - self.surjection_proof.as_ref().map(|prf| prf.len()).unwrap_or(0) + self.surjection_proof.as_ref().map_or(0, |prf| prf.len()) } } @@ -974,9 +974,9 @@ impl Transaction { } ) + if witness_flag { let amt_prf_len = input.witness.amount_rangeproof.as_ref() - .map(|x| x.len()).unwrap_or(0); + .map_or(0, |x| x.len()); let keys_prf_len = input.witness.inflation_keys_rangeproof.as_ref() - .map(|x| x.len()).unwrap_or(0); + .map_or(0, |x| x.len()); VarInt(amt_prf_len as u64).size() + amt_prf_len + From 2192bef5bfd1889b268508b5397ba940f83f13e9 Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 14/28] clippy: fix the match_wildcard_for_single_variants lint Better to be explicit. --- src/pset/serialize.rs | 4 ++-- src/sighash.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/pset/serialize.rs b/src/pset/serialize.rs index 868d6ae2..43719a19 100644 --- a/src/pset/serialize.rs +++ b/src/pset/serialize.rs @@ -227,7 +227,7 @@ impl Serialize for confidential::Value { match self { confidential::Value::Null => vec![], // should never be invoked confidential::Value::Explicit(x) => Serialize::serialize(x), - y => encode::serialize(y), // confidential can serialized as is + confidential::Value::Confidential(_) => encode::serialize(self), // confidential can serialized as is } } } @@ -272,7 +272,7 @@ impl Serialize for confidential::Asset { match self { confidential::Asset::Null => vec![], // should never be invoked confidential::Asset::Explicit(x) => Serialize::serialize(x), - y => encode::serialize(y), // confidential can serialized as is + confidential::Asset::Confidential(_) => encode::serialize(self), // confidential can serialized as is } } } diff --git a/src/sighash.rs b/src/sighash.rs index 88718e4c..8a5d49b2 100644 --- a/src/sighash.rs +++ b/src/sighash.rs @@ -180,7 +180,7 @@ impl Prevouts<'_, T> where T: Borrow { fn get_all(&self) -> Result<&[T], Error> { match self { Prevouts::All(prevouts) => Ok(*prevouts), - _ => Err(Error::PrevoutKind), + Prevouts::One(..) => Err(Error::PrevoutKind), } } From c19097a2bdf098b682b0a229448098da2d50ee07 Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 15/28] clippy: fix `needless_continue` lint --- src/blind.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/blind.rs b/src/blind.rs index eb3252fc..a41ed3e9 100644 --- a/src/blind.rs +++ b/src/blind.rs @@ -1004,7 +1004,7 @@ impl Transaction { ]; for (amt, asset) in &arr { match amt { - Value::Null => continue, + Value::Null => {}, Value::Explicit(v) => { let gen = Generator::new_unblinded(secp, asset.into_tag()); domain.push(gen); From e523b120b3eea2bb76dd8ec859738f3bd4308dd0 Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 16/28] clippy: fix `needless_pass_by_value` lint This has some API-breaking changes but they're worthwhile (and eliminate a bunch of clones even in this codebase). --- examples/raw_blind.rs | 4 ++-- src/blind.rs | 8 ++++---- src/pset/macros.rs | 2 +- src/pset/map/global.rs | 4 ++-- src/pset/map/input.rs | 14 +++++++------- src/pset/map/output.rs | 2 +- src/pset/raw.rs | 2 +- 7 files changed, 18 insertions(+), 18 deletions(-) diff --git a/examples/raw_blind.rs b/examples/raw_blind.rs index 4447a3b0..0091ceec 100644 --- a/examples/raw_blind.rs +++ b/examples/raw_blind.rs @@ -184,7 +184,7 @@ fn main() { &mut rng, &secp, dest_amt, - Address::p2wsh( + &Address::p2wsh( &Script::new_v0_wsh(&dest_wsh), Some(dest_blind_pk.inner), &PARAMS, @@ -206,7 +206,7 @@ fn main() { &mut rng, &secp, change_amt, - Address::p2wsh( + &Address::p2wsh( &Script::new_v0_wsh(&change_wsh), Some(change_blind_pk.inner), &PARAMS, diff --git a/src/blind.rs b/src/blind.rs index a41ed3e9..a81f311d 100644 --- a/src/blind.rs +++ b/src/blind.rs @@ -487,7 +487,7 @@ impl TxOut { rng: &mut R, secp: &Secp256k1, value: u64, - address: Address, + address: &Address, asset: AssetId, spent_utxo_secrets: &[S], ) -> Result<(Self, AssetBlindingFactor, ValueBlindingFactor, SecretKey), ConfidentialTxOutError> @@ -599,7 +599,7 @@ impl TxOut { self.value .explicit() .ok_or(ConfidentialTxOutError::ExpectedExplicitValue)?, - Address::from_script(&self.script_pubkey, Some(blinder), &AddressParams::ELEMENTS) + &Address::from_script(&self.script_pubkey, Some(blinder), &AddressParams::ELEMENTS) .ok_or(ConfidentialTxOutError::InvalidAddress)?, self.asset .explicit() @@ -1139,7 +1139,7 @@ impl Transaction { rng, secp, out.value.explicit().unwrap(), - address, + &address, out.asset.explicit().unwrap(), spent_utxo_secrets, )?; @@ -1510,7 +1510,7 @@ mod tests { &mut thread_rng(), SECP256K1, value, - address, + &address, asset, &spent_utxo_secrets, ) diff --git a/src/pset/macros.rs b/src/pset/macros.rs index edea5b17..25a04bc3 100644 --- a/src/pset/macros.rs +++ b/src/pset/macros.rs @@ -77,7 +77,7 @@ macro_rules! impl_psetmap_consensus_encoding { #[rustfmt::skip] macro_rules! impl_pset_prop_insert_pair { ($slf:ident.$unkeyed_name:ident <= <$raw_key:ident: _>|<$raw_value:ident: $unkeyed_value_type:ty>) => { - if $crate::pset::raw::ProprietaryKey::::from_key($raw_key.clone())?.key.is_empty() { + if $crate::pset::raw::ProprietaryKey::::from_key(&$raw_key)?.key.is_empty() { if $slf.$unkeyed_name.is_none() { let val: $unkeyed_value_type = $crate::pset::serialize::Deserialize::deserialize(&$raw_value)?; $slf.$unkeyed_name = Some(val) diff --git a/src/pset/map/global.rs b/src/pset/map/global.rs index 4405158f..45b26c60 100644 --- a/src/pset/map/global.rs +++ b/src/pset/map/global.rs @@ -165,7 +165,7 @@ impl Map for Global { | PSET_GLOBAL_TX_MODIFIABLE | PSET_GLOBAL_TX_VERSION => return Err(Error::DuplicateKey(raw_key).into()), PSET_GLOBAL_PROPRIETARY => { - let prop_key = raw::ProprietaryKey::from_key(raw_key.clone())?; + let prop_key = raw::ProprietaryKey::from_key(&raw_key)?; if prop_key.is_pset_key() && prop_key.subtype == PSBT_ELEMENTS_GLOBAL_SCALAR { if raw_value.is_empty() && prop_key.key.len() == 32 { let scalar = Tweak::from_slice(&prop_key.key)?; @@ -456,7 +456,7 @@ impl Decodable for Global { } } PSET_GLOBAL_PROPRIETARY => { - let prop_key = raw::ProprietaryKey::from_key(raw_key.clone())?; + let prop_key = raw::ProprietaryKey::from_key(&raw_key)?; if prop_key.is_pset_key() && prop_key.subtype == PSBT_ELEMENTS_GLOBAL_SCALAR { diff --git a/src/pset/map/input.rs b/src/pset/map/input.rs index f5ed3d39..4373fae5 100644 --- a/src/pset/map/input.rs +++ b/src/pset/map/input.rs @@ -658,7 +658,7 @@ impl Map for Input { pset_insert_hash_pair( &mut self.ripemd160_preimages, raw_key, - raw_value, + &raw_value, error::PsetHash::Ripemd, )?; } @@ -666,7 +666,7 @@ impl Map for Input { pset_insert_hash_pair( &mut self.sha256_preimages, raw_key, - raw_value, + &raw_value, error::PsetHash::Sha256, )?; } @@ -674,7 +674,7 @@ impl Map for Input { pset_insert_hash_pair( &mut self.hash160_preimages, raw_key, - raw_value, + &raw_value, error::PsetHash::Hash160, )?; } @@ -682,7 +682,7 @@ impl Map for Input { pset_insert_hash_pair( &mut self.hash256_preimages, raw_key, - raw_value, + &raw_value, error::PsetHash::Hash256, )?; } @@ -735,7 +735,7 @@ impl Map for Input { } } PSET_IN_PROPRIETARY => { - let prop_key = raw::ProprietaryKey::from_key(raw_key.clone())?; + let prop_key = raw::ProprietaryKey::from_key(&raw_key)?; if prop_key.is_pset_key() { match prop_key.subtype { PSBT_ELEMENTS_IN_ISSUANCE_VALUE => { @@ -1173,7 +1173,7 @@ impl Decodable for Input { fn pset_insert_hash_pair( map: &mut BTreeMap>, raw_key: raw::Key, - raw_value: Vec, + raw_value: &[u8], hash_type: error::PsetHash, ) -> Result<(), encode::Error> where @@ -1185,7 +1185,7 @@ where let key_val: H = serialize::Deserialize::deserialize(&raw_key.key)?; match map.entry(key_val) { Entry::Vacant(empty_key) => { - let val: Vec = serialize::Deserialize::deserialize(&raw_value)?; + let val: Vec = serialize::Deserialize::deserialize(raw_value)?; if ::hash(&val) != key_val { return Err(pset::Error::InvalidPreimageHashPair { preimage: val, diff --git a/src/pset/map/output.rs b/src/pset/map/output.rs index 6ed45f54..43d72eb4 100644 --- a/src/pset/map/output.rs +++ b/src/pset/map/output.rs @@ -341,7 +341,7 @@ impl Map for Output { } PSET_OUT_PROPRIETARY => { - let prop_key = raw::ProprietaryKey::from_key(raw_key.clone())?; + let prop_key = raw::ProprietaryKey::from_key(&raw_key)?; if prop_key.is_pset_key() { match prop_key.subtype { PSBT_ELEMENTS_OUT_VALUE_COMMITMENT => { diff --git a/src/pset/raw.rs b/src/pset/raw.rs index 2a79528a..a9c84cdf 100644 --- a/src/pset/raw.rs +++ b/src/pset/raw.rs @@ -212,7 +212,7 @@ where { /// Constructs [`ProprietaryKey`] from [Key]; returns /// [`Error::InvalidProprietaryKey`] if `key` do not starts with 0xFC byte - pub fn from_key(key: Key) -> Result { + pub fn from_key(key: &Key) -> Result { if key.type_value != 0xFC { return Err(Error::InvalidProprietaryKey); } From e536bd46acce95e04e83c2d38c58f20d92796e07 Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 17/28] clippy: fix `range_plus_one` lint; eliminates a hidden panic path --- src/script.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/script.rs b/src/script.rs index 2dab973a..0bc034b5 100644 --- a/src/script.rs +++ b/src/script.rs @@ -640,7 +640,7 @@ impl<'a> Iterator for Instructions<'a> { self.data = &[]; return Some(Err(Error::NonMinimalPush)); } - let ret = Some(Ok(Instruction::PushBytes(&self.data[1..n+1]))); + let ret = Some(Ok(Instruction::PushBytes(&self.data[1..=n]))); self.data = &self.data[n + 1..]; ret } From 30c40a39c0785a5d0a0b8a2a6beae9da7668d5da Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 18/28] clippy: fix `redundant_closure_for_method_calls` lint Essentially just a style thing; I think it's nicer to be explicit about what type we're calling methods on, and I think it's nicer to avoid the closure syntax when we can. --- src/blind.rs | 5 +++-- src/pset/map/input.rs | 4 ++-- src/pset/mod.rs | 4 ++-- src/sighash.rs | 2 +- src/taproot.rs | 2 +- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/blind.rs b/src/blind.rs index a81f311d..296b2f2f 100644 --- a/src/blind.rs +++ b/src/blind.rs @@ -715,12 +715,13 @@ impl TxOut { { let value_blind_inputs = spent_utxo_secrets .iter() - .map(|utxo_sec| utxo_sec.value_blind_inputs()) + .map(TxOutSecrets::value_blind_inputs) .collect::>(); let value_blind_outputs = output_secrets .iter() - .map(|e| e.value_blind_inputs()) + .copied() + .map(TxOutSecrets::value_blind_inputs) .collect::>(); let out_vbf = ValueBlindingFactor::last( diff --git a/src/pset/map/input.rs b/src/pset/map/input.rs index 4373fae5..7dd47f68 100644 --- a/src/pset/map/input.rs +++ b/src/pset/map/input.rs @@ -481,7 +481,7 @@ impl Input { self.sighash_type .map_or( Some(EcdsaSighashType::All), - |sighash_type| sighash_type.ecdsa_hash_ty(), + PsbtSighashType::ecdsa_hash_ty, ) } @@ -495,7 +495,7 @@ impl Input { self.sighash_type .map_or( Some(SchnorrSighashType::Default), - |sighash_type| sighash_type.schnorr_hash_ty(), + PsbtSighashType::schnorr_hash_ty, ) } diff --git a/src/pset/mod.rs b/src/pset/mod.rs index f04d44f5..37954d63 100644 --- a/src/pset/mod.rs +++ b/src/pset/mod.rs @@ -296,12 +296,12 @@ impl PartiallySignedTransaction { script_witness: psetin .final_script_witness .as_ref() - .map(|x| x.to_owned()) + .map(Vec::to_owned) .unwrap_or_default(), pegin_witness: psetin .pegin_witness .as_ref() - .map(|x| x.to_owned()) + .map(Vec::to_owned) .unwrap_or_default(), }, }; diff --git a/src/sighash.rs b/src/sighash.rs index 8a5d49b2..551391c5 100644 --- a/src/sighash.rs +++ b/src/sighash.rs @@ -195,7 +195,7 @@ impl Prevouts<'_, T> where T: Borrow { } Prevouts::All(prevouts) => prevouts .get(input_index) - .map(|x| x.borrow()) + .map(T::borrow) .ok_or(Error::PrevoutIndex), } } diff --git a/src/taproot.rs b/src/taproot.rs index 205e9bf8..a848c51f 100644 --- a/src/taproot.rs +++ b/src/taproot.rs @@ -571,7 +571,7 @@ impl TaprootMerkleBranch { /// Serialize self as bytes pub fn serialize(&self) -> Vec { - self.0.iter().flat_map(|e| e.as_byte_array()).copied().collect::>() + self.0.iter().flat_map(sha256::Hash::as_byte_array).copied().collect::>() } // Internal function to append elements to proof From 959f8b929b2be6c3002ed33537965a1857b8efc7 Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 19/28] clippy: fix `redundant_else` lint --- src/blind.rs | 3 +-- src/pset/map/global.rs | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/blind.rs b/src/blind.rs index 296b2f2f..31beacc0 100644 --- a/src/blind.rs +++ b/src/blind.rs @@ -639,9 +639,8 @@ impl TxOut { // unspendable. if self.script_pubkey.is_provably_unspendable() { return Err(TxOutError::ZeroValueCommitment); - } else { - return Err(TxOutError::NonUnspendableZeroValue); } + return Err(TxOutError::NonUnspendableZeroValue); } let asset_comm = self.get_asset_gen(secp)?; Ok(PedersenCommitment::new_unblinded(secp, value, asset_comm)) diff --git a/src/pset/map/global.rs b/src/pset/map/global.rs index 45b26c60..390f2bf4 100644 --- a/src/pset/map/global.rs +++ b/src/pset/map/global.rs @@ -464,9 +464,8 @@ impl Decodable for Global { let scalar = Tweak::from_slice(&prop_key.key)?; if scalars.contains(&scalar) { return Err(Error::DuplicateKey(raw_key).into()); - } else { - scalars.push(scalar); } + scalars.push(scalar); } else { return Err(Error::InvalidKey(raw_key))?; } From 35ee8f36dc6fc006085160453b28b5b8b1174ea8 Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 20/28] clippy: fix `ref_binding_to_reference` lint --- src/encode.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/encode.rs b/src/encode.rs index 39cfb2dc..1a0f09b2 100644 --- a/src/encode.rs +++ b/src/encode.rs @@ -76,7 +76,7 @@ impl fmt::Display for Error { "oversized vector allocation: requested {}, maximum {}", r, m ), - Error::ParseFailed(ref e) => write!(f, "parse failed: {}", e), + Error::ParseFailed(e) => write!(f, "parse failed: {}", e), Error::UnexpectedEOF => write!(f, "unexpected EOF"), Error::InvalidConfidentialPrefix(p) => { write!(f, "invalid confidential prefix: 0x{:02x}", p) From 372d5d6b0c53278df2576dd50468e41cdd6e497c Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 21/28] clippy: fix `return_self_not_must_use` I'm not convinced that any of these are really necessary, but they don't hurt and might save somebody a bug. --- src/address.rs | 2 ++ src/script.rs | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/src/address.rs b/src/address.rs index 155776f9..0480a40b 100644 --- a/src/address.rs +++ b/src/address.rs @@ -437,6 +437,7 @@ impl Address { } /// Convert this address to an unconfidential address. + #[must_use] pub fn to_unconfidential(&self) -> Address { Address { params: self.params, @@ -446,6 +447,7 @@ impl Address { } /// Convert this address to a confidential address with the given blinding pubkey. + #[must_use] pub fn to_confidential(&self, blinding_pubkey: secp256k1_zkp::PublicKey) -> Address { Address { params: self.params, diff --git a/src/script.rs b/src/script.rs index 0bc034b5..ac85402a 100644 --- a/src/script.rs +++ b/src/script.rs @@ -331,6 +331,7 @@ impl Script { pub fn into_bytes(self) -> Vec { self.0.into_vec() } /// Compute the P2SH output corresponding to this redeem script + #[must_use] pub fn to_p2sh(&self) -> Script { Builder::new().push_opcode(opcodes::all::OP_HASH160) .push_slice(&ScriptHash::hash(&self.0)[..]) @@ -340,6 +341,7 @@ impl Script { /// Compute the P2WSH output corresponding to this witnessScript (aka the "witness redeem /// script") + #[must_use] pub fn to_v0_p2wsh(&self) -> Script { Builder::new().push_int(0) .push_slice(&WScriptHash::hash(&self.0)[..]) @@ -741,6 +743,7 @@ impl Builder { /// Adds instructions to push an integer onto the stack. Integers are /// encoded as little-endian signed-magnitude numbers, but there are /// dedicated opcodes to push some small integers. + #[must_use] pub fn push_int(self, data: i64) -> Builder { // We can special-case -1, 1-16 if data == -1 || (data >= 1 && data <= 16) { @@ -759,11 +762,13 @@ impl Builder { /// Adds instructions to push an integer onto the stack, using the explicit /// encoding regardless of the availability of dedicated opcodes. + #[must_use] pub fn push_scriptint(self, data: i64) -> Builder { self.push_slice(&build_scriptint(data)) } /// Adds instructions to push some arbitrary data onto the stack + #[must_use] pub fn push_slice(mut self, data: &[u8]) -> Builder { // Start with a PUSH opcode match data.len() as u64 { @@ -793,6 +798,7 @@ impl Builder { } /// Pushes a public key + #[must_use] pub fn push_key(self, key: &PublicKey) -> Builder { if key.compressed { self.push_slice(&key.inner.serialize()[..]) @@ -802,6 +808,7 @@ impl Builder { } /// Adds a single opcode to the script + #[must_use] pub fn push_opcode(mut self, data: opcodes::All) -> Builder { self.0.push(data.into_u8()); self.1 = Some(data); @@ -811,6 +818,7 @@ impl Builder { /// Adds an `OP_VERIFY` to the script, unless the most-recently-added /// opcode has an alternate `VERIFY` form, in which case that opcode /// is replaced. e.g. `OP_CHECKSIG` will become `OP_CHECKSIGVERIFY`. + #[must_use] pub fn push_verify(mut self) -> Builder { match self.1 { Some(opcodes::all::OP_EQUAL) => { From 64d6853b011ff261034a96e8bd270e52d762cc48 Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 22/28] clippy: fix the `semicolon_if_nothing_returned` lint Just style. --- src/blind.rs | 4 ++-- src/pset/map/global.rs | 4 ++-- src/pset/map/input.rs | 46 +++++++++++++++++++++--------------------- src/pset/map/output.rs | 20 +++++++++--------- src/pset/mod.rs | 6 +++--- src/pset/raw.rs | 2 +- src/pset/serialize.rs | 2 +- src/taproot.rs | 4 ++-- 8 files changed, 44 insertions(+), 44 deletions(-) diff --git a/src/blind.rs b/src/blind.rs index 31beacc0..340e62c5 100644 --- a/src/blind.rs +++ b/src/blind.rs @@ -1009,12 +1009,12 @@ impl Transaction { let gen = Generator::new_unblinded(secp, asset.into_tag()); domain.push(gen); let comm = PedersenCommitment::new_unblinded(secp, *v, gen); - in_commits.push(comm) + in_commits.push(comm); } Value::Confidential(comm) => { let gen = Generator::new_unblinded(secp, asset.into_tag()); domain.push(gen); - in_commits.push(*comm) + in_commits.push(*comm); } } } diff --git a/src/pset/map/global.rs b/src/pset/map/global.rs index 390f2bf4..4f9b0e24 100644 --- a/src/pset/map/global.rs +++ b/src/pset/map/global.rs @@ -268,7 +268,7 @@ impl Map for Global { rv.push(raw::Pair { key: key.to_key(), value: vec![], // This is a bug in elements core c++, parses this value as vec![0] - }) + }); } impl_pset_get_pair! { @@ -437,7 +437,7 @@ impl Decodable for Global { decoder.read_exact(&mut fingerprint[..])?; let mut path = Vec::::with_capacity(child_count); while let Ok(index) = u32::consensus_decode(&mut decoder) { - path.push(ChildNumber::from(index)) + path.push(ChildNumber::from(index)); } let derivation = DerivationPath::from(path); // Keys, according to BIP-174, must be unique diff --git a/src/pset/map/input.rs b/src/pset/map/input.rs index 7dd47f68..72702525 100644 --- a/src/pset/map/input.rs +++ b/src/pset/map/input.rs @@ -534,7 +534,7 @@ impl Input { confidential::Value::Null => {} confidential::Value::Explicit(x) => ret.issuance_inflation_keys = Some(x), confidential::Value::Confidential(comm) => { - ret.issuance_inflation_keys_comm = Some(comm) + ret.issuance_inflation_keys_comm = Some(comm); } } @@ -739,71 +739,71 @@ impl Map for Input { if prop_key.is_pset_key() { match prop_key.subtype { PSBT_ELEMENTS_IN_ISSUANCE_VALUE => { - impl_pset_prop_insert_pair!(self.issuance_value_amount <= | ) + impl_pset_prop_insert_pair!(self.issuance_value_amount <= | ); } PSBT_ELEMENTS_IN_ISSUANCE_VALUE_COMMITMENT => { - impl_pset_prop_insert_pair!(self.issuance_value_comm <= | ) + impl_pset_prop_insert_pair!(self.issuance_value_comm <= | ); } PSBT_ELEMENTS_IN_ISSUANCE_VALUE_RANGEPROOF => { - impl_pset_prop_insert_pair!(self.issuance_value_rangeproof <= | >) + impl_pset_prop_insert_pair!(self.issuance_value_rangeproof <= | >); } PSBT_ELEMENTS_IN_ISSUANCE_KEYS_RANGEPROOF => { - impl_pset_prop_insert_pair!(self.issuance_keys_rangeproof <= | >) + impl_pset_prop_insert_pair!(self.issuance_keys_rangeproof <= | >); } PSBT_ELEMENTS_IN_PEG_IN_TX => { - impl_pset_prop_insert_pair!(self.pegin_tx <= | ) + impl_pset_prop_insert_pair!(self.pegin_tx <= | ); } // No support for TxOutProof struct yet PSBT_ELEMENTS_IN_PEG_IN_TXOUT_PROOF => { - impl_pset_prop_insert_pair!(self.pegin_txout_proof <= | >) + impl_pset_prop_insert_pair!(self.pegin_txout_proof <= | >); } PSBT_ELEMENTS_IN_PEG_IN_GENESIS => { - impl_pset_prop_insert_pair!(self.pegin_genesis_hash <= | ) + impl_pset_prop_insert_pair!(self.pegin_genesis_hash <= | ); } PSBT_ELEMENTS_IN_PEG_IN_CLAIM_SCRIPT => { - impl_pset_prop_insert_pair!(self.pegin_claim_script <= | ) + impl_pset_prop_insert_pair!(self.pegin_claim_script <= | ); } PSBT_ELEMENTS_IN_PEG_IN_VALUE => { - impl_pset_prop_insert_pair!(self.pegin_value <= | ) + impl_pset_prop_insert_pair!(self.pegin_value <= | ); } PSBT_ELEMENTS_IN_PEG_IN_WITNESS => { - impl_pset_prop_insert_pair!(self.pegin_witness <= | >>) + impl_pset_prop_insert_pair!(self.pegin_witness <= | >>); } PSBT_ELEMENTS_IN_ISSUANCE_INFLATION_KEYS => { - impl_pset_prop_insert_pair!(self.issuance_inflation_keys <= | ) + impl_pset_prop_insert_pair!(self.issuance_inflation_keys <= | ); } PSBT_ELEMENTS_IN_ISSUANCE_INFLATION_KEYS_COMMITMENT => { - impl_pset_prop_insert_pair!(self.issuance_inflation_keys_comm <= | ) + impl_pset_prop_insert_pair!(self.issuance_inflation_keys_comm <= | ); } PSBT_ELEMENTS_IN_ISSUANCE_BLINDING_NONCE => { - impl_pset_prop_insert_pair!(self.issuance_blinding_nonce <= | ) + impl_pset_prop_insert_pair!(self.issuance_blinding_nonce <= | ); } PSBT_ELEMENTS_IN_ISSUANCE_ASSET_ENTROPY => { - impl_pset_prop_insert_pair!(self.issuance_asset_entropy <= | ) + impl_pset_prop_insert_pair!(self.issuance_asset_entropy <= | ); } PSBT_ELEMENTS_IN_UTXO_RANGEPROOF => { - impl_pset_prop_insert_pair!(self.in_utxo_rangeproof <= | >) + impl_pset_prop_insert_pair!(self.in_utxo_rangeproof <= | >); } PSBT_ELEMENTS_IN_ISSUANCE_BLIND_VALUE_PROOF => { - impl_pset_prop_insert_pair!(self.in_issuance_blind_value_proof <= | >) + impl_pset_prop_insert_pair!(self.in_issuance_blind_value_proof <= | >); } PSBT_ELEMENTS_IN_ISSUANCE_BLIND_INFLATION_KEYS_PROOF => { - impl_pset_prop_insert_pair!(self.in_issuance_blind_inflation_keys_proof <= | >) + impl_pset_prop_insert_pair!(self.in_issuance_blind_inflation_keys_proof <= | >); } PSBT_ELEMENTS_IN_EXPLICIT_VALUE => { - impl_pset_prop_insert_pair!(self.amount <= | ) + impl_pset_prop_insert_pair!(self.amount <= | ); } PSBT_ELEMENTS_IN_VALUE_PROOF => { - impl_pset_prop_insert_pair!(self.blind_value_proof <= | >) + impl_pset_prop_insert_pair!(self.blind_value_proof <= | >); } PSBT_ELEMENTS_IN_EXPLICIT_ASSET => { - impl_pset_prop_insert_pair!(self.asset <= | ) + impl_pset_prop_insert_pair!(self.asset <= | ); } PSBT_ELEMENTS_IN_ASSET_PROOF => { - impl_pset_prop_insert_pair!(self.blind_asset_proof <= | >) + impl_pset_prop_insert_pair!(self.blind_asset_proof <= | >); } PSBT_ELEMENTS_IN_BLINDED_ISSUANCE => { - impl_pset_prop_insert_pair!(self.blinded_issuance <= | ) + impl_pset_prop_insert_pair!(self.blinded_issuance <= | ); } _ => match self.proprietary.entry(prop_key) { Entry::Vacant(empty_key) => { diff --git a/src/pset/map/output.rs b/src/pset/map/output.rs index 43d72eb4..d86d3389 100644 --- a/src/pset/map/output.rs +++ b/src/pset/map/output.rs @@ -345,34 +345,34 @@ impl Map for Output { if prop_key.is_pset_key() { match prop_key.subtype { PSBT_ELEMENTS_OUT_VALUE_COMMITMENT => { - impl_pset_prop_insert_pair!(self.amount_comm <= | ) + impl_pset_prop_insert_pair!(self.amount_comm <= | ); } PSBT_ELEMENTS_OUT_ASSET => { - impl_pset_prop_insert_pair!(self.asset <= | ) + impl_pset_prop_insert_pair!(self.asset <= | ); } PSBT_ELEMENTS_OUT_ASSET_COMMITMENT => { - impl_pset_prop_insert_pair!(self.asset_comm <= | ) + impl_pset_prop_insert_pair!(self.asset_comm <= | ); } PSBT_ELEMENTS_OUT_VALUE_RANGEPROOF => { - impl_pset_prop_insert_pair!(self.value_rangeproof <= | >) + impl_pset_prop_insert_pair!(self.value_rangeproof <= | >); } PSBT_ELEMENTS_OUT_ASSET_SURJECTION_PROOF => { - impl_pset_prop_insert_pair!(self.asset_surjection_proof <= | >) + impl_pset_prop_insert_pair!(self.asset_surjection_proof <= | >); } PSBT_ELEMENTS_OUT_BLINDING_PUBKEY => { - impl_pset_prop_insert_pair!(self.blinding_key <= | ) + impl_pset_prop_insert_pair!(self.blinding_key <= | ); } PSBT_ELEMENTS_OUT_ECDH_PUBKEY => { - impl_pset_prop_insert_pair!(self.ecdh_pubkey <= | ) + impl_pset_prop_insert_pair!(self.ecdh_pubkey <= | ); } PSBT_ELEMENTS_OUT_BLINDER_INDEX => { - impl_pset_prop_insert_pair!(self.blinder_index <= | ) + impl_pset_prop_insert_pair!(self.blinder_index <= | ); } PSBT_ELEMENTS_OUT_BLIND_VALUE_PROOF => { - impl_pset_prop_insert_pair!(self.blind_value_proof <= | >) + impl_pset_prop_insert_pair!(self.blind_value_proof <= | >); } PSBT_ELEMENTS_OUT_BLIND_ASSET_PROOF => { - impl_pset_prop_insert_pair!(self.blind_asset_proof <= | >) + impl_pset_prop_insert_pair!(self.blind_asset_proof <= | >); } _ => match self.proprietary.entry(prop_key) { Entry::Vacant(empty_key) => { diff --git a/src/pset/mod.rs b/src/pset/mod.rs index 37954d63..532826ec 100644 --- a/src/pset/mod.rs +++ b/src/pset/mod.rs @@ -441,7 +441,7 @@ impl PartiallySignedTransaction { value: 0, // This value really does not matter in surjection proofs value_bf: ValueBlindingFactor::zero(), }; - ret.push(SurjectionInput::from_txout_secrets(secrets)) + ret.push(SurjectionInput::from_txout_secrets(secrets)); } if inp.issuance_inflation_keys.is_some() || inp.issuance_inflation_keys_comm.is_some() @@ -452,7 +452,7 @@ impl PartiallySignedTransaction { value: 0, // This value really does not matter in surjection proofs value_bf: ValueBlindingFactor::zero(), }; - ret.push(SurjectionInput::from_txout_secrets(secrets)) + ret.push(SurjectionInput::from_txout_secrets(secrets)); } } } @@ -688,7 +688,7 @@ impl PartiallySignedTransaction { .map_err(|e| PsetBlindError::BlindingProofsCreationError(last_out_index, e))?, )); - self.global.scalars.clear() + self.global.scalars.clear(); } Ok(()) } diff --git a/src/pset/raw.rs b/src/pset/raw.rs index a9c84cdf..66a4b9a2 100644 --- a/src/pset/raw.rs +++ b/src/pset/raw.rs @@ -152,7 +152,7 @@ impl Encodable for Key { len += self.type_value.consensus_encode(&mut s)?; for key in &self.key { - len += key.consensus_encode(&mut s)? + len += key.consensus_encode(&mut s)?; } Ok(len) diff --git a/src/pset/serialize.rs b/src/pset/serialize.rs index 43719a19..ed8af56c 100644 --- a/src/pset/serialize.rs +++ b/src/pset/serialize.rs @@ -167,7 +167,7 @@ impl Serialize for KeySource { rv.append(&mut self.0.to_bytes().to_vec()); for cnum in &self.1 { - rv.append(&mut serialize(&u32::from(*cnum))) + rv.append(&mut serialize(&u32::from(*cnum))); } rv diff --git a/src/taproot.rs b/src/taproot.rs index a848c51f..7f5940e3 100644 --- a/src/taproot.rs +++ b/src/taproot.rs @@ -932,7 +932,7 @@ mod tests{ for (_weights, script) in script_weights { let ver_script = (script, LeafVersion::default()); let ctrl_block = tree_info.control_block(&ver_script).unwrap(); - assert!(ctrl_block.verify_taproot_commitment(&secp, &output_key, &ver_script.0)) + assert!(ctrl_block.verify_taproot_commitment(&secp, &output_key, &ver_script.0)); } } @@ -971,7 +971,7 @@ mod tests{ for script in scripts { let ver_script = (script, LeafVersion::default()); let ctrl_block = tree_info.control_block(&ver_script).unwrap(); - assert!(ctrl_block.verify_taproot_commitment(&secp, &output_key, &ver_script.0)) + assert!(ctrl_block.verify_taproot_commitment(&secp, &output_key, &ver_script.0)); } } } From c009837a638d46cfa48c86b0379691244820538c Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 23/28] clippy: fix `single_match_else` lint Just style, and apologies for the annoying-to-review diff that moves logic around. But the result is more consistent and (I think) better. --- src/address.rs | 18 +++++------------- src/script.rs | 27 ++++++++++++++++++--------- 2 files changed, 23 insertions(+), 22 deletions(-) diff --git a/src/address.rs b/src/address.rs index 0480a40b..296fa63b 100644 --- a/src/address.rs +++ b/src/address.rs @@ -494,19 +494,11 @@ impl Address { // When blinded, the structure is: // <1: blinding prefix> <1: regular prefix> <33: blinding pubkey> <20: hash160> - let (blinded, prefix) = match data[0] == params.blinded_prefix { - true => { - if data.len() != 55 { - return Err(AddressError::InvalidLength(data.len())); - } - (true, data[1]) - } - false => { - if data.len() != 21 { - return Err(AddressError::InvalidLength(data.len())); - } - (false, data[0]) - } + let blinded = data[0] == params.blinded_prefix; + let prefix = match (blinded, data.len()) { + (true, 55) => data[1], + (false, 21) => data[0], + (_, len) => return Err(AddressError::InvalidLength(len)), }; let (blinding_pubkey, payload_data) = match blinded { diff --git a/src/script.rs b/src/script.rs index ac85402a..27c998b4 100644 --- a/src/script.rs +++ b/src/script.rs @@ -485,9 +485,12 @@ impl Script { f.write_str("")?; break; } - match read_uint(&self.0[index..], 1) { - Ok(n) => { index += 1; n } - Err(_) => { f.write_str("")?; break; } + if let Ok(n) =read_uint(&self.0[index..], 1) { + index += 1; + n + } else { + f.write_str("")?; + break; } } opcodes::all::OP_PUSHDATA2 => { @@ -495,9 +498,12 @@ impl Script { f.write_str("")?; break; } - match read_uint(&self.0[index..], 2) { - Ok(n) => { index += 2; n } - Err(_) => { f.write_str("")?; break; } + if let Ok(n) = read_uint(&self.0[index..], 2) { + index += 2; + n + } else { + f.write_str("")?; + break; } } opcodes::all::OP_PUSHDATA4 => { @@ -505,9 +511,12 @@ impl Script { f.write_str("")?; break; } - match read_uint(&self.0[index..], 4) { - Ok(n) => { index += 4; n } - Err(_) => { f.write_str("")?; break; } + if let Ok(n) = read_uint(&self.0[index..], 4) { + index += 4; + n + } else { + f.write_str("")?; + break; } } _ => 0 From a3149937a3eb98ad8848e92c5756101bd6633f71 Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 24/28] clippy: fix `unnested_or_patterns` pattern Neat! I didn't know about this syntax. Simplifies a lot of opcode matching. --- src/opcodes.rs | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/src/opcodes.rs b/src/opcodes.rs index ef5cc9ca..c050b7a8 100644 --- a/src/opcodes.rs +++ b/src/opcodes.rs @@ -792,16 +792,13 @@ impl All { use self::all::*; match (self, ctx) { // 3 opcodes illegal in all contexts - (OP_VERIF, _) | (OP_VERNOTIF, _) | (OP_INVALIDOPCODE, _) => Class::IllegalOp, + (OP_VERIF | OP_VERNOTIF | OP_INVALIDOPCODE, _) => Class::IllegalOp, // 15 opcodes illegal in Legacy context - (OP_CAT, ctx) | (OP_SUBSTR, ctx) - | (OP_LEFT, ctx) | (OP_RIGHT, ctx) - | (OP_INVERT, ctx) - | (OP_AND, ctx) | (OP_OR, ctx) | (OP_XOR, ctx) - | (OP_2MUL, ctx) | (OP_2DIV, ctx) - | (OP_MUL, ctx) | (OP_DIV, ctx) | (OP_MOD, ctx) - | (OP_LSHIFT, ctx) | (OP_RSHIFT, ctx) if ctx == ClassifyContext::Legacy => Class::IllegalOp, + (OP_CAT | OP_SUBSTR | OP_LEFT | OP_RIGHT + | OP_INVERT | OP_AND | OP_OR | OP_XOR + | OP_2MUL | OP_2DIV | OP_MUL | OP_DIV + | OP_MOD | OP_LSHIFT | OP_RSHIFT, ClassifyContext::Legacy) => Class::IllegalOp, // 87 opcodes of SuccessOp class only in TapScript context (op, ClassifyContext::TapScript) @@ -820,16 +817,13 @@ impl All { (OP_RETURN, _) => Class::ReturnOp, // 4 opcodes operating equally to `OP_RETURN` only in Legacy context - (OP_RESERVED, ctx) - | (OP_RESERVED1, ctx) | (OP_RESERVED2, ctx) - | (OP_VER, ctx) if ctx == ClassifyContext::Legacy => Class::ReturnOp, + (OP_RESERVED | OP_RESERVED1 | OP_RESERVED2 | OP_VER, ClassifyContext::Legacy) => Class::ReturnOp, // 71 opcodes operating equally to `OP_RETURN` only in Legacy context (op, ClassifyContext::Legacy) if op.code >= OP_CHECKSIGADD.code => Class::ReturnOp, // 2 opcodes operating equally to `OP_RETURN` only in TapScript context - (OP_CHECKMULTISIG, ClassifyContext::TapScript) - | (OP_CHECKMULTISIGVERIFY, ClassifyContext::TapScript) => Class::ReturnOp, + (OP_CHECKMULTISIG | OP_CHECKMULTISIGVERIFY, ClassifyContext::TapScript) => Class::ReturnOp, // 1 opcode of PushNum class (OP_PUSHNUM_NEG1, _) => Class::PushNum(-1), From 3ab34e4da8faf3255e5d99b7a8c23450407ef682 Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 25/28] clippy: fix `unreadable_literal` lint I think this is a style improvement. --- src/blech32/mod.rs | 22 +++++++++++----------- src/block.rs | 8 ++++---- src/confidential.rs | 2 +- src/encode.rs | 2 +- src/endian.rs | 2 +- src/ext.rs | 4 ++-- src/script.rs | 16 ++++++++-------- src/sighash.rs | 4 ++-- src/transaction.rs | 24 ++++++++++++------------ 9 files changed, 42 insertions(+), 42 deletions(-) diff --git a/src/blech32/mod.rs b/src/blech32/mod.rs index 69694dd3..c4c2d5e6 100644 --- a/src/blech32/mod.rs +++ b/src/blech32/mod.rs @@ -30,11 +30,11 @@ impl bech32::Checksum for Blech32 { type MidstateRepr = u64; const CHECKSUM_LENGTH: usize = 12; const GENERATOR_SH: [u64; 5] = [ - 0x7d52fba40bd886, - 0x5e8dbf1a03950c, - 0x1c3a3c74072a18, - 0x385d72fa0e5139, - 0x7093e5a608865b, + 0x7d_52fb_a40b_d886, + 0x5e_8dbf_1a03_950c, + 0x1c_3a3c_7407_2a18, + 0x38_5d72_fa0e_5139, + 0x70_93e5_a608_865b, ]; const TARGET_RESIDUE: u64 = 1; @@ -49,13 +49,13 @@ impl bech32::Checksum for Blech32m { type MidstateRepr = u64; const CHECKSUM_LENGTH: usize = 12; const GENERATOR_SH: [u64; 5] = [ - 0x7d52fba40bd886, - 0x5e8dbf1a03950c, - 0x1c3a3c74072a18, - 0x385d72fa0e5139, - 0x7093e5a608865b, + 0x7d_52fb_a40b_d886, + 0x5e_8dbf_1a03_950c, + 0x1c_3a3c_7407_2a18, + 0x38_5d72_fa0e_5139, + 0x70_93e5_a608_865b, ]; - const TARGET_RESIDUE: u64 = 0x455972a3350f7a1; + const TARGET_RESIDUE: u64 = 0x455_972a_3350_f7a1; const CODE_LENGTH: usize = 1024; } diff --git a/src/block.rs b/src/block.rs index e6728976..f16f790f 100644 --- a/src/block.rs +++ b/src/block.rs @@ -463,7 +463,7 @@ mod tests { block.block_hash().to_string(), "287ca47e8da47eb8c28d870663450bb026922eadb30a1b2f8293e6e9d1ca5322" ); - assert_eq!(block.header.version, 0x20000000); + assert_eq!(block.header.version, 0x2000_0000); assert_eq!(block.header.height, 2); assert_eq!(block.txdata.len(), 1); assert_eq!(block.size(), serialize(&block).len()); @@ -675,7 +675,7 @@ mod tests { block.block_hash().to_string(), "e935d06cf3a616eb4d551338598b84daa0e8592ed14673263597f6af4b4a6ea6" ); - assert_eq!(block.header.version, 0x20000000); + assert_eq!(block.header.version, 0x2000_0000); assert_eq!(block.header.height, 1); assert_eq!(block.txdata.len(), 3); assert_eq!(block.size(), serialize(&block).len()); @@ -706,7 +706,7 @@ mod tests { block.block_hash().to_string(), "bcc6eb2ab6c97b9b4590825b9136f100b22e090c0469818572b8b93926a79f28" ); - assert_eq!(block.header.version, 0x20000000); + assert_eq!(block.header.version, 0x2000_0000); if let ExtData::Proof { challenge, solution } = block.header.ext { assert_eq!(challenge.len(), 1 + 3 * 34 + 2); assert_eq!(solution.len(), 144); @@ -740,7 +740,7 @@ mod tests { block.block_hash().to_string(), "4961df970cf12d789383974e6ab439f780d956b5a50162ca9d281362e46c605a" ); - assert_eq!(block.header.version, 0x20000000); + assert_eq!(block.header.version, 0x2000_0000); // Full current and proposal let block: Block = hex_deserialize!("\ diff --git a/src/confidential.rs b/src/confidential.rs index df358aa9..34f1a564 100644 --- a/src/confidential.rs +++ b/src/confidential.rs @@ -1168,7 +1168,7 @@ mod tests { &[ Token::Seq { len: Some(2) }, Token::U8(1), - Token::U64(63601271583539200), + Token::U64(63_601_271_583_539_200), Token::SeqEnd ] ); diff --git a/src/encode.rs b/src/encode.rs index 1a0f09b2..6868cee2 100644 --- a/src/encode.rs +++ b/src/encode.rs @@ -260,7 +260,7 @@ impl VarInt { match self.0 { 0..=0xFC => 1, 0xFD..=0xFFFF => 3, - 0x10000..=0xFFFFFFFF => 5, + 0x10000..=0xFFFF_FFFF => 5, _ => 9, } } diff --git a/src/endian.rs b/src/endian.rs index 6a009281..fec6eed9 100644 --- a/src/endian.rs +++ b/src/endian.rs @@ -20,6 +20,6 @@ mod tests { #[test] fn endianness_test() { - assert_eq!(u32_to_array_le(0xdeadbeef), [0xef, 0xbe, 0xad, 0xde]); + assert_eq!(u32_to_array_le(0xdead_beef), [0xef, 0xbe, 0xad, 0xde]); } } diff --git a/src/ext.rs b/src/ext.rs index b293db3a..d70e1556 100644 --- a/src/ext.rs +++ b/src/ext.rs @@ -119,7 +119,7 @@ impl WriteExt for W { self.emit_u16(i as u16)?; Ok(3) } - i @ 0x10000..=0xFFFFFFFF => { + i @ 0x10000..=0xFFFF_FFFF => { self.emit_u8(0xFE)?; self.emit_u32(i as u32)?; Ok(5) @@ -166,7 +166,7 @@ impl ReadExt for R { match self.read_u8()? { 0xFF => { let x = self.read_u64()?; - if x < 0x100000000 { + if x < 0x1_0000_0000 { Err(encode::Error::NonMinimalVarInt) } else { Ok(x) diff --git a/src/script.rs b/src/script.rs index 27c998b4..81adcba1 100644 --- a/src/script.rs +++ b/src/script.rs @@ -786,17 +786,17 @@ impl Builder { self.0.push(opcodes::Ordinary::OP_PUSHDATA1.into_u8()); self.0.push(n as u8); }, - n if n < 0x10000 => { + n if n < 0x1_0000 => { self.0.push(opcodes::Ordinary::OP_PUSHDATA2.into_u8()); self.0.push((n % 0x100) as u8); self.0.push((n / 0x100) as u8); }, - n if n < 0x100000000 => { + n if n < 0x1_0000_0000 => { self.0.push(opcodes::Ordinary::OP_PUSHDATA4.into_u8()); self.0.push((n % 0x100) as u8); self.0.push(((n / 0x100) % 0x100) as u8); - self.0.push(((n / 0x10000) % 0x100) as u8); - self.0.push((n / 0x1000000) as u8); + self.0.push(((n / 0x1_0000) % 0x100) as u8); + self.0.push((n / 0x100_0000) as u8); } _ => panic!("tried to put a 4bn+ sized object into a script!") } @@ -977,10 +977,10 @@ mod test { script = script.push_scriptint(4); comp.extend([1u8, 4].iter().copied()); assert_eq!(&script[..], &comp[..]); // big ints script = script.push_int(17); comp.extend([1u8, 17].iter().copied()); assert_eq!(&script[..], &comp[..]); - script = script.push_int(10000); comp.extend([2u8, 16, 39].iter().copied()); assert_eq!(&script[..], &comp[..]); + script = script.push_int(10_000); comp.extend([2u8, 16, 39].iter().copied()); assert_eq!(&script[..], &comp[..]); // notice the sign bit set here, hence the extra zero/128 at the end - script = script.push_int(10000000); comp.extend([4u8, 128, 150, 152, 0].iter().copied()); assert_eq!(&script[..], &comp[..]); - script = script.push_int(-10000000); comp.extend([4u8, 128, 150, 152, 128].iter().copied()); assert_eq!(&script[..], &comp[..]); + script = script.push_int(10_000_000); comp.extend([4u8, 128, 150, 152, 0].iter().copied()); assert_eq!(&script[..], &comp[..]); + script = script.push_int(-10_000_000); comp.extend([4u8, 128, 150, 152, 128].iter().copied()); assert_eq!(&script[..], &comp[..]); // data script = script.push_slice(b"NRA4VR"); comp.extend([6u8, 78, 82, 65, 52, 86, 82].iter().copied()); assert_eq!(&script[..], &comp[..]); @@ -1097,7 +1097,7 @@ mod test { assert_eq!(build_scriptint(256), vec![0, 1]); assert_eq!(build_scriptint(257), vec![1, 1]); assert_eq!(build_scriptint(511), vec![255, 1]); - for &i in &[10, 100, 255, 256, 1000, 10000, 25000, 200000, 5000000, 1000000000, + for &i in &[10, 100, 255, 256, 1000, 10000, 25000, 200_000, 5_000_000, 1_000_000_000, (1 << 31) - 1, -((1 << 31) - 1)] { assert_eq!(Ok(i), read_scriptint(&build_scriptint(i))); assert_eq!(Ok(-i), read_scriptint(&build_scriptint(-i))); diff --git a/src/sighash.rs b/src/sighash.rs index 551391c5..14461ddc 100644 --- a/src/sighash.rs +++ b/src/sighash.rs @@ -212,7 +212,7 @@ impl<'s> ScriptPath<'s> { } /// Create a new `ScriptPath` structure using default values for `code_separator_pos` and `leaf_version` pub fn with_defaults(script: &'s Script) -> Self { - Self::new(script, 0xFFFFFFFFu32, 0xc4) + Self::new(script, 0xFFFF_FFFFu32, 0xc4) } /// Compute the leaf hash @@ -483,7 +483,7 @@ impl> SighashCache { input_index, prevouts, None, - Some((leaf_hash.into(), 0xFFFFFFFF)), + Some((leaf_hash.into(), 0xFFFF_FFFF)), sighash_type, genesis_hash )?; diff --git a/src/transaction.rs b/src/transaction.rs index b004309e..ae012df8 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -187,7 +187,7 @@ impl Sequence { /// The maximum allowable sequence number. /// /// This sequence number disables lock-time and replace-by-fee. - pub const MAX: Self = Sequence(0xFFFFFFFF); + pub const MAX: Self = Sequence(0xFFFF_FFFF); /// Zero value sequence. /// /// This sequence number enables replace-by-fee and lock-time. @@ -197,7 +197,7 @@ impl Sequence { pub const ENABLE_LOCKTIME_NO_RBF: Self = Sequence::MIN_NO_RBF; /// The sequence number that enables replace-by-fee and absolute lock-time but /// disables relative lock-time. - pub const ENABLE_RBF_NO_LOCKTIME: Self = Sequence(0xFFFFFFFD); + pub const ENABLE_RBF_NO_LOCKTIME: Self = Sequence(0xFFFF_FFFD); /// The lowest sequence number that does not opt-in for replace-by-fee. /// @@ -206,11 +206,11 @@ impl Sequence { /// (Explicit Signalling [BIP-125]). /// /// [BIP-125]: - const MIN_NO_RBF: Self = Sequence(0xFFFFFFFE); + const MIN_NO_RBF: Self = Sequence(0xFFFF_FFFE); /// BIP-68 relative lock-time disable flag mask - const LOCK_TIME_DISABLE_FLAG_MASK: u32 = 0x80000000; + const LOCK_TIME_DISABLE_FLAG_MASK: u32 = 0x8000_0000; /// BIP-68 relative lock-time type flag mask - const LOCK_TYPE_MASK: u32 = 0x00400000; + const LOCK_TYPE_MASK: u32 = 0x0040_0000; /// Returns `true` if the sequence number indicates that the transaction is finalised. /// @@ -545,7 +545,7 @@ impl Decodable for TxIn { let has_issuance; // Pegin/issuance flags are encoded into the high bits of `vout`, *except* // if vout is all 1's; this indicates a coinbase transaction - if outp.vout == 0xffffffff { + if outp.vout == 0xffff_ffff { is_pegin = false; has_issuance = false; } else { @@ -1373,10 +1373,10 @@ mod tests { assert_eq!(tx.weight(), tx.size() * 4); assert!(!tx.output[0].is_fee()); assert!(tx.output[1].is_fee()); - assert_eq!(tx.output[0].value, confidential::Value::Explicit(9999996700)); - assert_eq!(tx.output[1].value, confidential::Value::Explicit( 3300)); - assert_eq!(tx.output[0].minimum_value(), 9999996700); - assert_eq!(tx.output[1].minimum_value(), 3300); + assert_eq!(tx.output[0].value, confidential::Value::Explicit(9_999_996_700)); + assert_eq!(tx.output[1].value, confidential::Value::Explicit(3300)); + assert_eq!(tx.output[0].minimum_value(), 9_999_996_700); + assert_eq!(tx.output[1].minimum_value(), 3300); let fee_asset = "b2e15d0d7a0c94e4e2ce0fe6e8691b9e451377f6e46e8045a86f7c4b5d4f0f23".parse().unwrap(); assert_eq!(tx.fee_in(fee_asset), 3300); assert_eq!(tx.all_fees()[&fee_asset], 3300); @@ -1688,7 +1688,7 @@ mod tests { ).unwrap(), vout: 0, }, - value: 100000000, + value: 100_000_000, asset: tx.output[0].asset.explicit().unwrap(), genesis_hash: bitcoin::BlockHash::from_str( "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206" @@ -1803,7 +1803,7 @@ mod tests { tx.output[0].pegout_data(), Some(super::PegoutData { asset: tx.output[0].asset, - value: 99993900, + value: 99_993_900, genesis_hash: bitcoin::BlockHash::from_str( "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206" ).unwrap(), From 0fd22466d60a05490e57013c0d60f7460d3dd3bf Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 23:33:23 +0000 Subject: [PATCH 26/28] clippy: whitelist one instance of `clippy::wildcard-imports` lint --- src/opcodes.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/opcodes.rs b/src/opcodes.rs index c050b7a8..fb8648c4 100644 --- a/src/opcodes.rs +++ b/src/opcodes.rs @@ -788,6 +788,7 @@ pub enum ClassifyContext { impl All { /// Classifies an Opcode into a broad class. #[inline] + #[allow(clippy::wildcard_imports)] // ok to import all the opcodes with all::* pub fn classify(self, ctx: ClassifyContext) -> Class { use self::all::*; match (self, ctx) { From d68dee5545056a69bda3a1b192711a2bd96e995a Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Wed, 25 Jun 2025 22:17:41 +0000 Subject: [PATCH 27/28] clippy: fix `enum_glob_use` lint --- src/blech32/decode.rs | 166 ++++++++++++++++++------------------------ src/locktime.rs | 60 ++++++--------- 2 files changed, 94 insertions(+), 132 deletions(-) diff --git a/src/blech32/decode.rs b/src/blech32/decode.rs index 45a31d3d..93dfb2d9 100644 --- a/src/blech32/decode.rs +++ b/src/blech32/decode.rs @@ -138,7 +138,7 @@ impl<'s> UncheckedHrpstring<'s> { /// checksum if `NoChecksum` is used). #[inline] pub fn validate_checksum(&self) -> Result<(), ChecksumError> { - use ChecksumError::*; + use ChecksumError as E; if Ck::CHECKSUM_LENGTH == 0 { // Called with NoChecksum @@ -146,7 +146,7 @@ impl<'s> UncheckedHrpstring<'s> { } if self.data.len() < Ck::CHECKSUM_LENGTH { - return Err(InvalidChecksumLength); + return Err(E::InvalidChecksumLength); } let mut checksum_eng = checksum::Engine::::new(); @@ -158,7 +158,7 @@ impl<'s> UncheckedHrpstring<'s> { } if checksum_eng.residue() != &Ck::TARGET_RESIDUE { - return Err(InvalidChecksum); + return Err(E::InvalidChecksum); } Ok(()) @@ -405,7 +405,7 @@ impl<'s> SegwitHrpstring<'s> { /// /// The byte-index into the string where the '1' separator occurs, or an error if it does not. fn check_characters(s: &str) -> Result { - use CharError::*; + use CharError as E; let mut has_upper = false; let mut has_lower = false; @@ -417,7 +417,7 @@ fn check_characters(s: &str) -> Result { sep_pos = Some(n); } if req_bech32 { - Fe32::from_char(ch).map_err(|_| InvalidChar(ch))?; + Fe32::from_char(ch).map_err(|_| E::InvalidChar(ch))?; } if ch.is_ascii_uppercase() { has_upper = true; @@ -426,11 +426,11 @@ fn check_characters(s: &str) -> Result { } } if has_upper && has_lower { - Err(MixedCase) + Err(E::MixedCase) } else if let Some(pos) = sep_pos { Ok(pos) } else { - Err(MissingSeparator) + Err(E::MissingSeparator) } } @@ -505,29 +505,25 @@ pub enum SegwitHrpstringError { impl fmt::Display for SegwitHrpstringError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use SegwitHrpstringError::*; - match *self { - Unchecked(ref e) => write_err!(f, "parsing unchecked hrpstring failed"; e), - MissingWitnessVersion => write!(f, "the witness version byte is missing"), - InvalidWitnessVersion(fe) => write!(f, "invalid segwit witness version: {}", fe.to_u8()), - Padding(ref e) => write_err!(f, "invalid padding on the witness data"; e), - WitnessLength(ref e) => write_err!(f, "invalid witness length"; e), - Checksum(ref e) => write_err!(f, "invalid checksum"; e), + Self::Unchecked(ref e) => write_err!(f, "parsing unchecked hrpstring failed"; e), + Self::MissingWitnessVersion => write!(f, "the witness version byte is missing"), + Self::InvalidWitnessVersion(fe) => write!(f, "invalid segwit witness version: {}", fe.to_u8()), + Self::Padding(ref e) => write_err!(f, "invalid padding on the witness data"; e), + Self::WitnessLength(ref e) => write_err!(f, "invalid witness length"; e), + Self::Checksum(ref e) => write_err!(f, "invalid checksum"; e), } } } impl std::error::Error for SegwitHrpstringError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - use SegwitHrpstringError::*; - match *self { - Unchecked(ref e) => Some(e), - Padding(ref e) => Some(e), - WitnessLength(ref e) => Some(e), - Checksum(ref e) => Some(e), - MissingWitnessVersion | InvalidWitnessVersion(_) => None, + Self::Unchecked(ref e) => Some(e), + Self::Padding(ref e) => Some(e), + Self::WitnessLength(ref e) => Some(e), + Self::Checksum(ref e) => Some(e), + Self::MissingWitnessVersion | Self::InvalidWitnessVersion(_) => None, } } } @@ -564,22 +560,18 @@ pub enum CheckedHrpstringError { impl fmt::Display for CheckedHrpstringError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use CheckedHrpstringError::*; - match *self { - Parse(ref e) => write_err!(f, "parse failed"; e), - Checksum(ref e) => write_err!(f, "invalid checksum"; e), + Self::Parse(ref e) => write_err!(f, "parse failed"; e), + Self::Checksum(ref e) => write_err!(f, "invalid checksum"; e), } } } impl std::error::Error for CheckedHrpstringError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - use CheckedHrpstringError::*; - match *self { - Parse(ref e) => Some(e), - Checksum(ref e) => Some(e), + Self::Parse(ref e) => Some(e), + Self::Checksum(ref e) => Some(e), } } } @@ -606,22 +598,18 @@ pub enum UncheckedHrpstringError { impl fmt::Display for UncheckedHrpstringError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use UncheckedHrpstringError::*; - match *self { - Char(ref e) => write_err!(f, "character error"; e), - Hrp(ref e) => write_err!(f, "invalid human-readable part"; e), + Self::Char(ref e) => write_err!(f, "character error"; e), + Self::Hrp(ref e) => write_err!(f, "invalid human-readable part"; e), } } } impl std::error::Error for UncheckedHrpstringError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - use UncheckedHrpstringError::*; - match *self { - Char(ref e) => Some(e), - Hrp(ref e) => Some(e), + Self::Char(ref e) => Some(e), + Self::Hrp(ref e) => Some(e), } } } @@ -656,30 +644,26 @@ pub enum CharError { impl fmt::Display for CharError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use CharError::*; - match *self { - MissingSeparator => write!(f, "missing human-readable separator, \"{}\"", SEP), - NothingAfterSeparator => write!(f, "invalid data - no characters after the separator"), - InvalidChecksum => write!(f, "invalid checksum"), - InvalidChecksumLength => write!(f, "the checksum is not a valid length"), - InvalidChar(n) => write!(f, "invalid character (code={})", n), - MixedCase => write!(f, "mixed-case strings not allowed"), + Self::MissingSeparator => write!(f, "missing human-readable separator, \"{}\"", SEP), + Self::NothingAfterSeparator => write!(f, "invalid data - no characters after the separator"), + Self::InvalidChecksum => write!(f, "invalid checksum"), + Self::InvalidChecksumLength => write!(f, "the checksum is not a valid length"), + Self::InvalidChar(n) => write!(f, "invalid character (code={})", n), + Self::MixedCase => write!(f, "mixed-case strings not allowed"), } } } impl std::error::Error for CharError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - use CharError::*; - match *self { - MissingSeparator - | NothingAfterSeparator - | InvalidChecksum - | InvalidChecksumLength - | InvalidChar(_) - | MixedCase => None, + Self::MissingSeparator + | Self::NothingAfterSeparator + | Self::InvalidChecksum + | Self::InvalidChecksumLength + | Self::InvalidChar(_) + | Self::MixedCase => None, } } } @@ -696,21 +680,17 @@ pub enum ChecksumError { impl fmt::Display for ChecksumError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use ChecksumError::*; - match *self { - InvalidChecksum => write!(f, "invalid checksum"), - InvalidChecksumLength => write!(f, "the checksum is not a valid length"), + Self::InvalidChecksum => write!(f, "invalid checksum"), + Self::InvalidChecksumLength => write!(f, "the checksum is not a valid length"), } } } impl std::error::Error for ChecksumError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - use ChecksumError::*; - match *self { - InvalidChecksum | InvalidChecksumLength => None, + Self::InvalidChecksum | Self::InvalidChecksumLength => None, } } } @@ -727,21 +707,17 @@ pub enum PaddingError { impl fmt::Display for PaddingError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use PaddingError::*; - match *self { - TooMuch => write!(f, "the data payload has too many bits of padding"), - NonZero => write!(f, "the data payload is padded with non-zero bits"), + Self::TooMuch => write!(f, "the data payload has too many bits of padding"), + Self::NonZero => write!(f, "the data payload is padded with non-zero bits"), } } } impl std::error::Error for PaddingError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - use PaddingError::*; - match *self { - TooMuch | NonZero => None, + Self::TooMuch | Self::NonZero => None, } } } @@ -752,32 +728,32 @@ mod tests { #[test] fn bip_173_invalid_parsing_fails() { - use UncheckedHrpstringError::*; + use UncheckedHrpstringError as E; let invalid: Vec<(&str, UncheckedHrpstringError)> = vec!( ("\u{20}1nwldj5", // TODO: Rust >= 1.59.0 use Hrp(hrp::Error::InvalidAsciiByte('\u{20}'.try_into().unwrap()))), - Hrp(hrp::Error::InvalidAsciiByte(32))), + E::Hrp(hrp::Error::InvalidAsciiByte(32))), ("\u{7F}1axkwrx", - Hrp(hrp::Error::InvalidAsciiByte(127))), + E::Hrp(hrp::Error::InvalidAsciiByte(127))), ("\u{80}1eym55h", - Hrp(hrp::Error::NonAsciiChar('\u{80}'))), + E::Hrp(hrp::Error::NonAsciiChar('\u{80}'))), ("an84characterslonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11d6pts4", - Hrp(hrp::Error::TooLong(84))), + E::Hrp(hrp::Error::TooLong(84))), ("pzry9x0s0muk", - Char(CharError::MissingSeparator)), + E::Char(CharError::MissingSeparator)), ("1pzry9x0s0muk", - Hrp(hrp::Error::Empty)), + E::Hrp(hrp::Error::Empty)), ("x1b4n0q5v", - Char(CharError::InvalidChar('b'))), + E::Char(CharError::InvalidChar('b'))), // "li1dgmt3" in separate test because error is a checksum error. ("de1lg7wt\u{ff}", - Char(CharError::InvalidChar('\u{ff}'))), + E::Char(CharError::InvalidChar('\u{ff}'))), // "A1G7SGD8" in separate test because error is a checksum error. ("10a06t8", - Hrp(hrp::Error::Empty)), + E::Hrp(hrp::Error::Empty)), ("1qzzfhee", - Hrp(hrp::Error::Empty)), + E::Hrp(hrp::Error::Empty)), ); for (s, want) in invalid { @@ -789,54 +765,54 @@ mod tests { /* #[test] fn bip_173_invalid_parsing_fails_invalid_checksum() { - use ChecksumError::*; + use ChecksumError as E; let err = UncheckedHrpstring::new("li1dgmt3") .expect("string parses correctly") .validate_checksum::() .unwrap_err(); - assert_eq!(err, InvalidChecksumLength); + assert_eq!(err, E::InvalidChecksumLength); let err = UncheckedHrpstring::new("A1G7SGD8") .expect("string parses correctly") .validate_checksum::() .unwrap_err(); - assert_eq!(err, InvalidChecksum); + assert_eq!(err, E::InvalidChecksum); } */ #[test] fn bip_350_invalid_parsing_fails() { - use UncheckedHrpstringError::*; + use UncheckedHrpstringError as E; let invalid: Vec<(&str, UncheckedHrpstringError)> = vec!( ("\u{20}1xj0phk", // TODO: Rust >= 1.59.0 use Hrp(hrp::Error::InvalidAsciiByte('\u{20}'.try_into().unwrap()))), - Hrp(hrp::Error::InvalidAsciiByte(32))), + E::Hrp(hrp::Error::InvalidAsciiByte(32))), ("\u{7F}1g6xzxy", - Hrp(hrp::Error::InvalidAsciiByte(127))), + E::Hrp(hrp::Error::InvalidAsciiByte(127))), ("\u{80}1g6xzxy", - Hrp(hrp::Error::NonAsciiChar('\u{80}'))), + E::Hrp(hrp::Error::NonAsciiChar('\u{80}'))), ("an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx", - Hrp(hrp::Error::TooLong(84))), + E::Hrp(hrp::Error::TooLong(84))), ("qyrz8wqd2c9m", - Char(CharError::MissingSeparator)), + E::Char(CharError::MissingSeparator)), ("1qyrz8wqd2c9m", - Hrp(hrp::Error::Empty)), + E::Hrp(hrp::Error::Empty)), ("y1b0jsk6g", - Char(CharError::InvalidChar('b'))), + E::Char(CharError::InvalidChar('b'))), ("lt1igcx5c0", - Char(CharError::InvalidChar('i'))), + E::Char(CharError::InvalidChar('i'))), // "in1muywd" in separate test because error is a checksum error. ("mm1crxm3i", - Char(CharError::InvalidChar('i'))), + E::Char(CharError::InvalidChar('i'))), ("au1s5cgom", - Char(CharError::InvalidChar('o'))), + E::Char(CharError::InvalidChar('o'))), // "M1VUXWEZ" in separate test because error is a checksum error. ("16plkw9", - Hrp(hrp::Error::Empty)), + E::Hrp(hrp::Error::Empty)), ("1p2gdwpf", - Hrp(hrp::Error::Empty)), + E::Hrp(hrp::Error::Empty)), ); diff --git a/src/locktime.rs b/src/locktime.rs index e06786ef..e93f10b6 100644 --- a/src/locktime.rs +++ b/src/locktime.rs @@ -54,13 +54,13 @@ pub const LOCK_TIME_THRESHOLD: u32 = 500_000_000; /// /// # Examples /// ``` -/// # use elements::{LockTime, LockTime::*}; +/// # use elements::LockTime; /// # let n = LockTime::from_consensus(100); // n OP_CHECKLOCKTIMEVERIFY /// # let lock_time = LockTime::from_consensus(100); // nLockTime /// // To compare lock times there are various `is_satisfied_*` methods, you may also use: /// let is_satisfied = match (n, lock_time) { -/// (Blocks(n), Blocks(lock_time)) => n <= lock_time, -/// (Seconds(n), Seconds(lock_time)) => n <= lock_time, +/// (LockTime::Blocks(n), LockTime::Blocks(lock_time)) => n <= lock_time, +/// (LockTime::Seconds(n), LockTime::Seconds(lock_time)) => n <= lock_time, /// _ => panic!("handle invalid comparison error"), /// }; /// ``` @@ -197,11 +197,9 @@ impl LockTime { /// ```` #[inline] pub fn is_satisfied_by(&self, height: Height, time: Time) -> bool { - use LockTime::*; - match *self { - Blocks(n) => n <= height, - Seconds(n) => n <= time, + LockTime::Blocks(n) => n <= height, + LockTime::Seconds(n) => n <= time, } } @@ -216,13 +214,13 @@ impl LockTime { /// # Examples /// /// ```rust - /// # use elements::{LockTime, LockTime::*}; + /// # use elements::LockTime; /// # let n = LockTime::from_consensus(100); // n OP_CHECKLOCKTIMEVERIFY /// # let lock_time = LockTime::from_consensus(100); // nLockTime /// /// let is_satisfied = match (n, lock_time) { - /// (Blocks(n), Blocks(lock_time)) => n <= lock_time, - /// (Seconds(n), Seconds(lock_time)) => n <= lock_time, + /// (LockTime::Blocks(n), LockTime::Blocks(lock_time)) => n <= lock_time, + /// (LockTime::Seconds(n), LockTime::Seconds(lock_time)) => n <= lock_time, /// _ => panic!("invalid comparison"), /// }; /// @@ -254,11 +252,9 @@ impl From