What changed, and why it matters
This commit only turns on a Rust style lint (clippy::use_self) and rewrites code to use `Self` instead of repeating type names. It does not change any behavior, logic, or security properties of the library.
No security action needed. This is a code-style/linting change. Reviewers can verify it is purely mechanical and that CI passes with the new lint enabled.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The patch adds use_self = "warn" under [lints.clippy] in bitcoin/Cargo.toml and bitcoin/embedded/Cargo.toml, then mechanically replaces explicit type names with Self across 43 source files. Examples include constructors returning Self, match arms using Self::Variant, and From/TryFrom impls using Self. There are no algorithmic, API, or safety changes.
Changed components
bitcoin/Cargo.tomlbitcoin/embedded/Cargo.tomlbitcoin/src/**/*.rsInspect captured patch +509 / −523
diff --git a/bitcoin/Cargo.toml b/bitcoin/Cargo.toml
index 1556c1d6..12e4e289 100644
--- a/bitcoin/Cargo.toml
+++ b/bitcoin/Cargo.toml
@@ -101,3 +101,6 @@ required-features = ["std", "serde"]
[lints.rust]
unexpected_cfgs = { level = "deny", check-cfg = ['cfg(fuzzing)', 'cfg(kani)'] }
+
+[lints.clippy]
+use_self = "warn"
diff --git a/bitcoin/embedded/Cargo.toml b/bitcoin/embedded/Cargo.toml
index 8a6f7ecb..fdf2c69f 100644
--- a/bitcoin/embedded/Cargo.toml
+++ b/bitcoin/embedded/Cargo.toml
@@ -15,6 +15,9 @@ cortex-m-semihosting = "0.3.3"
alloc-cortex-m = "0.4.1"
bitcoin = { path="../", default-features = false, features = ["secp-lowmemory"] }
+[lints.clippy]
+use_self = "warn"
+
[[bin]]
name = "embedded"
test = false
diff --git a/bitcoin/examples/ecdsa-psbt.rs b/bitcoin/examples/ecdsa-psbt.rs
index 868030c8..10d9abe4 100644
--- a/bitcoin/examples/ecdsa-psbt.rs
+++ b/bitcoin/examples/ecdsa-psbt.rs
@@ -124,7 +124,7 @@ impl ColdStorage {
let input_xpriv = master_xpriv.derive_xpriv(secp, &path).expect("derivation path is short");
let input_xpub = Xpub::from_xpriv(secp, &input_xpriv);
- let wallet = ColdStorage { master_xpriv, master_xpub };
+ let wallet = Self { master_xpriv, master_xpub };
let fingerprint = wallet.master_fingerprint();
Ok((wallet, fingerprint, account_0_xpub, input_xpub))
@@ -169,7 +169,7 @@ impl WatchOnly {
/// The reason for importing the `input_xpub` is so one can use bitcoind to grab a valid input
/// to verify the workflow presented in this file.
fn new(account_0_xpub: Xpub, input_xpub: Xpub, master_fingerprint: Fingerprint) -> Self {
- WatchOnly { account_0_xpub, input_xpub, master_fingerprint }
+ Self { account_0_xpub, input_xpub, master_fingerprint }
}
/// Creates the PSBT, in BIP-0174 parlance this is the 'Creator'.
@@ -284,7 +284,7 @@ fn previous_output() -> TxOut {
struct Error(Box<dyn std::error::Error>);
impl<T: std::error::Error + 'static> From<T> for Error {
- fn from(e: T) -> Self { Error(Box::new(e)) }
+ fn from(e: T) -> Self { Self(Box::new(e)) }
}
impl fmt::Debug for Error {
diff --git a/bitcoin/src/address/error.rs b/bitcoin/src/address/error.rs
index f1479425..a0d5fd46 100644
--- a/bitcoin/src/address/error.rs
+++ b/bitcoin/src/address/error.rs
@@ -125,7 +125,7 @@ impl From<Bech32Error> for ParseError {
}
impl From<UnknownHrpError> for ParseError {
- fn from(e: UnknownHrpError) -> ParseError { Self::Bech32(e.into()) }
+ fn from(e: UnknownHrpError) -> Self { Self::Bech32(e.into()) }
}
impl From<NetworkValidationError> for ParseError {
diff --git a/bitcoin/src/address/mod.rs b/bitcoin/src/address/mod.rs
index d065105f..3f7b6640 100644
--- a/bitcoin/src/address/mod.rs
+++ b/bitcoin/src/address/mod.rs
@@ -99,12 +99,12 @@ pub enum AddressType {
impl fmt::Display for AddressType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match *self {
- AddressType::P2pkh => "p2pkh",
- AddressType::P2sh => "p2sh",
- AddressType::P2wpkh => "p2wpkh",
- AddressType::P2wsh => "p2wsh",
- AddressType::P2tr => "p2tr",
- AddressType::P2a => "p2a",
+ Self::P2pkh => "p2pkh",
+ Self::P2sh => "p2sh",
+ Self::P2wpkh => "p2wpkh",
+ Self::P2wsh => "p2wsh",
+ Self::P2tr => "p2tr",
+ Self::P2a => "p2a",
})
}
}
@@ -113,12 +113,12 @@ impl FromStr for AddressType {
type Err = UnknownAddressTypeError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
- "p2pkh" => Ok(AddressType::P2pkh),
- "p2sh" => Ok(AddressType::P2sh),
- "p2wpkh" => Ok(AddressType::P2wpkh),
- "p2wsh" => Ok(AddressType::P2wsh),
- "p2tr" => Ok(AddressType::P2tr),
- "p2a" => Ok(AddressType::P2a),
+ "p2pkh" => Ok(Self::P2pkh),
+ "p2sh" => Ok(Self::P2sh),
+ "p2wpkh" => Ok(Self::P2wpkh),
+ "p2wsh" => Ok(Self::P2wsh),
+ "p2tr" => Ok(Self::P2tr),
+ "p2a" => Ok(Self::P2a),
_ => Err(UnknownAddressTypeError(s.to_owned())),
}
}
@@ -279,9 +279,9 @@ impl From<Network> for KnownHrp {
impl From<KnownHrp> for NetworkKind {
fn from(hrp: KnownHrp) -> Self {
match hrp {
- KnownHrp::Mainnet => NetworkKind::Main,
- KnownHrp::Testnets => NetworkKind::Test,
- KnownHrp::Regtest => NetworkKind::Test,
+ KnownHrp::Mainnet => Self::Main,
+ KnownHrp::Testnets => Self::Test,
+ KnownHrp::Regtest => Self::Test,
}
}
}
@@ -418,7 +418,7 @@ impl<N: NetworkValidation> fmt::Display for DisplayUnchecked<'_, N> {
#[cfg(feature = "serde")]
impl<'de, U: NetworkValidationUnchecked> serde::Deserialize<'de> for Address<U> {
- fn deserialize<D>(deserializer: D) -> Result<Address<U>, D::Error>
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
@@ -463,7 +463,7 @@ impl<V: NetworkValidation> serde::Serialize for Address<V> {
/// Methods on [`Address`] that can be called on both `Address<NetworkChecked>` and
/// `Address<NetworkUnchecked>`.
impl<V: NetworkValidation> Address<V> {
- fn from_inner(inner: AddressInner) -> Self { Address(PhantomData, inner) }
+ fn from_inner(inner: AddressInner) -> Self { Self(PhantomData, inner) }
fn to_inner(self) -> AddressInner { self.1 }
@@ -475,9 +475,7 @@ impl<V: NetworkValidation> Address<V> {
}
/// Marks the network of this address as unchecked.
- pub fn to_unchecked(self) -> Address<NetworkUnchecked> {
- Address::from_inner(self.to_inner())
- }
+ pub fn to_unchecked(self) -> Address<NetworkUnchecked> { Address::from_inner(self.to_inner()) }
/// Marks the network of this address as unchecked.
#[deprecated(since = "0.33.0", note = "use to_unchecked instead")]
@@ -502,7 +500,7 @@ impl Address {
///
/// This is the preferred non-witness type address.
#[inline]
- pub fn p2pkh(pk: impl Into<PubkeyHash>, network: impl Into<NetworkKind>) -> Address {
+ pub fn p2pkh(pk: impl Into<PubkeyHash>, network: impl Into<NetworkKind>) -> Self {
let hash = pk.into();
Self::from_inner(AddressInner::P2pkh { hash, network: network.into() })
}
@@ -515,9 +513,9 @@ impl Address {
pub fn p2sh<T: ScriptHashableTag>(
redeem_script: &Script<T>,
network: impl Into<NetworkKind>,
- ) -> Result<Address, RedeemScriptSizeError> {
+ ) -> Result<Self, RedeemScriptSizeError> {
let hash = redeem_script.script_hash()?;
- Ok(Address::p2sh_from_hash(hash, network))
+ Ok(Self::p2sh_from_hash(hash, network))
}
/// Constructs a new pay-to-script-hash (P2SH) [`Address`] from a script hash.
@@ -526,7 +524,7 @@ impl Address {
///
/// The `hash` pre-image (redeem script) must not exceed 520 bytes in length
/// otherwise outputs created from the returned address will be un-spendable.
- pub fn p2sh_from_hash(hash: ScriptHash, network: impl Into<NetworkKind>) -> Address {
+ pub fn p2sh_from_hash(hash: ScriptHash, network: impl Into<NetworkKind>) -> Self {
Self::from_inner(AddressInner::P2sh { hash, network: network.into() })
}
@@ -535,32 +533,32 @@ impl Address {
/// This is the native SegWit address type for an output redeemable with a single signature.
pub fn p2wpkh(pk: CompressedPublicKey, hrp: impl Into<KnownHrp>) -> Self {
let program = WitnessProgram::p2wpkh(pk);
- Address::from_witness_program(program, hrp)
+ Self::from_witness_program(program, hrp)
}
/// Constructs a new pay-to-script-hash (P2SH) [`Address`] that embeds a
/// pay-to-witness-public-key-hash (P2WPKH).
///
/// This is a SegWit address type that looks familiar (as p2sh) to legacy clients.
- pub fn p2shwpkh(pk: CompressedPublicKey, network: impl Into<NetworkKind>) -> Address {
+ pub fn p2shwpkh(pk: CompressedPublicKey, network: impl Into<NetworkKind>) -> Self {
let builder = ScriptPubKey::builder().push_int_unchecked(0).push_slice(pk.wpubkey_hash());
let script_hash = builder.as_script().script_hash().expect("script is less than 520 bytes");
- Address::p2sh_from_hash(script_hash, network)
+ Self::p2sh_from_hash(script_hash, network)
}
/// Constructs a new pay-to-witness-script-hash (P2WSH) [`Address`] from a witness script.
pub fn p2wsh(
witness_script: &WitnessScript,
hrp: impl Into<KnownHrp>,
- ) -> Result<Address, WitnessScriptSizeError> {
+ ) -> Result<Self, WitnessScriptSizeError> {
let program = WitnessProgram::p2wsh(witness_script)?;
- Ok(Address::from_witness_program(program, hrp))
+ Ok(Self::from_witness_program(program, hrp))
}
/// Constructs a new pay-to-witness-script-hash (P2WSH) [`Address`] from a witness script hash.
- pub fn p2wsh_from_hash(hash: WScriptHash, hrp: impl Into<KnownHrp>) -> Address {
+ pub fn p2wsh_from_hash(hash: WScriptHash, hrp: impl Into<KnownHrp>) -> Self {
let program = WitnessProgram::p2wsh_from_hash(hash);
- Address::from_witness_program(program, hrp)
+ Self::from_witness_program(program, hrp)
}
/// Constructs a new pay-to-script-hash (P2SH) [`Address`] that embeds a
@@ -570,11 +568,11 @@ impl Address {
pub fn p2shwsh(
witness_script: &WitnessScript,
network: impl Into<NetworkKind>,
- ) -> Result<Address, WitnessScriptSizeError> {
+ ) -> Result<Self, WitnessScriptSizeError> {
let hash = witness_script.wscript_hash()?;
let builder = ScriptPubKey::builder().push_int_unchecked(0).push_slice(hash);
let script_hash = builder.as_script().script_hash().expect("script is less than 520 bytes");
- Ok(Address::p2sh_from_hash(script_hash, network))
+ Ok(Self::p2sh_from_hash(script_hash, network))
}
/// Constructs a new pay-to-Taproot (P2TR) [`Address`] from an untweaked key.
@@ -583,25 +581,25 @@ impl Address {
internal_key: K,
merkle_root: Option<TapNodeHash>,
hrp: impl Into<KnownHrp>,
- ) -> Address {
+ ) -> Self {
let internal_key = internal_key.into();
let program = WitnessProgram::p2tr(secp, internal_key, merkle_root);
- Address::from_witness_program(program, hrp)
+ Self::from_witness_program(program, hrp)
}
/// Constructs a new pay-to-Taproot (P2TR) [`Address`] from a pre-tweaked output key.
- pub fn p2tr_tweaked(output_key: TweakedPublicKey, hrp: impl Into<KnownHrp>) -> Address {
+ pub fn p2tr_tweaked(output_key: TweakedPublicKey, hrp: impl Into<KnownHrp>) -> Self {
let program = WitnessProgram::p2tr_tweaked(output_key);
- Address::from_witness_program(program, hrp)
+ Self::from_witness_program(program, hrp)
}
/// Constructs a new [`Address`] from an arbitrary [`WitnessProgram`].
///
/// This only exists to support future witness versions. If you are doing normal mainnet things
/// then you likely do not need this constructor.
- pub fn from_witness_program(program: WitnessProgram, hrp: impl Into<KnownHrp>) -> Address {
+ pub fn from_witness_program(program: WitnessProgram, hrp: impl Into<KnownHrp>) -> Self {
let inner = AddressInner::Segwit { program, hrp: hrp.into() };
- Address::from_inner(inner)
+ Self::from_inner(inner)
}
/// Gets the address type of the [`Address`].
@@ -689,22 +687,22 @@ impl Address {
pub fn from_script(
script: &ScriptPubKey,
params: impl AsRef<Params>,
- ) -> Result<Address, FromScriptError> {
+ ) -> Result<Self, FromScriptError> {
let network = params.as_ref().network;
if script.is_p2pkh() {
let bytes = script.as_bytes()[3..23].try_into().expect("statically 20B long");
let hash = PubkeyHash::from_byte_array(bytes);
- Ok(Address::p2pkh(hash, network))
+ Ok(Self::p2pkh(hash, network))
} else if script.is_p2sh() {
let bytes = script.as_bytes()[2..22].try_into().expect("statically 20B long");
let hash = ScriptHash::from_byte_array(bytes);
- Ok(Address::p2sh_from_hash(hash, network))
+ Ok(Self::p2sh_from_hash(hash, network))
} else if script.is_witness_program() {
let opcode = script.first_opcode().expect("is_witness_program guarantees len > 4");
let version = WitnessVersion::try_from(opcode)?;
let program = WitnessProgram::new(version, &script.as_bytes()[2..])?;
- Ok(Address::from_witness_program(program, network))
+ Ok(Self::from_witness_program(program, network))
} else {
Err(FromScriptError::UnrecognizedScript)
}
@@ -907,7 +905,7 @@ impl Address<NetworkUnchecked> {
pub fn assume_checked(self) -> Address { Address::from_inner(self.to_inner()) }
/// Parses a bech32 Address string
- pub fn from_bech32_str(s: &str) -> Result<Address<NetworkUnchecked>, Bech32Error> {
+ pub fn from_bech32_str(s: &str) -> Result<Self, Bech32Error> {
let (hrp, witness_version, data) =
bech32::segwit::decode(s).map_err(|e| Bech32Error::ParseBech32(ParseBech32Error(e)))?;
let version = WitnessVersion::try_from(witness_version.to_u8())?;
@@ -916,11 +914,11 @@ impl Address<NetworkUnchecked> {
let hrp = KnownHrp::from_hrp(hrp)?;
let inner = AddressInner::Segwit { program, hrp };
- Ok(Address::from_inner(inner))
+ Ok(Self::from_inner(inner))
}
/// Parses a base58 Address string
- pub fn from_base58_str(s: &str) -> Result<Address<NetworkUnchecked>, Base58Error> {
+ pub fn from_base58_str(s: &str) -> Result<Self, Base58Error> {
if s.len() > 50 {
return Err(LegacyAddressTooLongError { length: s.len() }.into());
}
@@ -951,7 +949,7 @@ impl Address<NetworkUnchecked> {
invalid => return Err(InvalidLegacyPrefixError { invalid }.into()),
};
- Ok(Address::from_inner(inner))
+ Ok(Self::from_inner(inner))
}
}
@@ -999,10 +997,10 @@ impl<U: NetworkValidationUnchecked> FromStr for Address<U> {
if ["bc1", "bcrt1", "tb1"].iter().any(|&prefix| s.to_lowercase().starts_with(prefix)) {
let address = Address::from_bech32_str(s)?;
// We know that `U` is only ever `NetworkUnchecked` but the compiler does not.
- Ok(Address::from_inner(address.to_inner()))
+ Ok(Self::from_inner(address.to_inner()))
} else if ["1", "2", "3", "m", "n"].iter().any(|&prefix| s.starts_with(prefix)) {
let address = Address::from_base58_str(s)?;
- Ok(Address::from_inner(address.to_inner()))
+ Ok(Self::from_inner(address.to_inner()))
} else {
let hrp = match s.rfind('1') {
Some(pos) => &s[..pos],
diff --git a/bitcoin/src/bip152.rs b/bitcoin/src/bip152.rs
index 829a4b0e..7095e3aa 100644
--- a/bitcoin/src/bip152.rs
+++ b/bitcoin/src/bip152.rs
@@ -39,8 +39,8 @@ impl From<Infallible> for Error {
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
- Error::UnknownVersion => write!(f, "an unknown version number was used"),
- Error::InvalidPrefill => write!(f, "the prefill slice provided was invalid"),
+ Self::UnknownVersion => write!(f, "an unknown version number was used"),
+ Self::InvalidPrefill => write!(f, "the prefill slice provided was invalid"),
}
}
}
@@ -94,7 +94,7 @@ impl Decodable for PrefilledTransaction {
consensus::parse_failed_error("BIP-0152 prefilled tx index out of bounds")
})?;
let tx = Transaction::consensus_decode(r)?;
- Ok(PrefilledTransaction { idx, tx })
+ Ok(Self { idx, tx })
}
}
@@ -124,13 +124,13 @@ impl ShortId {
}
/// Calculates the short ID with the given (w)txid and using the provided SipHash keys.
- pub fn with_siphash_keys<T: TxIdentifier>(txid: &T, siphash_keys: (u64, u64)) -> ShortId {
+ pub fn with_siphash_keys<T: TxIdentifier>(txid: &T, siphash_keys: (u64, u64)) -> Self {
// 2. Running SipHash-2-4 with the input being the transaction ID and the keys (k0/k1)
// set to the first two little-endian 64-bit integers from the above hash, respectively.
let hash = siphash24::Hash::hash_with_keys(siphash_keys.0, siphash_keys.1, txid.as_ref());
// 3. Dropping the 2 most significant bytes from the SipHash output to make it 6 bytes.
- let mut id = ShortId([0; 6]);
+ let mut id = Self([0; 6]);
id.0.copy_from_slice(&hash.as_byte_array()[0..6]);
id
}
@@ -145,8 +145,8 @@ impl Encodable for ShortId {
impl Decodable for ShortId {
#[inline]
- fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<ShortId, encode::Error> {
- Ok(ShortId(Decodable::consensus_decode(r)?))
+ fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
+ Ok(Self(Decodable::consensus_decode(r)?))
}
}
@@ -171,7 +171,7 @@ pub struct HeaderAndShortIds {
impl Decodable for HeaderAndShortIds {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- let header_short_ids = HeaderAndShortIds {
+ let header_short_ids = Self {
header: Decodable::consensus_decode(r)?,
nonce: Decodable::consensus_decode(r)?,
short_ids: Decodable::consensus_decode(r)?,
@@ -211,7 +211,7 @@ impl HeaderAndShortIds {
nonce: u64,
version: u32,
mut prefill: &[usize],
- ) -> Result<HeaderAndShortIds, Error> {
+ ) -> Result<Self, Error> {
if version != 1 && version != 2 {
return Err(Error::UnknownVersion);
}
@@ -266,7 +266,7 @@ impl HeaderAndShortIds {
return Err(Error::InvalidPrefill);
}
- Ok(HeaderAndShortIds {
+ Ok(Self {
header: *block.header(),
nonce,
// Provide coinbase prefilled.
@@ -304,7 +304,7 @@ impl Encodable for BlockTransactionsRequest {
impl Decodable for BlockTransactionsRequest {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- Ok(BlockTransactionsRequest {
+ Ok(Self {
block_hash: BlockHash::consensus_decode(r)?,
indexes: {
// Manually decode indexes because they are differentially encoded as CompactSize.
@@ -383,8 +383,8 @@ impl BlockTransactions {
pub fn from_request(
request: &BlockTransactionsRequest,
block: &Block<BlockChecked>,
- ) -> Result<BlockTransactions, TxIndexOutOfRangeError> {
- Ok(BlockTransactions {
+ ) -> Result<Self, TxIndexOutOfRangeError> {
+ Ok(Self {
block_hash: request.block_hash,
transactions: {
let mut txs = Vec::with_capacity(request.indexes.len());
@@ -403,21 +403,21 @@ impl BlockTransactions {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for ShortId {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(ShortId(u.arbitrary()?))
+ Ok(Self(u.arbitrary()?))
}
}
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for PrefilledTransaction {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(PrefilledTransaction { idx: u.arbitrary()?, tx: u.arbitrary()? })
+ Ok(Self { idx: u.arbitrary()?, tx: u.arbitrary()? })
}
}
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for HeaderAndShortIds {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(HeaderAndShortIds {
+ Ok(Self {
header: u.arbitrary()?,
nonce: u.arbitrary()?,
short_ids: Vec::<ShortId>::arbitrary(u)?,
@@ -429,7 +429,7 @@ impl<'a> Arbitrary<'a> for HeaderAndShortIds {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for BlockTransactions {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(BlockTransactions {
+ Ok(Self {
block_hash: u.arbitrary()?,
transactions: Vec::<Transaction>::arbitrary(u)?,
})
@@ -439,7 +439,7 @@ impl<'a> Arbitrary<'a> for BlockTransactions {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for BlockTransactionsRequest {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(BlockTransactionsRequest {
+ Ok(Self {
block_hash: u.arbitrary()?,
indexes: Vec::<u64>::arbitrary(u)?,
})
diff --git a/bitcoin/src/bip158.rs b/bitcoin/src/bip158.rs
index 530798ad..928c3d0d 100644
--- a/bitcoin/src/bip158.rs
+++ b/bitcoin/src/bip158.rs
@@ -111,7 +111,7 @@ impl std::error::Error for Error {
}
impl From<io::Error> for Error {
- fn from(io: io::Error) -> Self { Error::Io(io) }
+ fn from(io: io::Error) -> Self { Self::Io(io) }
}
/// A block filter, as described by BIP 158.
@@ -133,13 +133,13 @@ impl FilterHash {
impl BlockFilter {
/// Constructs a new filter from pre-computed data.
- pub fn new(content: &[u8]) -> BlockFilter { BlockFilter { content: content.to_vec() } }
+ pub fn new(content: &[u8]) -> Self { Self { content: content.to_vec() } }
/// Computes a SCRIPT_FILTER that contains spent and output scripts.
pub fn new_script_filter<M, S>(
block: &Block<Checked>,
script_for_coin: M,
- ) -> Result<BlockFilter, Error>
+ ) -> Result<Self, Error>
where
M: Fn(&OutPoint) -> Result<S, Error>,
S: Borrow<ScriptPubKey>,
@@ -151,7 +151,7 @@ impl BlockFilter {
writer.add_input_scripts(script_for_coin)?;
writer.finish()?;
- Ok(BlockFilter { content: out })
+ Ok(Self { content: out })
}
/// Computes this filter's ID in a chain of filters (see [BIP 157]).
@@ -196,7 +196,7 @@ pub struct BlockFilterWriter<'a, W> {
impl<'a, W: Write> BlockFilterWriter<'a, W> {
/// Constructs a new [`BlockFilterWriter`] from `block`.
- pub fn new(writer: &'a mut W, block: &'a Block<Checked>) -> BlockFilterWriter<'a, W> {
+ pub fn new(writer: &'a mut W, block: &'a Block<Checked>) -> Self {
let block_hash_as_int = block.block_hash().to_byte_array();
let k0 = u64::from_le_bytes(*block_hash_as_int.sub_array::<0, 8>());
let k1 = u64::from_le_bytes(*block_hash_as_int.sub_array::<8, 8>());
@@ -251,11 +251,11 @@ pub struct BlockFilterReader {
impl BlockFilterReader {
/// Constructs a new [`BlockFilterReader`] from `block_hash`.
- pub fn new(block_hash: BlockHash) -> BlockFilterReader {
+ pub fn new(block_hash: BlockHash) -> Self {
let block_hash_as_int = block_hash.to_byte_array();
let k0 = u64::from_le_bytes(*block_hash_as_int.sub_array::<0, 8>());
let k1 = u64::from_le_bytes(*block_hash_as_int.sub_array::<8, 8>());
- BlockFilterReader { reader: GcsFilterReader::new(k0, k1, M, P) }
+ Self { reader: GcsFilterReader::new(k0, k1, M, P) }
}
/// Returns true if any query matches against this [`BlockFilterReader`].
@@ -287,8 +287,8 @@ pub struct GcsFilterReader {
impl GcsFilterReader {
/// Constructs a new [`GcsFilterReader`] with specific seed to siphash.
- pub fn new(k0: u64, k1: u64, m: u64, p: u8) -> GcsFilterReader {
- GcsFilterReader { filter: GcsFilter::new(k0, k1, p), m }
+ pub fn new(k0: u64, k1: u64, m: u64, p: u8) -> Self {
+ Self { filter: GcsFilter::new(k0, k1, p), m }
}
/// Returns true if any query matches against this [`GcsFilterReader`].
@@ -392,7 +392,7 @@ pub struct GcsFilterWriter<'a, W> {
impl<'a, W: Write> GcsFilterWriter<'a, W> {
/// Constructs a new [`GcsFilterWriter`] wrapping a generic writer, with specific seed to siphash.
- pub fn new(writer: &'a mut W, k0: u64, k1: u64, m: u64, p: u8) -> GcsFilterWriter<'a, W> {
+ pub fn new(writer: &'a mut W, k0: u64, k1: u64, m: u64, p: u8) -> Self {
GcsFilterWriter { filter: GcsFilter::new(k0, k1, p), writer, elements: BTreeSet::new(), m }
}
@@ -439,7 +439,7 @@ struct GcsFilter {
impl GcsFilter {
/// Constructs a new [`GcsFilter`].
- fn new(k0: u64, k1: u64, p: u8) -> GcsFilter { GcsFilter { k0, k1, p } }
+ fn new(k0: u64, k1: u64, p: u8) -> Self { Self { k0, k1, p } }
/// Golomb-Rice encodes a number `n` to a bit stream (parameter 2^k).
fn golomb_rice_encode<W>(
@@ -490,7 +490,7 @@ pub struct BitStreamReader<'a, R: ?Sized> {
impl<'a, R: BufRead + ?Sized> BitStreamReader<'a, R> {
/// Constructs a new [`BitStreamReader`] that reads bitwise from a given `reader`.
- pub fn new(reader: &'a mut R) -> BitStreamReader<'a, R> {
+ pub fn new(reader: &'a mut R) -> Self {
BitStreamReader { buffer: [0u8], reader, offset: 8 }
}
@@ -538,7 +538,7 @@ pub struct BitStreamWriter<'a, W> {
impl<'a, W: Write> BitStreamWriter<'a, W> {
/// Constructs a new [`BitStreamWriter`] that writes bitwise to a given `writer`.
- pub fn new(writer: &'a mut W) -> BitStreamWriter<'a, W> {
+ pub fn new(writer: &'a mut W) -> Self {
BitStreamWriter { buffer: [0u8], writer, offset: 0 }
}
@@ -579,14 +579,14 @@ impl<'a, W: Write> BitStreamWriter<'a, W> {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for FilterHash {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(FilterHash::from_byte_array(u.arbitrary()?))
+ Ok(Self::from_byte_array(u.arbitrary()?))
}
}
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for FilterHeader {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(FilterHeader::from_byte_array(u.arbitrary()?))
+ Ok(Self::from_byte_array(u.arbitrary()?))
}
}
diff --git a/bitcoin/src/bip32.rs b/bitcoin/src/bip32.rs
index 3e86f503..1abebbf1 100644
--- a/bitcoin/src/bip32.rs
+++ b/bitcoin/src/bip32.rs
@@ -45,7 +45,7 @@ internal_macros::impl_array_newtype_stringify!(ChainCode, 32);
impl ChainCode {
fn from_hmac(hmac: Hmac<sha512::Hash>) -> Self {
- ChainCode(*hmac.as_byte_array().split_array::<32, 32>().1)
+ Self(*hmac.as_byte_array().split_array::<32, 32>().1)
}
}
@@ -133,16 +133,16 @@ pub enum ChildNumber {
}
impl ChildNumber {
/// Normal child number with index 0.
- pub const ZERO_NORMAL: Self = ChildNumber::Normal { index: 0 };
+ pub const ZERO_NORMAL: Self = Self::Normal { index: 0 };
/// Normal child number with index 1.
- pub const ONE_NORMAL: Self = ChildNumber::Normal { index: 1 };
+ pub const ONE_NORMAL: Self = Self::Normal { index: 1 };
/// Hardened child number with index 0.
- pub const ZERO_HARDENED: Self = ChildNumber::Hardened { index: 0 };
+ pub const ZERO_HARDENED: Self = Self::Hardened { index: 0 };
/// Hardened child number with index 1.
- pub const ONE_HARDENED: Self = ChildNumber::Hardened { index: 1 };
+ pub const ONE_HARDENED: Self = Self::Hardened { index: 1 };
/// Constructs a new [`Normal`] from an index, returns an error if the index is not within
/// [0, 2^31 - 1].
@@ -150,7 +150,7 @@ impl ChildNumber {
/// [`Normal`]: #variant.Normal
pub fn from_normal_idx(index: u32) -> Result<Self, IndexOutOfRangeError> {
if index & (1 << 31) == 0 {
- Ok(ChildNumber::Normal { index })
+ Ok(Self::Normal { index })
} else {
Err(IndexOutOfRangeError { index })
}
@@ -162,7 +162,7 @@ impl ChildNumber {
/// [`Hardened`]: #variant.Hardened
pub fn from_hardened_idx(index: u32) -> Result<Self, IndexOutOfRangeError> {
if index & (1 << 31) == 0 {
- Ok(ChildNumber::Hardened { index })
+ Ok(Self::Hardened { index })
} else {
Err(IndexOutOfRangeError { index })
}
@@ -178,19 +178,19 @@ impl ChildNumber {
/// [`Hardened`]: #variant.Hardened
pub fn is_hardened(&self) -> bool {
match self {
- ChildNumber::Hardened { .. } => true,
- ChildNumber::Normal { .. } => false,
+ Self::Hardened { .. } => true,
+ Self::Normal { .. } => false,
}
}
/// Returns the child number that is a single increment from this one.
- pub fn increment(self) -> Result<ChildNumber, IndexOutOfRangeError> {
+ pub fn increment(self) -> Result<Self, IndexOutOfRangeError> {
// Bare addition in this function is okay, because we have an invariant that
// `index` is always within [0, 2^31 - 1]. FIXME this is not actually an
// invariant because the fields are public.
match self {
- ChildNumber::Normal { index: idx } => ChildNumber::from_normal_idx(idx + 1),
- ChildNumber::Hardened { index: idx } => ChildNumber::from_hardened_idx(idx + 1),
+ Self::Normal { index: idx } => Self::from_normal_idx(idx + 1),
+ Self::Hardened { index: idx } => Self::from_hardened_idx(idx + 1),
}
}
@@ -208,12 +208,12 @@ impl ChildNumber {
F: Fn(&u32, &mut fmt::Formatter) -> fmt::Result,
{
match *self {
- ChildNumber::Hardened { index } => {
+ Self::Hardened { index } => {
format_fn(&index, f)?;
let alt = f.alternate();
f.write_str(if alt { hardened_alt_suffix } else { "'" })
}
- ChildNumber::Normal { index } => format_fn(&index, f),
+ Self::Normal { index } => format_fn(&index, f),
}
}
}
@@ -221,9 +221,9 @@ impl ChildNumber {
impl From<u32> for ChildNumber {
fn from(number: u32) -> Self {
if number & (1 << 31) != 0 {
- ChildNumber::Hardened { index: number ^ (1 << 31) }
+ Self::Hardened { index: number ^ (1 << 31) }
} else {
- ChildNumber::Normal { index: number }
+ Self::Normal { index: number }
}
}
}
@@ -273,19 +273,19 @@ impl FromStr for ChildNumber {
fn from_str(inp: &str) -> Result<Self, Self::Err> {
let is_hardened = inp.chars().last().is_some_and(|l| l == '\'' || l == 'h');
Ok(if is_hardened {
- ChildNumber::from_hardened_idx(
+ Self::from_hardened_idx(
inp[0..inp.len() - 1].parse().map_err(ParseChildNumberError::ParseInt)?,
)
.map_err(ParseChildNumberError::IndexOutOfRange)?
} else {
- ChildNumber::from_normal_idx(inp.parse().map_err(ParseChildNumberError::ParseInt)?)
+ Self::from_normal_idx(inp.parse().map_err(ParseChildNumberError::ParseInt)?)
.map_err(ParseChildNumberError::IndexOutOfRange)?
})
}
}
-impl AsRef<[ChildNumber]> for ChildNumber {
- fn as_ref(&self) -> &[ChildNumber] { slice::from_ref(self) }
+impl AsRef<[Self]> for ChildNumber {
+ fn as_ref(&self) -> &[Self] { slice::from_ref(self) }
}
#[cfg(feature = "serde")]
@@ -294,7 +294,7 @@ impl<'de> serde::Deserialize<'de> for ChildNumber {
where
D: serde::Deserializer<'de>,
{
- u32::deserialize(deserializer).map(ChildNumber::from)
+ u32::deserialize(deserializer).map(Self::from)
}
}
@@ -333,7 +333,7 @@ where
}
impl Default for DerivationPath {
- fn default() -> DerivationPath { DerivationPath::master() }
+ fn default() -> Self { Self::master() }
}
impl<T> IntoDerivationPath for T
@@ -354,7 +354,7 @@ impl IntoDerivationPath for &'_ str {
}
impl From<Vec<ChildNumber>> for DerivationPath {
- fn from(numbers: Vec<ChildNumber>) -> Self { DerivationPath(numbers) }
+ fn from(numbers: Vec<ChildNumber>) -> Self { Self(numbers) }
}
impl From<DerivationPath> for Vec<ChildNumber> {
@@ -362,7 +362,7 @@ impl From<DerivationPath> for Vec<ChildNumber> {
}
impl<'a> From<&'a [ChildNumber]> for DerivationPath {
- fn from(numbers: &'a [ChildNumber]) -> Self { DerivationPath(numbers.to_vec()) }
+ fn from(numbers: &'a [ChildNumber]) -> Self { Self(numbers.to_vec()) }
}
impl core::iter::FromIterator<ChildNumber> for DerivationPath {
@@ -370,7 +370,7 @@ impl core::iter::FromIterator<ChildNumber> for DerivationPath {
where
T: IntoIterator<Item = ChildNumber>,
{
- DerivationPath(Vec::from_iter(iter))
+ Self(Vec::from_iter(iter))
}
}
@@ -396,7 +396,7 @@ impl FromStr for DerivationPath {
let parts = path.split('/');
let ret: Result<Vec<ChildNumber>, _> = parts.map(str::parse).collect();
- Ok(DerivationPath(ret?))
+ Ok(Self(ret?))
}
}
@@ -411,7 +411,7 @@ pub struct DerivationPathIterator<'a> {
impl<'a> DerivationPathIterator<'a> {
/// Starts a new [DerivationPathIterator] at the given child.
- pub fn start_from(path: &'a DerivationPath, start: ChildNumber) -> DerivationPathIterator<'a> {
+ pub fn start_from(path: &'a DerivationPath, start: ChildNumber) -> Self {
DerivationPathIterator { base: path, next_child: Some(start) }
}
}
@@ -434,24 +434,24 @@ impl DerivationPath {
pub fn is_empty(&self) -> bool { self.0.is_empty() }
/// Returns derivation path for a master key (i.e. empty derivation path)
- pub fn master() -> DerivationPath { DerivationPath(vec![]) }
+ pub fn master() -> Self { Self(vec![]) }
/// Returns whether derivation path represents master key (i.e. it's length
/// is empty). True for `m` path.
pub fn is_master(&self) -> bool { self.0.is_empty() }
/// Constructs a new [DerivationPath] that is a child of this one.
- pub fn child(&self, cn: ChildNumber) -> DerivationPath {
+ pub fn child(&self, cn: ChildNumber) -> Self {
let mut path = self.0.clone();
path.push(cn);
- DerivationPath(path)
+ Self(path)
}
/// Converts into a [DerivationPath] that is a child of this one.
- pub fn into_child(self, cn: ChildNumber) -> DerivationPath {
+ pub fn into_child(self, cn: ChildNumber) -> Self {
let mut path = self.0;
path.push(cn);
- DerivationPath(path)
+ Self(path)
}
/// Gets an [Iterator] over the children of this [DerivationPath]
@@ -485,7 +485,7 @@ impl DerivationPath {
///
/// assert_eq!(deriv_1, deriv_2);
/// ```
- pub fn extend<T: AsRef<[ChildNumber]>>(&self, path: T) -> DerivationPath {
+ pub fn extend<T: AsRef<[ChildNumber]>>(&self, path: T) -> Self {
let mut new_path = self.clone();
new_path.0.extend_from_slice(path.as_ref());
new_path
@@ -612,15 +612,15 @@ impl std::error::Error for ParseError {
}
impl From<secp256k1::Error> for ParseError {
- fn from(e: secp256k1::Error) -> ParseError { ParseError::Secp256k1(e) }
+ fn from(e: secp256k1::Error) -> Self { Self::Secp256k1(e) }
}
impl From<base58::Error> for ParseError {
- fn from(err: base58::Error) -> Self { ParseError::Base58(err) }
+ fn from(err: base58::Error) -> Self { Self::Base58(err) }
}
impl From<InvalidBase58PayloadLengthError> for ParseError {
- fn from(e: InvalidBase58PayloadLengthError) -> ParseError {
+ fn from(e: InvalidBase58PayloadLengthError) -> Self {
Self::InvalidBase58PayloadLength(e)
}
}
@@ -710,12 +710,12 @@ impl fmt::Display for ParseChildNumberError {
impl Xpriv {
/// Constructs a new master key from a seed value
- pub fn new_master(network: impl Into<NetworkKind>, seed: &[u8]) -> Xpriv {
+ pub fn new_master(network: impl Into<NetworkKind>, seed: &[u8]) -> Self {
let mut engine = HmacEngine::<sha512::HashEngine>::new(b"Bitcoin seed");
engine.input(seed);
let hmac = engine.finalize();
- Xpriv {
+ Self {
network: network.into(),
depth: 0,
parent_fingerprint: Default::default(),
@@ -757,7 +757,7 @@ impl Xpriv {
&self,
secp: &Secp256k1<C>,
path: P,
- ) -> Result<Xpriv, DerivationError> {
+ ) -> Result<Self, DerivationError> {
self.derive_xpriv(secp, path)
}
@@ -768,8 +768,8 @@ impl Xpriv {
&self,
secp: &Secp256k1<C>,
path: P,
- ) -> Result<Xpriv, DerivationError> {
- let mut sk: Xpriv = *self;
+ ) -> Result<Self, DerivationError> {
+ let mut sk: Self = *self;
for cnum in path.as_ref() {
sk = sk.ckd_priv(secp, *cnum)?;
}
@@ -781,7 +781,7 @@ impl Xpriv {
&self,
secp: &Secp256k1<C>,
i: ChildNumber,
- ) -> Result<Xpriv, DerivationError> {
+ ) -> Result<Self, DerivationError> {
let mut engine = HmacEngine::<sha512::HashEngine>::new(&self.chain_code[..]);
match i {
ChildNumber::Normal { .. } => {
@@ -805,7 +805,7 @@ impl Xpriv {
let tweaked =
sk.add_tweak(&self.private_key.into()).expect("statistically impossible to hit");
- Ok(Xpriv {
+ Ok(Self {
network: self.network,
depth: self.depth.checked_add(1).ok_or(DerivationError::MaximumDepthExceeded)?,
parent_fingerprint: self.fingerprint(secp),
@@ -816,7 +816,7 @@ impl Xpriv {
}
/// Decoding extended private key from binary data according to BIP-0032
- pub fn decode(data: &[u8]) -> Result<Xpriv, ParseError> {
+ pub fn decode(data: &[u8]) -> Result<Self, ParseError> {
let Common { network, depth, parent_fingerprint, child_number, chain_code, key } =
Common::decode(data)?;
@@ -831,7 +831,7 @@ impl Xpriv {
return Err(ParseError::InvalidPrivateKeyPrefix);
}
- Ok(Xpriv {
+ Ok(Self {
network,
depth,
parent_fingerprint,
@@ -871,13 +871,13 @@ impl Xpriv {
impl Xpub {
/// Constructs a new extended public key from an extended private key.
#[deprecated(since = "TBD", note = "use `from_xpriv()` instead")]
- pub fn from_priv<C: secp256k1::Signing>(secp: &Secp256k1<C>, sk: &Xpriv) -> Xpub {
+ pub fn from_priv<C: secp256k1::Signing>(secp: &Secp256k1<C>, sk: &Xpriv) -> Self {
Self::from_xpriv(secp, sk)
}
/// Constructs a new extended public key from an extended private key.
- pub fn from_xpriv<C: secp256k1::Signing>(secp: &Secp256k1<C>, xpriv: &Xpriv) -> Xpub {
- Xpub {
+ pub fn from_xpriv<C: secp256k1::Signing>(secp: &Secp256k1<C>, xpriv: &Xpriv) -> Self {
+ Self {
network: xpriv.network,
depth: xpriv.depth,
parent_fingerprint: xpriv.parent_fingerprint,
@@ -911,7 +911,7 @@ impl Xpub {
&self,
secp: &Secp256k1<C>,
path: P,
- ) -> Result<Xpub, DerivationError> {
+ ) -> Result<Self, DerivationError> {
self.derive_xpub(secp, path)
}
@@ -922,8 +922,8 @@ impl Xpub {
&self,
secp: &Secp256k1<C>,
path: P,
- ) -> Result<Xpub, DerivationError> {
- let mut pk: Xpub = *self;
+ ) -> Result<Self, DerivationError> {
+ let mut pk: Self = *self;
for cnum in path.as_ref() {
pk = pk.ckd_pub(secp, *cnum)?
}
@@ -958,12 +958,12 @@ impl Xpub {
&self,
secp: &Secp256k1<C>,
i: ChildNumber,
- ) -> Result<Xpub, DerivationError> {
+ ) -> Result<Self, DerivationError> {
let (sk, chain_code) = self.ckd_pub_tweak(i)?;
let tweaked =
self.public_key.add_exp_tweak(secp, &sk.into()).expect("cryptographically unreachable");
- Ok(Xpub {
+ Ok(Self {
network: self.network,
depth: self.depth.checked_add(1).ok_or(DerivationError::MaximumDepthExceeded)?,
parent_fingerprint: self.fingerprint(),
@@ -974,7 +974,7 @@ impl Xpub {
}
/// Decoding extended public key from binary data according to BIP-0032
- pub fn decode(data: &[u8]) -> Result<Xpub, ParseError> {
+ pub fn decode(data: &[u8]) -> Result<Self, ParseError> {
let Common { network, depth, parent_fingerprint, child_number, chain_code, key } =
Common::decode(data)?;
@@ -984,7 +984,7 @@ impl Xpub {
unknown => return Err(ParseError::UnknownVersion(unknown)),
};
- Ok(Xpub {
+ Ok(Self {
network,
depth,
parent_fingerprint,
@@ -1029,14 +1029,14 @@ impl fmt::Display for Xpriv {
impl FromStr for Xpriv {
type Err = ParseError;
- fn from_str(inp: &str) -> Result<Xpriv, ParseError> {
+ fn from_str(inp: &str) -> Result<Self, ParseError> {
let data = base58::decode_check(inp)?;
if data.len() != 78 {
return Err(InvalidBase58PayloadLengthError { length: data.len() }.into());
}
- Xpriv::decode(&data)
+ Self::decode(&data)
}
}
@@ -1049,23 +1049,23 @@ impl fmt::Display for Xpub {
impl FromStr for Xpub {
type Err = ParseError;
- fn from_str(inp: &str) -> Result<Xpub, ParseError> {
+ fn from_str(inp: &str) -> Result<Self, ParseError> {
let data = base58::decode_check(inp)?;
if data.len() != 78 {
return Err(InvalidBase58PayloadLengthError { length: data.len() }.into());
}
- Xpub::decode(&data)
+ Self::decode(&data)
}
}
impl From<Xpub> for XKeyIdentifier {
- fn from(key: Xpub) -> XKeyIdentifier { key.identifier() }
+ fn from(key: Xpub) -> Self { key.identifier() }
}
impl From<&Xpub> for XKeyIdentifier {
- fn from(key: &Xpub) -> XKeyIdentifier { key.identifier() }
+ fn from(key: &Xpub) -> Self { key.identifier() }
}
/// Decoded base58 data was an invalid length.
@@ -1125,7 +1125,7 @@ impl Common {
}
}
- Ok(Common {
+ Ok(Self {
network,
depth,
parent_fingerprint: parent_fingerprint.into(),
diff --git a/bitcoin/src/blockdata/block.rs b/bitcoin/src/blockdata/block.rs
index 2ff3d716..8507c9a4 100644
--- a/bitcoin/src/blockdata/block.rs
+++ b/bitcoin/src/blockdata/block.rs
@@ -42,7 +42,7 @@ impl Encodable for BlockHash {
impl Decodable for BlockHash {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- Ok(BlockHash::from_byte_array(<[u8; 32]>::consensus_decode(r)?))
+ Ok(Self::from_byte_array(<[u8; 32]>::consensus_decode(r)?))
}
}
@@ -95,7 +95,7 @@ impl Encodable for Version {
impl Decodable for Version {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- Decodable::consensus_decode(r).map(Version::from_consensus)
+ Decodable::consensus_decode(r).map(Self::from_consensus)
}
}
@@ -107,7 +107,7 @@ impl Encodable for BlockTime {
impl Decodable for BlockTime {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- Decodable::consensus_decode(r).map(BlockTime::from_u32)
+ Decodable::consensus_decode(r).map(Self::from_u32)
}
}
@@ -141,7 +141,7 @@ impl BlockUncheckedExt for Block<Unchecked> {
match check_witness_commitment(&transactions) {
(false, _) => Err(InvalidBlockError::InvalidWitnessCommitment),
(true, witness_root) => {
- let block = Block::new_unchecked(header, transactions);
+ let block = Self::new_unchecked(header, transactions);
Ok(block.assume_checked(witness_root))
}
}
@@ -409,20 +409,20 @@ impl Decodable for Block<Unchecked> {
#[inline]
fn consensus_decode_from_finite_reader<R: io::BufRead + ?Sized>(
r: &mut R,
- ) -> Result<Block, encode::Error> {
+ ) -> Result<Self, encode::Error> {
let header = Decodable::consensus_decode_from_finite_reader(r)?;
let transactions = Decodable::consensus_decode_from_finite_reader(r)?;
- Ok(Block::new_unchecked(header, transactions))
+ Ok(Self::new_unchecked(header, transactions))
}
#[inline]
- fn consensus_decode<R: io::BufRead + ?Sized>(r: &mut R) -> Result<Block, encode::Error> {
+ fn consensus_decode<R: io::BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
let mut r = r.take(internals::ToU64::to_u64(encode::MAX_VEC_SIZE));
let header = Decodable::consensus_decode(&mut r)?;
let transactions = Decodable::consensus_decode(&mut r)?;
- Ok(Block::new_unchecked(header, transactions))
+ Ok(Self::new_unchecked(header, transactions))
}
}
diff --git a/bitcoin/src/blockdata/constants.rs b/bitcoin/src/blockdata/constants.rs
index 589323b1..d6ba583f 100644
--- a/bitcoin/src/blockdata/constants.rs
+++ b/bitcoin/src/blockdata/constants.rs
@@ -259,7 +259,7 @@ impl ChainHash {
/// Converts genesis block hash into `ChainHash`.
pub fn from_genesis_block_hash(block_hash: crate::BlockHash) -> Self {
- ChainHash(block_hash.to_byte_array())
+ Self(block_hash.to_byte_array())
}
}
diff --git a/bitcoin/src/blockdata/mod.rs b/bitcoin/src/blockdata/mod.rs
index 0f19a9f7..c4ca8230 100644
--- a/bitcoin/src/blockdata/mod.rs
+++ b/bitcoin/src/blockdata/mod.rs
@@ -58,7 +58,7 @@ pub mod locktime {
impl Decodable for LockTime {
#[inline]
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- u32::consensus_decode(r).map(LockTime::from_consensus)
+ u32::consensus_decode(r).map(Self::from_consensus)
}
}
}
diff --git a/bitcoin/src/blockdata/opcodes.rs b/bitcoin/src/blockdata/opcodes.rs
index 552e1603..add8bdb4 100644
--- a/bitcoin/src/blockdata/opcodes.rs
+++ b/bitcoin/src/blockdata/opcodes.rs
@@ -488,7 +488,7 @@ impl Opcode {
impl From<u8> for Opcode {
#[inline]
- fn from(b: u8) -> Opcode { Opcode { code: b } }
+ fn from(b: u8) -> Self { Self { code: b } }
}
impl fmt::Debug for Opcode {
diff --git a/bitcoin/src/blockdata/script/push_bytes.rs b/bitcoin/src/blockdata/script/push_bytes.rs
index 5a394898..820e315d 100644
--- a/bitcoin/src/blockdata/script/push_bytes.rs
+++ b/bitcoin/src/blockdata/script/push_bytes.rs
@@ -195,10 +195,10 @@ mod primitive {
impl PushBytesBuf {
/// Constructs an empty `PushBytesBuf`.
#[inline]
- pub const fn new() -> Self { PushBytesBuf(Vec::new()) }
+ pub const fn new() -> Self { Self(Vec::new()) }
/// Constructs an empty `PushBytesBuf` with reserved capacity.
- pub fn with_capacity(capacity: usize) -> Self { PushBytesBuf(Vec::with_capacity(capacity)) }
+ pub fn with_capacity(capacity: usize) -> Self { Self(Vec::with_capacity(capacity)) }
/// Reserve capacity for `additional_capacity` bytes.
pub fn reserve(&mut self, additional_capacity: usize) {
@@ -273,7 +273,7 @@ mod primitive {
fn try_from(vec: Vec<u8>) -> Result<Self, Self::Error> {
// check len
let _: &PushBytes = vec.as_slice().try_into()?;
- Ok(PushBytesBuf(vec))
+ Ok(Self(vec))
}
}
@@ -361,12 +361,12 @@ impl DerefMut for PushBytesBuf {
fn deref_mut(&mut self) -> &mut Self::Target { self.as_mut_push_bytes() }
}
-impl AsRef<PushBytes> for PushBytes {
- fn as_ref(&self) -> &PushBytes { self }
+impl AsRef<Self> for PushBytes {
+ fn as_ref(&self) -> &Self { self }
}
-impl AsMut<PushBytes> for PushBytes {
- fn as_mut(&mut self) -> &mut PushBytes { self }
+impl AsMut<Self> for PushBytes {
+ fn as_mut(&mut self) -> &mut Self { self }
}
impl AsRef<PushBytes> for PushBytesBuf {
diff --git a/bitcoin/src/blockdata/script/witness_program.rs b/bitcoin/src/blockdata/script/witness_program.rs
index 89f2f854..3af8b5c5 100644
--- a/bitcoin/src/blockdata/script/witness_program.rs
+++ b/bitcoin/src/blockdata/script/witness_program.rs
@@ -57,28 +57,28 @@ impl WitnessProgram {
}
let program = ArrayVec::from_slice(bytes);
- Ok(WitnessProgram { version, program })
+ Ok(Self { version, program })
}
/// Constructs a new [`WitnessProgram`] from a 20 byte pubkey hash.
fn new_p2wpkh(program: [u8; 20]) -> Self {
- WitnessProgram { version: WitnessVersion::V0, program: ArrayVec::from_slice(&program) }
+ Self { version: WitnessVersion::V0, program: ArrayVec::from_slice(&program) }
}
/// Constructs a new [`WitnessProgram`] from a 32 byte script hash.
fn new_p2wsh(program: [u8; 32]) -> Self {
- WitnessProgram { version: WitnessVersion::V0, program: ArrayVec::from_slice(&program) }
+ Self { version: WitnessVersion::V0, program: ArrayVec::from_slice(&program) }
}
/// Constructs a new [`WitnessProgram`] from a 32 byte serialized Taproot x-only pubkey.
fn new_p2tr(program: [u8; 32]) -> Self {
- WitnessProgram { version: WitnessVersion::V1, program: ArrayVec::from_slice(&program) }
+ Self { version: WitnessVersion::V1, program: ArrayVec::from_slice(&program) }
}
/// Constructs a new [`WitnessProgram`] from `pk` for a P2WPKH output.
pub fn p2wpkh(pk: CompressedPublicKey) -> Self {
let hash = pk.wpubkey_hash();
- WitnessProgram::new_p2wpkh(hash.to_byte_array())
+ Self::new_p2wpkh(hash.to_byte_array())
}
/// Constructs a new [`WitnessProgram`] from `script` for a P2WSH output.
@@ -88,7 +88,7 @@ impl WitnessProgram {
/// Constructs a new [`WitnessProgram`] from `script` for a P2WSH output.
pub fn p2wsh_from_hash(hash: WScriptHash) -> Self {
- WitnessProgram::new_p2wsh(hash.to_byte_array())
+ Self::new_p2wsh(hash.to_byte_array())
}
/// Constructs a new [`WitnessProgram`] from an untweaked key for a P2TR output.
@@ -103,18 +103,18 @@ impl WitnessProgram {
let internal_key = internal_key.into();
let (output_key, _parity) = internal_key.tap_tweak(secp, merkle_root);
let pubkey = output_key.as_x_only_public_key().serialize();
- WitnessProgram::new_p2tr(pubkey)
+ Self::new_p2tr(pubkey)
}
/// Constructs a new [`WitnessProgram`] from a tweaked key for a P2TR output.
pub fn p2tr_tweaked(output_key: TweakedPublicKey) -> Self {
let pubkey = output_key.as_x_only_public_key().serialize();
- WitnessProgram::new_p2tr(pubkey)
+ Self::new_p2tr(pubkey)
}
/// Constructs a new [`WitnessProgram`] for a P2A output.
pub const fn p2a() -> Self {
- WitnessProgram { version: WitnessVersion::V1, program: ArrayVec::from_slice(&P2A_PROGRAM) }
+ Self { version: WitnessVersion::V1, program: ArrayVec::from_slice(&P2A_PROGRAM) }
}
/// Returns the witness program version.
diff --git a/bitcoin/src/blockdata/script/witness_version.rs b/bitcoin/src/blockdata/script/witness_version.rs
index 559509ce..dd7c2cd0 100644
--- a/bitcoin/src/blockdata/script/witness_version.rs
+++ b/bitcoin/src/blockdata/script/witness_version.rs
@@ -83,7 +83,7 @@ impl FromStr for WitnessVersion {
fn from_str(s: &str) -> Result<Self, Self::Err> {
let version: u8 = parse_int::int_from_str(s)?;
- Ok(WitnessVersion::try_from(version)?)
+ Ok(Self::try_from(version)?)
}
}
@@ -121,9 +121,9 @@ impl TryFrom<Opcode> for WitnessVersion {
fn try_from(opcode: Opcode) -> Result<Self, Self::Error> {
match opcode.to_u8() {
- 0 => Ok(WitnessVersion::V0),
+ 0 => Ok(Self::V0),
version if version >= OP_1.to_u8() && version <= OP_16.to_u8() =>
- WitnessVersion::try_from(version - OP_1.to_u8() + 1),
+ Self::try_from(version - OP_1.to_u8() + 1),
invalid => Err(TryFromError { invalid }),
}
}
@@ -134,18 +134,18 @@ impl TryFrom<Instruction<'_>> for WitnessVersion {
fn try_from(instruction: Instruction) -> Result<Self, Self::Error> {
match instruction {
- Instruction::Op(op) => Ok(WitnessVersion::try_from(op)?),
- Instruction::PushBytes(bytes) if bytes.is_empty() => Ok(WitnessVersion::V0),
+ Instruction::Op(op) => Ok(Self::try_from(op)?),
+ Instruction::PushBytes(bytes) if bytes.is_empty() => Ok(Self::V0),
Instruction::PushBytes(_) => Err(TryFromInstructionError::DataPush),
}
}
}
impl From<WitnessVersion> for Opcode {
- fn from(version: WitnessVersion) -> Opcode {
+ fn from(version: WitnessVersion) -> Self {
match version {
WitnessVersion::V0 => OP_PUSHBYTES_0,
- no => Opcode::from(OP_1.to_u8() + no.to_num() - 1),
+ no => Self::from(OP_1.to_u8() + no.to_num() - 1),
}
}
}
diff --git a/bitcoin/src/blockdata/transaction.rs b/bitcoin/src/blockdata/transaction.rs
index 47bc135b..de043691 100644
--- a/bitcoin/src/blockdata/transaction.rs
+++ b/bitcoin/src/blockdata/transaction.rs
@@ -42,7 +42,7 @@ impl Encodable for Txid {
impl Decodable for Txid {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- Ok(Txid::from_byte_array(<[u8; 32]>::consensus_decode(r)?))
+ Ok(Self::from_byte_array(<[u8; 32]>::consensus_decode(r)?))
}
}
@@ -54,7 +54,7 @@ impl Encodable for Wtxid {
impl Decodable for Wtxid {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- Ok(Wtxid::from_byte_array(<[u8; 32]>::consensus_decode(r)?))
+ Ok(Self::from_byte_array(<[u8; 32]>::consensus_decode(r)?))
}
}
@@ -686,7 +686,7 @@ impl Encodable for Version {
impl Decodable for Version {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- Decodable::consensus_decode(r).map(Version::maybe_non_standard)
+ Decodable::consensus_decode(r).map(Self::maybe_non_standard)
}
}
@@ -700,7 +700,7 @@ impl Encodable for OutPoint {
}
impl Decodable for OutPoint {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- Ok(OutPoint {
+ Ok(Self {
txid: Decodable::consensus_decode(r)?,
vout: Decodable::consensus_decode(r)?,
})
@@ -721,7 +721,7 @@ impl Decodable for TxIn {
fn consensus_decode_from_finite_reader<R: BufRead + ?Sized>(
r: &mut R,
) -> Result<Self, encode::Error> {
- Ok(TxIn {
+ Ok(Self {
previous_output: Decodable::consensus_decode_from_finite_reader(r)?,
script_sig: Decodable::consensus_decode_from_finite_reader(r)?,
sequence: Decodable::consensus_decode_from_finite_reader(r)?,
@@ -788,7 +788,7 @@ impl Decodable for Transaction {
"witness flag set but no witnesses present",
))
} else {
- Ok(Transaction {
+ Ok(Self {
version,
inputs,
outputs,
@@ -801,7 +801,7 @@ impl Decodable for Transaction {
}
// non-SegWit
} else {
- Ok(Transaction {
+ Ok(Self {
version,
inputs,
outputs: Decodable::consensus_decode_from_finite_reader(r)?,
@@ -991,7 +991,7 @@ impl InputWeightPrediction {
/// under-paying. See [`ground_p2wpkh`](Self::ground_p2wpkh) if you do use signature grinding.
///
/// [signature grinding]: https://bitcoin.stackexchange.com/questions/111660/what-is-signature-grinding
- pub const P2WPKH_MAX: Self = InputWeightPrediction::from_slice(0, &[72, 33]);
+ pub const P2WPKH_MAX: Self = Self::from_slice(0, &[72, 33]);
/// Input weight prediction corresponding to spending of [nested P2WPKH] output with the largest possible
/// DER-encoded signature.
@@ -1004,7 +1004,7 @@ impl InputWeightPrediction {
///
/// [nested P2WPKH]: https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#p2wpkh-nested-in-bip16-p2sh
/// [signature grinding]: https://bitcoin.stackexchange.com/questions/111660/what-is-signature-grinding
- pub const NESTED_P2WPKH_MAX: Self = InputWeightPrediction::from_slice(23, &[72, 33]);
+ pub const NESTED_P2WPKH_MAX: Self = Self::from_slice(23, &[72, 33]);
/// Input weight prediction corresponding to spending of a P2PKH output with the largest possible
/// DER-encoded signature, and a compressed public key.
@@ -1017,28 +1017,28 @@ impl InputWeightPrediction {
/// signature grinding.
///
/// [signature grinding]: https://bitcoin.stackexchange.com/questions/111660/what-is-signature-grinding
- pub const P2PKH_COMPRESSED_MAX: Self = InputWeightPrediction::from_slice(107, &[]);
+ pub const P2PKH_COMPRESSED_MAX: Self = Self::from_slice(107, &[]);
/// Input weight prediction corresponding to spending of a P2PKH output with the largest possible
/// DER-encoded signature, and an uncompressed public key.
///
/// If the input in your transaction uses P2PKH with an uncompressed key, you can use this instead of
/// [`InputWeightPrediction::new`].
- pub const P2PKH_UNCOMPRESSED_MAX: Self = InputWeightPrediction::from_slice(139, &[]);
+ pub const P2PKH_UNCOMPRESSED_MAX: Self = Self::from_slice(139, &[]);
/// Input weight prediction corresponding to spending of Taproot output using the key and
/// default sighash.
///
/// If the input in your transaction uses Taproot key spend you can use this instead of
/// [`InputWeightPrediction::new`].
- pub const P2TR_KEY_DEFAULT_SIGHASH: Self = InputWeightPrediction::from_slice(0, &[64]);
+ pub const P2TR_KEY_DEFAULT_SIGHASH: Self = Self::from_slice(0, &[64]);
/// Input weight prediction corresponding to spending of Taproot output using the key and
/// **non**-default sighash.
///
/// If the input in your transaction uses Taproot key spend you can use this instead of
/// [`InputWeightPrediction::new`].
- pub const P2TR_KEY_NON_DEFAULT_SIGHASH: Self = InputWeightPrediction::from_slice(0, &[65]);
+ pub const P2TR_KEY_NON_DEFAULT_SIGHASH: Self = Self::from_slice(0, &[65]);
const fn saturate_to_u32(x: usize) -> u32 {
if x > u32::MAX as usize {
@@ -1074,7 +1074,7 @@ impl InputWeightPrediction {
pub const fn ground_p2wpkh(bytes_to_grind: usize) -> Self {
// Written to trigger const/debug panic for unreasonably high values.
let der_signature_size = 10 + (62 - bytes_to_grind);
- InputWeightPrediction::from_slice(0, &[der_signature_size, 33])
+ Self::from_slice(0, &[der_signature_size, 33])
}
/// Input weight prediction corresponding to spending of [nested P2WPKH] output using [signature
@@ -1095,7 +1095,7 @@ impl InputWeightPrediction {
pub const fn ground_nested_p2wpkh(bytes_to_grind: usize) -> Self {
// Written to trigger const/debug panic for unreasonably high values.
let der_signature_size = 10 + (62 - bytes_to_grind);
- InputWeightPrediction::from_slice(23, &[der_signature_size, 33])
+ Self::from_slice(23, &[der_signature_size, 33])
}
/// Input weight prediction corresponding to spending of a P2PKH output using [signature
@@ -1116,7 +1116,7 @@ impl InputWeightPrediction {
// Written to trigger const/debug panic for unreasonably high values.
let der_signature_size = 10 + (62 - bytes_to_grind);
- InputWeightPrediction::from_slice(2 + 33 + der_signature_size, &[])
+ Self::from_slice(2 + 33 + der_signature_size, &[])
}
/// Computes the prediction for a single input.
@@ -1138,7 +1138,7 @@ impl InputWeightPrediction {
let script_size =
Self::saturate_to_u32(input_script_len) + Self::encoded_size(input_script_len);
- InputWeightPrediction { script_size, witness_size }
+ Self { script_size, witness_size }
}
/// Computes the prediction for a single input in `const` context.
@@ -1165,7 +1165,7 @@ impl InputWeightPrediction {
let script_size = Self::saturate_to_u32(input_script_len)
.saturating_add(Self::encoded_size(input_script_len));
- InputWeightPrediction { script_size, witness_size }
+ Self { script_size, witness_size }
}
/// Computes the **signature weight** added to a transaction by an input with this weight prediction,
@@ -1270,21 +1270,21 @@ mod sealed {
impl<'a> Arbitrary<'a> for InputWeightPrediction {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
match u.int_in_range(0..=7)? {
- 0 => Ok(InputWeightPrediction::P2WPKH_MAX),
- 1 => Ok(InputWeightPrediction::NESTED_P2WPKH_MAX),
- 2 => Ok(InputWeightPrediction::P2PKH_COMPRESSED_MAX),
- 3 => Ok(InputWeightPrediction::P2PKH_UNCOMPRESSED_MAX),
- 4 => Ok(InputWeightPrediction::P2TR_KEY_DEFAULT_SIGHASH),
- 5 => Ok(InputWeightPrediction::P2TR_KEY_NON_DEFAULT_SIGHASH),
+ 0 => Ok(Self::P2WPKH_MAX),
+ 1 => Ok(Self::NESTED_P2WPKH_MAX),
+ 2 => Ok(Self::P2PKH_COMPRESSED_MAX),
+ 3 => Ok(Self::P2PKH_UNCOMPRESSED_MAX),
+ 4 => Ok(Self::P2TR_KEY_DEFAULT_SIGHASH),
+ 5 => Ok(Self::P2TR_KEY_NON_DEFAULT_SIGHASH),
6 => {
let input_script_len = usize::arbitrary(u)?;
let witness_element_lengths: Vec<usize> = Vec::arbitrary(u)?;
- Ok(InputWeightPrediction::new(input_script_len, witness_element_lengths))
+ Ok(Self::new(input_script_len, witness_element_lengths))
}
_ => {
let input_script_len = usize::arbitrary(u)?;
let witness_element_lengths: Vec<usize> = Vec::arbitrary(u)?;
- Ok(InputWeightPrediction::from_slice(input_script_len, &witness_element_lengths))
+ Ok(Self::from_slice(input_script_len, &witness_element_lengths))
}
}
}
diff --git a/bitcoin/src/blockdata/witness.rs b/bitcoin/src/blockdata/witness.rs
index 59df9380..ebb6eda5 100644
--- a/bitcoin/src/blockdata/witness.rs
+++ b/bitcoin/src/blockdata/witness.rs
@@ -34,7 +34,7 @@ impl Decodable for Witness {
.into());
}
if witness_elements == 0 {
- Ok(Witness::default())
+ Ok(Self::default())
} else {
// Leave space at the head for element positions.
// We will rotate them to the end of the Vec later.
@@ -82,7 +82,7 @@ impl Decodable for Witness {
// Index space is now at the end of the Vec
content.rotate_left(witness_index_space);
let indices_start = cursor - witness_index_space;
- Ok(Witness::from_parts__unstable(content, witness_elements, indices_start))
+ Ok(Self::from_parts__unstable(content, witness_elements, indices_start))
}
}
}
diff --git a/bitcoin/src/consensus/encode.rs b/bitcoin/src/consensus/encode.rs
index eafe8212..bad559bb 100644
--- a/bitcoin/src/consensus/encode.rs
+++ b/bitcoin/src/consensus/encode.rs
@@ -373,7 +373,7 @@ impl Encodable for bool {
impl Decodable for bool {
#[inline]
- fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<bool, Error> {
+ fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
ReadExt::read_bool(r)
}
}
@@ -387,8 +387,8 @@ impl Encodable for String {
impl Decodable for String {
#[inline]
- fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<String, Error> {
- String::from_utf8(Decodable::consensus_decode(r)?)
+ fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
+ Self::from_utf8(Decodable::consensus_decode(r)?)
.map_err(|_| super::parse_failed_error("String was not valid UTF8"))
}
}
@@ -402,7 +402,7 @@ impl Encodable for Cow<'static, str> {
impl Decodable for Cow<'static, str> {
#[inline]
- fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Cow<'static, str>, Error> {
+ fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
String::from_utf8(Decodable::consensus_decode(r)?)
.map_err(|_| super::parse_failed_error("String was not valid UTF8"))
.map(Cow::Owned)
@@ -491,7 +491,7 @@ impl<T: Decodable + 'static> Decodable for Vec<T> {
#[inline]
fn consensus_decode_from_finite_reader<R: BufRead + ?Sized>(
r: &mut R,
- ) -> Result<Vec<T>, Error> {
+ ) -> Result<Self, Error> {
if TypeId::of::<T>() == TypeId::of::<u8>() {
let len = r.read_compact_size()? as usize;
// most real-world vec of bytes data, wouldn't be larger than 128KiB
@@ -499,7 +499,7 @@ impl<T: Decodable + 'static> Decodable for Vec<T> {
let bytes = read_bytes_from_finite_reader(r, opts)?;
// unsafe: We've just checked that T is `u8` so the transmute here is a no-op.
- unsafe { Ok(mem::transmute::<Vec<u8>, Vec<T>>(bytes)) }
+ unsafe { Ok(mem::transmute::<Vec<u8>, Self>(bytes)) }
} else {
let len = r.read_compact_size()?;
// Do not allocate upfront more items than if the sequence of type
@@ -509,7 +509,7 @@ impl<T: Decodable + 'static> Decodable for Vec<T> {
// Note: OOM protection relies on reader eventually running out of
// data to feed us.
let max_capacity = MAX_VEC_SIZE / 4 / mem::size_of::<T>();
- let mut ret = Vec::with_capacity(cmp::min(len as usize, max_capacity));
+ let mut ret = Self::with_capacity(cmp::min(len as usize, max_capacity));
for _ in 0..len {
ret.push(Decodable::consensus_decode_from_finite_reader(r)?);
}
diff --git a/bitcoin/src/consensus/error.rs b/bitcoin/src/consensus/error.rs
index 00c86936..4fe207f5 100644
--- a/bitcoin/src/consensus/error.rs
+++ b/bitcoin/src/consensus/error.rs
@@ -137,14 +137,14 @@ impl From<io::Error> for Error {
use io::ErrorKind;
match e.kind() {
- ErrorKind::UnexpectedEof => Error::Parse(ParseError::MissingData),
- _ => Error::Io(e),
+ ErrorKind::UnexpectedEof => Self::Parse(ParseError::MissingData),
+ _ => Self::Io(e),
}
}
}
impl From<ParseError> for Error {
- fn from(e: ParseError) -> Self { Error::Parse(e) }
+ fn from(e: ParseError) -> Self { Self::Parse(e) }
}
/// Encoding is invalid.
diff --git a/bitcoin/src/consensus/mod.rs b/bitcoin/src/consensus/mod.rs
index ecf4b6fd..dbfa9c4d 100644
--- a/bitcoin/src/consensus/mod.rs
+++ b/bitcoin/src/consensus/mod.rs
@@ -32,7 +32,7 @@ struct IterReader<E: fmt::Debug, I: Iterator<Item = Result<u8, E>>> {
impl<E: fmt::Debug, I: Iterator<Item = Result<u8, E>>> IterReader<E, I> {
pub(crate) fn new(iterator: I) -> Self {
- IterReader { iterator: iterator.fuse(), buf: None, error: None }
+ Self { iterator: iterator.fuse(), buf: None, error: None }
}
fn decode<T: Decodable>(mut self) -> Result<T, DecodeError<E>> {
diff --git a/bitcoin/src/consensus/serde.rs b/bitcoin/src/consensus/serde.rs
index 15b6e5f1..d673085b 100644
--- a/bitcoin/src/consensus/serde.rs
+++ b/bitcoin/src/consensus/serde.rs
@@ -26,7 +26,7 @@ where
Case: hex::Case;
impl<C: hex::Case> Default for Hex<C> {
- fn default() -> Self { Hex(Default::default()) }
+ fn default() -> Self { Self(Default::default()) }
}
impl<C: hex::Case> ByteEncoder for Hex<C> {
@@ -75,7 +75,7 @@ pub mod hex {
impl<C: Case> From<super::Hex<C>> for Encoder<C> {
fn from(_: super::Hex<C>) -> Self {
- Encoder(BufEncoder::new(C::INTERNAL_CASE), Default::default())
+ Self(BufEncoder::new(C::INTERNAL_CASE), Default::default())
}
}
@@ -194,7 +194,7 @@ struct ErrorTrackingWriter<W: fmt::Write> {
impl<W: fmt::Write> ErrorTrackingWriter<W> {
fn new(writer: W) -> Self {
- ErrorTrackingWriter {
+ Self {
writer,
#[cfg(debug_assertions)]
was_error: false,
@@ -387,9 +387,9 @@ where
{
fn unify(self) -> E {
match self {
- DecodeError::Other(error) => error,
- DecodeError::Unconsumed => E::custom(format_args!("got more bytes than expected")),
- DecodeError::Parse(e) => consensus_error_into_serde(e),
+ Self::Other(error) => error,
+ Self::Unconsumed => E::custom(format_args!("got more bytes than expected")),
+ Self::Parse(e) => consensus_error_into_serde(e),
}
}
}
@@ -400,9 +400,9 @@ where
{
fn into_de_error<DE: serde::de::Error>(self) -> DE {
match self {
- DecodeError::Other(error) => error.into_de_error(),
- DecodeError::Unconsumed => DE::custom(format_args!("got more bytes than expected")),
- DecodeError::Parse(e) => consensus_error_into_serde(e),
+ Self::Other(error) => error.into_de_error(),
+ Self::Unconsumed => DE::custom(format_args!("got more bytes than expected")),
+ Self::Parse(e) => consensus_error_into_serde(e),
}
}
}
diff --git a/bitcoin/src/consensus_validation.rs b/bitcoin/src/consensus_validation.rs
index d4128b10..cf5343c3 100644
--- a/bitcoin/src/consensus_validation.rs
+++ b/bitcoin/src/consensus_validation.rs
@@ -266,5 +266,5 @@ impl std::error::Error for TxVerifyError {
}
impl From<BitcoinconsensusError> for TxVerifyError {
- fn from(e: BitcoinconsensusError) -> Self { TxVerifyError::ScriptVerification(e) }
+ fn from(e: BitcoinconsensusError) -> Self { Self::ScriptVerification(e) }
}
diff --git a/bitcoin/src/crypto/ecdsa.rs b/bitcoin/src/crypto/ecdsa.rs
index 617612f9..0b5a1462 100644
--- a/bitcoin/src/crypto/ecdsa.rs
+++ b/bitcoin/src/crypto/ecdsa.rs
@@ -34,8 +34,8 @@ pub struct Signature {
impl Signature {
/// Constructs a new ECDSA Bitcoin signature for [`EcdsaSighashType::All`].
- pub fn sighash_all(signature: secp256k1::ecdsa::Signature) -> Signature {
- Signature { signature, sighash_type: EcdsaSighashType::All }
+ pub fn sighash_all(signature: secp256k1::ecdsa::Signature) -> Self {
+ Self { signature, sighash_type: EcdsaSighashType::All }
}
/// Deserializes from slice following the standardness rules for [`EcdsaSighashType`].
@@ -44,7 +44,7 @@ impl Signature {
let sighash_type = EcdsaSighashType::from_standard(*sighash_type as u32)?;
let signature =
secp256k1::ecdsa::Signature::from_der(sig).map_err(DecodeError::Secp256k1)?;
- Ok(Signature { signature, sighash_type })
+ Ok(Self { signature, sighash_type })
}
/// Serializes an ECDSA signature (inner secp256k1 signature in DER format).
@@ -186,7 +186,7 @@ impl fmt::UpperHex for SerializedSignature {
impl PartialEq for SerializedSignature {
#[inline]
- fn eq(&self, other: &SerializedSignature) -> bool { **self == **other }
+ fn eq(&self, other: &Self) -> bool { **self == **other }
}
impl Eq for SerializedSignature {}
@@ -325,7 +325,7 @@ impl<'a> Arbitrary<'a> for Signature {
signature_bytes[..32].copy_from_slice(&bytes);
signature_bytes[32..].copy_from_slice(&bytes);
- Ok(Signature {
+ Ok(Self {
signature: secp256k1::ecdsa::Signature::from_compact(&signature_bytes).unwrap(),
sighash_type: EcdsaSighashType::arbitrary(u)?,
})
diff --git a/bitcoin/src/crypto/key.rs b/bitcoin/src/crypto/key.rs
index d2f2e5ef..db618b03 100644
--- a/bitcoin/src/crypto/key.rs
+++ b/bitcoin/src/crypto/key.rs
@@ -37,17 +37,15 @@ pub struct XOnlyPublicKey(secp256k1::XOnlyPublicKey);
impl XOnlyPublicKey {
/// Constructs a new x-only public key from the provided generic secp256k1 x-only public key.
- pub fn new(key: impl Into<secp256k1::XOnlyPublicKey>) -> XOnlyPublicKey {
- XOnlyPublicKey(key.into())
- }
+ pub fn new(key: impl Into<secp256k1::XOnlyPublicKey>) -> Self { Self(key.into()) }
/// Constructs an x-only public key from a keypair.
///
/// Returns the x-only public key and the parity of the full public key.
#[inline]
- pub fn from_keypair(keypair: &Keypair) -> (XOnlyPublicKey, Parity) {
+ pub fn from_keypair(keypair: &Keypair) -> (Self, Parity) {
let (xonly, parity) = secp256k1::XOnlyPublicKey::from_keypair(keypair);
- (XOnlyPublicKey::new(xonly), parity)
+ (Self::new(xonly), parity)
}
/// Constructs an x-only public key from a 32-byte x-coordinate.
@@ -56,9 +54,9 @@ impl XOnlyPublicKey {
#[inline]
pub fn from_byte_array(
data: &[u8; constants::SCHNORR_PUBLIC_KEY_SIZE],
- ) -> Result<XOnlyPublicKey, ParseXOnlyPublicKeyError> {
+ ) -> Result<Self, ParseXOnlyPublicKeyError> {
secp256k1::XOnlyPublicKey::from_byte_array(data)
- .map(XOnlyPublicKey::new)
+ .map(Self::new)
.map_err(|_| ParseXOnlyPublicKeyError::InvalidXCoordinate)
}
@@ -101,9 +99,9 @@ impl XOnlyPublicKey {
&self,
secp: &Secp256k1<V>,
tweak: &secp256k1::Scalar,
- ) -> Result<(XOnlyPublicKey, Parity), TweakXOnlyPublicKeyError> {
+ ) -> Result<(Self, Parity), TweakXOnlyPublicKeyError> {
match self.0.add_tweak(secp, tweak) {
- Ok((xonly, parity)) => Ok((XOnlyPublicKey(xonly), parity)),
+ Ok((xonly, parity)) => Ok((Self(xonly), parity)),
Err(secp256k1::Error::InvalidTweak) => Err(TweakXOnlyPublicKeyError::BadTweak),
Err(secp256k1::Error::InvalidParityValue(_)) =>
Err(TweakXOnlyPublicKeyError::ParityError),
@@ -114,19 +112,19 @@ impl XOnlyPublicKey {
impl FromStr for XOnlyPublicKey {
type Err = ParseXOnlyPublicKeyError;
- fn from_str(s: &str) -> Result<XOnlyPublicKey, ParseXOnlyPublicKeyError> {
+ fn from_str(s: &str) -> Result<Self, ParseXOnlyPublicKeyError> {
secp256k1::XOnlyPublicKey::from_str(s)
- .map(XOnlyPublicKey::from)
+ .map(Self::from)
.map_err(|_| ParseXOnlyPublicKeyError::InvalidXCoordinate)
}
}
impl From<secp256k1::XOnlyPublicKey> for XOnlyPublicKey {
- fn from(pk: secp256k1::XOnlyPublicKey) -> XOnlyPublicKey { XOnlyPublicKey::new(pk) }
+ fn from(pk: secp256k1::XOnlyPublicKey) -> Self { Self::new(pk) }
}
impl From<secp256k1::PublicKey> for XOnlyPublicKey {
- fn from(pk: secp256k1::PublicKey) -> XOnlyPublicKey { XOnlyPublicKey::new(pk) }
+ fn from(pk: secp256k1::PublicKey) -> Self { Self::new(pk) }
}
impl fmt::LowerHex for XOnlyPublicKey {
@@ -150,14 +148,14 @@ pub struct PublicKey {
impl PublicKey {
/// Constructs a new compressed ECDSA public key from the provided generic secp256k1 public key.
- pub fn new(key: impl Into<secp256k1::PublicKey>) -> PublicKey {
- PublicKey { compressed: true, inner: key.into() }
+ pub fn new(key: impl Into<secp256k1::PublicKey>) -> Self {
+ Self { compressed: true, inner: key.into() }
}
/// Constructs a new uncompressed (legacy) ECDSA public key from the provided generic secp256k1
/// public key.
- pub fn new_uncompressed(key: impl Into<secp256k1::PublicKey>) -> PublicKey {
- PublicKey { compressed: false, inner: key.into() }
+ pub fn new_uncompressed(key: impl Into<secp256k1::PublicKey>) -> Self {
+ Self { compressed: false, inner: key.into() }
}
fn with_serialized<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
@@ -295,7 +293,7 @@ impl PublicKey {
}
/// Deserializes a public key from a slice.
- pub fn from_slice(data: &[u8]) -> Result<PublicKey, FromSliceError> {
+ pub fn from_slice(data: &[u8]) -> Result<Self, FromSliceError> {
let compressed = match data.len() {
33 => true,
65 => false,
@@ -308,14 +306,11 @@ impl PublicKey {
return Err(FromSliceError::InvalidKeyPrefix(data[0]));
}
- Ok(PublicKey { compressed, inner: secp256k1::PublicKey::from_slice(data)? })
+ Ok(Self { compressed, inner: secp256k1::PublicKey::from_slice(data)? })
}
/// Computes the public key as supposed to be used with this secret.
- pub fn from_private_key<C: secp256k1::Signing>(
- secp: &Secp256k1<C>,
- sk: PrivateKey,
- ) -> PublicKey {
+ pub fn from_private_key<C: secp256k1::Signing>(secp: &Secp256k1<C>, sk: PrivateKey) -> Self {
sk.public_key(secp)
}
@@ -331,11 +326,11 @@ impl PublicKey {
}
impl From<secp256k1::PublicKey> for PublicKey {
- fn from(pk: secp256k1::PublicKey) -> PublicKey { PublicKey::new(pk) }
+ fn from(pk: secp256k1::PublicKey) -> Self { Self::new(pk) }
}
impl From<PublicKey> for XOnlyPublicKey {
- fn from(pk: PublicKey) -> XOnlyPublicKey { XOnlyPublicKey::new(pk.inner) }
+ fn from(pk: PublicKey) -> Self { Self::new(pk.inner) }
}
/// An opaque return type for PublicKey::to_sort_key.
@@ -350,7 +345,7 @@ impl fmt::Display for PublicKey {
impl FromStr for PublicKey {
type Err = ParsePublicKeyError;
- fn from_str(s: &str) -> Result<PublicKey, ParsePublicKeyError> {
+ fn from_str(s: &str) -> Result<Self, ParsePublicKeyError> {
use HexToArrayError::*;
match s.len() {
@@ -359,14 +354,14 @@ impl FromStr for PublicKey {
InvalidChar(e) => ParsePublicKeyError::InvalidChar(e),
InvalidLength(_) => unreachable!("length checked already"),
})?;
- Ok(PublicKey::from_slice(&bytes)?)
+ Ok(Self::from_slice(&bytes)?)
}
130 => {
let bytes = <[u8; 65]>::from_hex(s).map_err(|e| match e {
InvalidChar(e) => ParsePublicKeyError::InvalidChar(e),
InvalidLength(_) => unreachable!("length checked already"),
})?;
- Ok(PublicKey::from_slice(&bytes)?)
+ Ok(Self::from_slice(&bytes)?)
}
len => Err(ParsePublicKeyError::InvalidHexLength(len)),
}
@@ -387,11 +382,11 @@ hashes::impl_serde_for_newtype!(PubkeyHash, WPubkeyHash);
impl_asref_push_bytes!(PubkeyHash, WPubkeyHash);
impl From<PublicKey> for PubkeyHash {
- fn from(key: PublicKey) -> PubkeyHash { key.pubkey_hash() }
+ fn from(key: PublicKey) -> Self { key.pubkey_hash() }
}
impl From<&PublicKey> for PubkeyHash {
- fn from(key: &PublicKey) -> PubkeyHash { key.pubkey_hash() }
+ fn from(key: &PublicKey) -> Self { key.pubkey_hash() }
}
/// An always-compressed Bitcoin ECDSA public key.
@@ -488,7 +483,7 @@ impl FromStr for CompressedPublicKey {
type Err = ParseCompressedPublicKeyError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
- CompressedPublicKey::from_slice(&<[u8; 33]>::from_hex(s)?).map_err(Into::into)
+ Self::from_slice(&<[u8; 33]>::from_hex(s)?).map_err(Into::into)
}
}
@@ -497,7 +492,7 @@ impl TryFrom<PublicKey> for CompressedPublicKey {
fn try_from(value: PublicKey) -> Result<Self, Self::Error> {
if value.compressed {
- Ok(CompressedPublicKey(value.inner))
+ Ok(Self(value.inner))
} else {
Err(UncompressedPublicKeyError)
}
@@ -505,7 +500,7 @@ impl TryFrom<PublicKey> for CompressedPublicKey {
}
impl From<CompressedPublicKey> for PublicKey {
- fn from(value: CompressedPublicKey) -> Self { PublicKey::new(value.0) }
+ fn from(value: CompressedPublicKey) -> Self { Self::new(value.0) }
}
impl From<CompressedPublicKey> for XOnlyPublicKey {
@@ -543,23 +538,20 @@ impl PrivateKey {
/// Constructs a new compressed ECDSA private key using the secp256k1 algorithm and
/// a secure random number generator.
#[cfg(feature = "rand-std")]
- pub fn generate(network: impl Into<NetworkKind>) -> PrivateKey {
+ pub fn generate(network: impl Into<NetworkKind>) -> Self {
let secret_key = secp256k1::SecretKey::new(&mut rand::thread_rng());
- PrivateKey::new(secret_key, network.into())
+ Self::new(secret_key, network.into())
}
/// Constructs a new compressed ECDSA private key from the provided generic secp256k1 private key
/// and the specified network.
- pub fn new(key: secp256k1::SecretKey, network: impl Into<NetworkKind>) -> PrivateKey {
- PrivateKey { compressed: true, network: network.into(), inner: key }
+ pub fn new(key: secp256k1::SecretKey, network: impl Into<NetworkKind>) -> Self {
+ Self { compressed: true, network: network.into(), inner: key }
}
/// Constructs a new uncompressed (legacy) ECDSA private key from the provided generic secp256k1
/// private key and the specified network.
- pub fn new_uncompressed(
- key: secp256k1::SecretKey,
- network: impl Into<NetworkKind>,
- ) -> PrivateKey {
- PrivateKey { compressed: false, network: network.into(), inner: key }
+ pub fn new_uncompressed(key: secp256k1::SecretKey, network: impl Into<NetworkKind>) -> Self {
+ Self { compressed: false, network: network.into(), inner: key }
}
/// Constructs a new public key from this private key.
@@ -581,8 +573,8 @@ impl PrivateKey {
pub fn from_byte_array(
data: [u8; 32],
network: impl Into<NetworkKind>,
- ) -> Result<PrivateKey, secp256k1::Error> {
- Ok(PrivateKey::new(secp256k1::SecretKey::from_byte_array(&data)?, network))
+ ) -> Result<Self, secp256k1::Error> {
+ Ok(Self::new(secp256k1::SecretKey::from_byte_array(&data)?, network))
}
/// Deserializes a private key from a slice.
@@ -590,7 +582,7 @@ impl PrivateKey {
pub fn from_slice(
data: &[u8],
network: impl Into<NetworkKind>,
- ) -> Result<PrivateKey, secp256k1::Error> {
+ ) -> Result<Self, secp256k1::Error> {
let array = data.try_into().map_err(|_| secp256k1::Error::InvalidSecretKey)?;
Self::from_byte_array(array, network)
}
@@ -620,7 +612,7 @@ impl PrivateKey {
}
/// Parses the WIF encoded private key.
- pub fn from_wif(wif: &str) -> Result<PrivateKey, FromWifError> {
+ pub fn from_wif(wif: &str) -> Result<Self, FromWifError> {
let data = base58::decode_check(wif)?;
let (compressed, data) = if let Ok(data) = <&[u8; 33]>::try_from(&*data) {
@@ -644,7 +636,7 @@ impl PrivateKey {
}
};
- Ok(PrivateKey { compressed, network, inner: secp256k1::SecretKey::from_byte_array(key)? })
+ Ok(Self { compressed, network, inner: secp256k1::SecretKey::from_byte_array(key)? })
}
/// Returns a new private key with the negated secret value.
@@ -654,11 +646,7 @@ impl PrivateKey {
/// with specific public key formats and BIP-0340 requirements.
#[inline]
pub fn negate(&self) -> Self {
- PrivateKey {
- compressed: self.compressed,
- network: self.network,
- inner: self.inner.negate(),
- }
+ Self { compressed: self.compressed, network: self.network, inner: self.inner.negate() }
}
}
@@ -668,7 +656,7 @@ impl fmt::Display for PrivateKey {
impl FromStr for PrivateKey {
type Err = FromWifError;
- fn from_str(s: &str) -> Result<PrivateKey, FromWifError> { PrivateKey::from_wif(s) }
+ fn from_str(s: &str) -> Result<Self, FromWifError> { Self::from_wif(s) }
}
impl ops::Index<ops::RangeFull> for PrivateKey {
@@ -685,7 +673,7 @@ impl serde::Serialize for PrivateKey {
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for PrivateKey {
- fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<PrivateKey, D::Error> {
+ fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct WifVisitor;
impl serde::de::Visitor<'_> for WifVisitor {
@@ -732,7 +720,7 @@ impl serde::Serialize for PublicKey {
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for PublicKey {
- fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<PublicKey, D::Error> {
+ fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
if d.is_human_readable() {
struct HexVisitor;
@@ -991,7 +979,7 @@ impl TweakedPublicKey {
#[inline]
pub fn from_keypair(keypair: TweakedKeypair) -> Self {
let (xonly, _parity) = keypair.0.x_only_public_key();
- TweakedPublicKey(xonly.into())
+ Self(xonly.into())
}
/// Constructs a new [`TweakedPublicKey`] from a [`XOnlyPublicKey`]. No tweak is applied, consider
@@ -1000,9 +988,7 @@ impl TweakedPublicKey {
/// This method is dangerous and can lead to loss of funds if used incorrectly.
/// Specifically, in multi-party protocols a peer can provide a value that allows them to steal.
#[inline]
- pub fn dangerous_assume_tweaked(key: XOnlyPublicKey) -> TweakedPublicKey {
- TweakedPublicKey(key)
- }
+ pub fn dangerous_assume_tweaked(key: XOnlyPublicKey) -> Self { Self(key) }
/// Returns the underlying public key.
#[inline]
@@ -1030,7 +1016,7 @@ impl TweakedKeypair {
/// This method is dangerous and can lead to loss of funds if used incorrectly.
/// Specifically, in multi-party protocols a peer can provide a value that allows them to steal.
#[inline]
- pub fn dangerous_assume_tweaked(pair: Keypair) -> TweakedKeypair { TweakedKeypair(pair) }
+ pub fn dangerous_assume_tweaked(pair: Keypair) -> Self { Self(pair) }
/// Returns the underlying key pair.
#[inline]
@@ -1066,7 +1052,7 @@ impl From<TweakedKeypair> for Keypair {
impl From<TweakedKeypair> for TweakedPublicKey {
#[inline]
- fn from(pair: TweakedKeypair) -> Self { TweakedPublicKey::from_keypair(pair) }
+ fn from(pair: TweakedKeypair) -> Self { Self::from_keypair(pair) }
}
/// Error returned while generating key from slice.
@@ -1173,19 +1159,15 @@ impl From<secp256k1::Error> for FromWifError {
}
impl From<InvalidBase58PayloadLengthError> for FromWifError {
- fn from(e: InvalidBase58PayloadLengthError) -> FromWifError {
- Self::InvalidBase58PayloadLength(e)
- }
+ fn from(e: InvalidBase58PayloadLengthError) -> Self { Self::InvalidBase58PayloadLength(e) }
}
impl From<InvalidAddressVersionError> for FromWifError {
- fn from(e: InvalidAddressVersionError) -> FromWifError { Self::InvalidAddressVersion(e) }
+ fn from(e: InvalidAddressVersionError) -> Self { Self::InvalidAddressVersion(e) }
}
impl From<InvalidWifCompressionFlagError> for FromWifError {
- fn from(e: InvalidWifCompressionFlagError) -> FromWifError {
- Self::InvalidWifCompressionFlag(e)
- }
+ fn from(e: InvalidWifCompressionFlagError) -> Self { Self::InvalidWifCompressionFlag(e) }
}
/// Error returned while constructing public key from string.
@@ -1391,8 +1373,8 @@ impl AsRef<[u8; 32]> for SerializedXOnlyPublicKey {
fn as_ref(&self) -> &[u8; 32] { self.as_byte_array() }
}
-impl From<&SerializedXOnlyPublicKey> for SerializedXOnlyPublicKey {
- fn from(borrowed: &SerializedXOnlyPublicKey) -> Self { *borrowed }
+impl From<&Self> for SerializedXOnlyPublicKey {
+ fn from(borrowed: &Self) -> Self { *borrowed }
}
impl fmt::Debug for SerializedXOnlyPublicKey {
diff --git a/bitcoin/src/crypto/sighash.rs b/bitcoin/src/crypto/sighash.rs
index 0b0806cc..550c34db 100644
--- a/bitcoin/src/crypto/sighash.rs
+++ b/bitcoin/src/crypto/sighash.rs
@@ -355,7 +355,7 @@ impl<'s> ScriptPath<'s> {
}
impl<'s> From<ScriptPath<'s>> for TapLeafHash {
- fn from(script_path: ScriptPath<'s>) -> TapLeafHash { script_path.leaf_hash() }
+ fn from(script_path: ScriptPath<'s>) -> Self { script_path.leaf_hash() }
}
/// Hashtype of an input's signature, encoded in the last byte of the signature.
@@ -419,7 +419,7 @@ impl str::FromStr for EcdsaSighashType {
impl EcdsaSighashType {
/// Splits the sighash flag into the "real" sighash flag and the ANYONECANPAY boolean.
- pub(crate) fn split_anyonecanpay_flag(self) -> (EcdsaSighashType, bool) {
+ pub(crate) fn split_anyonecanpay_flag(self) -> (Self, bool) {
use EcdsaSighashType::*;
match self {
@@ -449,7 +449,7 @@ impl EcdsaSighashType {
/// `EcdsaSighashType::from_consensus(n) as u32 != n` for non-standard values of `n`. While
/// verifying signatures, the user should retain the `n` and use it to compute the signature hash
/// message.
- pub fn from_consensus(n: u32) -> EcdsaSighashType {
+ pub fn from_consensus(n: u32) -> Self {
use EcdsaSighashType::*;
// In Bitcoin Core, the SignatureHash function will mask the (int32) value with
@@ -476,7 +476,7 @@ impl EcdsaSighashType {
/// # Errors
///
/// If `n` is a non-standard sighash value.
- pub fn from_standard(n: u32) -> Result<EcdsaSighashType, NonStandardSighashTypeError> {
+ pub fn from_standard(n: u32) -> Result<Self, NonStandardSighashTypeError> {
use EcdsaSighashType::*;
match n {
@@ -514,7 +514,7 @@ impl From<EcdsaSighashType> for TapSighashType {
impl TapSighashType {
/// Breaks the sighash flag into the "real" sighash flag and the `SIGHASH_ANYONECANPAY` boolean.
- pub(crate) fn split_anyonecanpay_flag(self) -> (TapSighashType, bool) {
+ pub(crate) fn split_anyonecanpay_flag(self) -> (Self, bool) {
use TapSighashType::*;
match self {
@@ -604,7 +604,7 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
/// sighashes to be valid, no fields in the transaction may change except for script_sig and
/// witness.
pub fn new(tx: R) -> Self {
- SighashCache { tx, common_cache: None, taproot_cache: None, segwit_cache: None }
+ Self { tx, common_cache: None, taproot_cache: None, segwit_cache: None }
}
/// Returns the reference to the cached transaction.
@@ -1284,7 +1284,7 @@ impl From<Infallible> for P2wpkhError {
}
impl From<transaction::InputsIndexError> for P2wpkhError {
- fn from(value: transaction::InputsIndexError) -> Self { P2wpkhError::Sighash(value) }
+ fn from(value: transaction::InputsIndexError) -> Self { Self::Sighash(value) }
}
impl fmt::Display for P2wpkhError {
@@ -1425,9 +1425,9 @@ impl<E> EncodeSigningDataResult<E> {
#[allow(clippy::wrong_self_convention)] // Consume self so we can take the error.
pub fn is_sighash_single_bug(self) -> Result<bool, E> {
match self {
- EncodeSigningDataResult::SighashSingleBug => Ok(true),
- EncodeSigningDataResult::WriteResult(Ok(())) => Ok(false),
- EncodeSigningDataResult::WriteResult(Err(e)) => Err(e),
+ Self::SighashSingleBug => Ok(true),
+ Self::WriteResult(Ok(())) => Ok(false),
+ Self::WriteResult(Err(e)) => Err(e),
}
}
@@ -1440,10 +1440,10 @@ impl<E> EncodeSigningDataResult<E> {
F: FnOnce(E) -> E2,
{
match self {
- EncodeSigningDataResult::SighashSingleBug => EncodeSigningDataResult::SighashSingleBug,
- EncodeSigningDataResult::WriteResult(Err(e)) =>
+ Self::SighashSingleBug => EncodeSigningDataResult::SighashSingleBug,
+ Self::WriteResult(Err(e)) =>
EncodeSigningDataResult::WriteResult(Err(f(e))),
- EncodeSigningDataResult::WriteResult(Ok(o)) =>
+ Self::WriteResult(Ok(o)) =>
EncodeSigningDataResult::WriteResult(Ok(o)),
}
}
@@ -1496,8 +1496,8 @@ impl<E: fmt::Display> fmt::Display for SigningDataError<E> {
impl<E: std::error::Error + 'static> std::error::Error for SigningDataError<E> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
- SigningDataError::Io(error) => Some(error),
- SigningDataError::Sighash(error) => Some(error),
+ Self::Io(error) => Some(error),
+ Self::Sighash(error) => Some(error),
}
}
}
@@ -1507,12 +1507,12 @@ impl<'a> Arbitrary<'a> for EcdsaSighashType {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
let choice = u.int_in_range(0..=5)?;
match choice {
- 0 => Ok(EcdsaSighashType::All),
- 1 => Ok(EcdsaSighashType::None),
- 2 => Ok(EcdsaSighashType::Single),
- 3 => Ok(EcdsaSighashType::AllPlusAnyoneCanPay),
- 4 => Ok(EcdsaSighashType::NonePlusAnyoneCanPay),
- _ => Ok(EcdsaSighashType::SinglePlusAnyoneCanPay),
+ 0 => Ok(Self::All),
+ 1 => Ok(Self::None),
+ 2 => Ok(Self::Single),
+ 3 => Ok(Self::AllPlusAnyoneCanPay),
+ 4 => Ok(Self::NonePlusAnyoneCanPay),
+ _ => Ok(Self::SinglePlusAnyoneCanPay),
}
}
}
@@ -1522,13 +1522,13 @@ impl<'a> Arbitrary<'a> for TapSighashType {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
let choice = u.int_in_range(0..=6)?;
match choice {
- 0 => Ok(TapSighashType::Default),
- 1 => Ok(TapSighashType::All),
- 2 => Ok(TapSighashType::None),
- 3 => Ok(TapSighashType::Single),
- 4 => Ok(TapSighashType::AllPlusAnyoneCanPay),
- 5 => Ok(TapSighashType::NonePlusAnyoneCanPay),
- _ => Ok(TapSighashType::SinglePlusAnyoneCanPay),
+ 0 => Ok(Self::Default),
+ 1 => Ok(Self::All),
+ 2 => Ok(Self::None),
+ 3 => Ok(Self::Single),
+ 4 => Ok(Self::AllPlusAnyoneCanPay),
+ 5 => Ok(Self::NonePlusAnyoneCanPay),
+ _ => Ok(Self::SinglePlusAnyoneCanPay),
}
}
}
diff --git a/bitcoin/src/crypto/taproot.rs b/bitcoin/src/crypto/taproot.rs
index 87f18a8a..db7aa4b1 100644
--- a/bitcoin/src/crypto/taproot.rs
+++ b/bitcoin/src/crypto/taproot.rs
@@ -33,12 +33,12 @@ impl Signature {
if let Ok(signature) = <[u8; 64]>::try_from(sl) {
// default type
let signature = secp256k1::schnorr::Signature::from_byte_array(signature);
- Ok(Signature { signature, sighash_type: TapSighashType::Default })
+ Ok(Self { signature, sighash_type: TapSighashType::Default })
} else if let Ok(signature) = <[u8; 65]>::try_from(sl) {
let (sighash_type, signature) = signature.split_last();
let sighash_type = TapSighashType::from_consensus_u8(*sighash_type)?;
let signature = secp256k1::schnorr::Signature::from_byte_array(*signature);
- Ok(Signature { signature, sighash_type })
+ Ok(Self { signature, sighash_type })
} else {
Err(SigFromSliceError::InvalidSignatureSize(sl.len()))
}
@@ -138,7 +138,7 @@ impl<'a> Arbitrary<'a> for Signature {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
let arbitrary_bytes: [u8; secp256k1::constants::SCHNORR_SIGNATURE_SIZE] = u.arbitrary()?;
- Ok(Signature {
+ Ok(Self {
signature: secp256k1::schnorr::Signature::from_byte_array(arbitrary_bytes),
sighash_type: TapSighashType::arbitrary(u)?,
})
diff --git a/bitcoin/src/lib.rs b/bitcoin/src/lib.rs
index 5a95be55..c1565833 100644
--- a/bitcoin/src/lib.rs
+++ b/bitcoin/src/lib.rs
@@ -251,7 +251,7 @@ pub mod amount {
impl Decodable for Amount {
#[inline]
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- Amount::from_sat(Decodable::consensus_decode(r)?).map_err(|_| {
+ Self::from_sat(Decodable::consensus_decode(r)?).map_err(|_| {
consensus::parse_failed_error("amount is greater than Amount::MAX_MONEY")
})
}
diff --git a/bitcoin/src/merkle_tree/block.rs b/bitcoin/src/merkle_tree/block.rs
index 7a8987f7..55eee568 100644
--- a/bitcoin/src/merkle_tree/block.rs
+++ b/bitcoin/src/merkle_tree/block.rs
@@ -99,7 +99,7 @@ impl MerkleBlock {
let matches: Vec<bool> = block_txids.iter().map(match_txids).collect();
let pmt = PartialMerkleTree::from_txids(block_txids, &matches);
- MerkleBlock { header: *header, txn: pmt }
+ Self { header: *header, txn: pmt }
}
/// Extracts the matching txid's represented by this partial Merkle tree
@@ -129,7 +129,7 @@ impl Encodable for MerkleBlock {
impl Decodable for MerkleBlock {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- Ok(MerkleBlock {
+ Ok(Self {
header: Decodable::consensus_decode(r)?,
txn: Decodable::consensus_decode(r)?,
})
@@ -223,7 +223,7 @@ impl PartialMerkleTree {
assert_ne!(txids.len(), 0);
assert_eq!(txids.len(), matches.len());
- let mut pmt = PartialMerkleTree {
+ let mut pmt = Self {
num_transactions: txids.len() as u32,
bits: Vec::with_capacity(txids.len()),
hashes: vec![],
@@ -445,7 +445,7 @@ impl Decodable for PartialMerkleTree {
}
}
- Ok(PartialMerkleTree { num_transactions, hashes, bits })
+ Ok(Self { num_transactions, hashes, bits })
}
}
@@ -515,7 +515,7 @@ impl std::error::Error for MerkleBlockError {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for PartialMerkleTree {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(PartialMerkleTree {
+ Ok(Self {
num_transactions: u.arbitrary()?,
bits: Vec::<bool>::arbitrary(u)?,
hashes: Vec::<TxMerkleNode>::arbitrary(u)?,
@@ -526,7 +526,7 @@ impl<'a> Arbitrary<'a> for PartialMerkleTree {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for MerkleBlock {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(MerkleBlock { header: u.arbitrary()?, txn: u.arbitrary()? })
+ Ok(Self { header: u.arbitrary()?, txn: u.arbitrary()? })
}
}
diff --git a/bitcoin/src/merkle_tree/mod.rs b/bitcoin/src/merkle_tree/mod.rs
index 760c57cf..bd677931 100644
--- a/bitcoin/src/merkle_tree/mod.rs
+++ b/bitcoin/src/merkle_tree/mod.rs
@@ -38,7 +38,7 @@ impl Encodable for TxMerkleNode {
impl Decodable for TxMerkleNode {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- Ok(TxMerkleNode::from_byte_array(<[u8; 32]>::consensus_decode(r)?))
+ Ok(Self::from_byte_array(<[u8; 32]>::consensus_decode(r)?))
}
}
@@ -50,7 +50,7 @@ impl Encodable for WitnessMerkleNode {
impl Decodable for WitnessMerkleNode {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- Ok(WitnessMerkleNode::from_byte_array(<[u8; 32]>::consensus_decode(r)?))
+ Ok(Self::from_byte_array(<[u8; 32]>::consensus_decode(r)?))
}
}
diff --git a/bitcoin/src/network/mod.rs b/bitcoin/src/network/mod.rs
index f98114d0..3de1b280 100644
--- a/bitcoin/src/network/mod.rs
+++ b/bitcoin/src/network/mod.rs
@@ -35,7 +35,7 @@ pub enum NetworkKind {
// ambiguous due to confusion caused by signet/testnet/regtest.
impl NetworkKind {
/// Returns true if this is real mainnet bitcoin.
- pub fn is_mainnet(&self) -> bool { *self == NetworkKind::Main }
+ pub fn is_mainnet(&self) -> bool { *self == Self::Main }
}
impl From<Network> for NetworkKind {
@@ -43,8 +43,8 @@ impl From<Network> for NetworkKind {
use Network::*;
match n {
- Bitcoin => NetworkKind::Main,
- Testnet(_) | Signet | Regtest => NetworkKind::Test,
+ Bitcoin => Self::Main,
+ Testnet(_) | Signet | Regtest => Self::Test,
}
}
}
@@ -130,12 +130,12 @@ impl Network {
/// ```
pub fn to_core_arg(self) -> &'static str {
match self {
- Network::Bitcoin => "main",
+ Self::Bitcoin => "main",
// For user-side compatibility, testnet3 is retained as test
- Network::Testnet(TestnetVersion::V3) => "test",
- Network::Testnet(TestnetVersion::V4) => "testnet4",
- Network::Signet => "signet",
- Network::Regtest => "regtest",
+ Self::Testnet(TestnetVersion::V3) => "test",
+ Self::Testnet(TestnetVersion::V4) => "testnet4",
+ Self::Signet => "signet",
+ Self::Regtest => "regtest",
}
}
@@ -185,18 +185,18 @@ impl Network {
///
/// assert_eq!(Ok(Network::Bitcoin), Network::try_from(ChainHash::BITCOIN));
/// ```
- pub fn from_chain_hash(chain_hash: ChainHash) -> Option<Network> {
- Network::try_from(chain_hash).ok()
+ pub fn from_chain_hash(chain_hash: ChainHash) -> Option<Self> {
+ Self::try_from(chain_hash).ok()
}
/// Returns the associated network parameters.
pub const fn params(self) -> &'static Params {
match self {
- Network::Bitcoin => &Params::BITCOIN,
- Network::Testnet(TestnetVersion::V3) => &Params::TESTNET3,
- Network::Testnet(TestnetVersion::V4) => &Params::TESTNET4,
- Network::Signet => &Params::SIGNET,
- Network::Regtest => &Params::REGTEST,
+ Self::Bitcoin => &Params::BITCOIN,
+ Self::Testnet(TestnetVersion::V3) => &Params::TESTNET3,
+ Self::Testnet(TestnetVersion::V4) => &Params::TESTNET4,
+ Self::Signet => &Params::SIGNET,
+ Self::Regtest => &Params::REGTEST,
}
}
@@ -204,11 +204,11 @@ impl Network {
/// This is useful for displaying the network type as a string.
const fn as_display_str(self) -> &'static str {
match self {
- Network::Bitcoin => "bitcoin",
- Network::Testnet(TestnetVersion::V3) => "testnet",
- Network::Testnet(TestnetVersion::V4) => "testnet4",
- Network::Signet => "signet",
- Network::Regtest => "regtest",
+ Self::Bitcoin => "bitcoin",
+ Self::Testnet(TestnetVersion::V3) => "testnet",
+ Self::Testnet(TestnetVersion::V4) => "testnet4",
+ Self::Signet => "signet",
+ Self::Regtest => "regtest",
}
}
}
@@ -279,12 +279,12 @@ impl FromStr for Network {
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
- "bitcoin" => Ok(Network::Bitcoin),
+ "bitcoin" => Ok(Self::Bitcoin),
// For user-side compatibility, testnet3 is retained as testnet
- "testnet" => Ok(Network::Testnet(TestnetVersion::V3)),
- "testnet4" => Ok(Network::Testnet(TestnetVersion::V4)),
- "signet" => Ok(Network::Signet),
- "regtest" => Ok(Network::Regtest),
+ "testnet" => Ok(Self::Testnet(TestnetVersion::V3)),
+ "testnet4" => Ok(Self::Testnet(TestnetVersion::V4)),
+ "signet" => Ok(Self::Signet),
+ "regtest" => Ok(Self::Regtest),
_ => Err(ParseNetworkError(s.to_owned())),
}
}
@@ -318,11 +318,11 @@ impl TryFrom<ChainHash> for Network {
fn try_from(chain_hash: ChainHash) -> Result<Self, Self::Error> {
match chain_hash {
// Note: any new network entries must be matched against here.
- ChainHash::BITCOIN => Ok(Network::Bitcoin),
- ChainHash::TESTNET3 => Ok(Network::Testnet(TestnetVersion::V3)),
- ChainHash::TESTNET4 => Ok(Network::Testnet(TestnetVersion::V4)),
- ChainHash::SIGNET => Ok(Network::Signet),
- ChainHash::REGTEST => Ok(Network::Regtest),
+ ChainHash::BITCOIN => Ok(Self::Bitcoin),
+ ChainHash::TESTNET3 => Ok(Self::Testnet(TestnetVersion::V3)),
+ ChainHash::TESTNET4 => Ok(Self::Testnet(TestnetVersion::V4)),
+ ChainHash::SIGNET => Ok(Self::Signet),
+ ChainHash::REGTEST => Ok(Self::Regtest),
_ => Err(UnknownChainHashError(chain_hash)),
}
}
diff --git a/bitcoin/src/network/params.rs b/bitcoin/src/network/params.rs
index e3aa6558..7fd79a00 100644
--- a/bitcoin/src/network/params.rs
+++ b/bitcoin/src/network/params.rs
@@ -134,10 +134,10 @@ pub static REGTEST: Params = Params::REGTEST;
#[allow(deprecated)] // For `pow_limit`.
impl Params {
/// The mainnet parameters (alias for `Params::MAINNET`).
- pub const BITCOIN: Params = Params::MAINNET;
+ pub const BITCOIN: Self = Self::MAINNET;
/// The mainnet parameters.
- pub const MAINNET: Params = Params {
+ pub const MAINNET: Self = Self {
network: Network::Bitcoin,
bip16_time: 1333238400, // Apr 1 2012
bip34_height: BlockHeight::from_u32(227931), // 000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8
@@ -155,7 +155,7 @@ impl Params {
/// The testnet3 parameters.
#[deprecated(since = "TBD", note = "use `TESTNET3` instead")]
- pub const TESTNET: Params = Params {
+ pub const TESTNET: Self = Self {
network: Network::Testnet(TestnetVersion::V3),
bip16_time: 1333238400, // Apr 1 2012
bip34_height: BlockHeight::from_u32(21111), // 0000000023b3a96d3484e5abb3755c413e7d41500f8e2a5c3f0dd01299cd8ef8
@@ -172,7 +172,7 @@ impl Params {
};
/// The testnet3 parameters.
- pub const TESTNET3: Params = Params {
+ pub const TESTNET3: Self = Self {
network: Network::Testnet(TestnetVersion::V3),
bip16_time: 1333238400, // Apr 1 2012
bip34_height: BlockHeight::from_u32(21111), // 0000000023b3a96d3484e5abb3755c413e7d41500f8e2a5c3f0dd01299cd8ef8
@@ -189,7 +189,7 @@ impl Params {
};
/// The testnet4 parameters.
- pub const TESTNET4: Params = Params {
+ pub const TESTNET4: Self = Self {
network: Network::Testnet(TestnetVersion::V4),
bip16_time: 1333238400, // Apr 1 2012
bip34_height: BlockHeight::from_u32(1),
@@ -206,7 +206,7 @@ impl Params {
};
/// The signet parameters.
- pub const SIGNET: Params = Params {
+ pub const SIGNET: Self = Self {
network: Network::Signet,
bip16_time: 1333238400, // Apr 1 2012
bip34_height: BlockHeight::from_u32(1),
@@ -223,7 +223,7 @@ impl Params {
};
/// The regtest parameters.
- pub const REGTEST: Params = Params {
+ pub const REGTEST: Self = Self {
network: Network::Regtest,
bip16_time: 1333238400, // Apr 1 2012
bip34_height: BlockHeight::from_u32(100000000), // not activated on regtest
@@ -242,11 +242,11 @@ impl Params {
/// Constructs parameters set for the given network.
pub const fn new(network: Network) -> Self {
match network {
- Network::Bitcoin => Params::MAINNET,
- Network::Testnet(TestnetVersion::V3) => Params::TESTNET3,
- Network::Testnet(TestnetVersion::V4) => Params::TESTNET4,
- Network::Signet => Params::SIGNET,
- Network::Regtest => Params::REGTEST,
+ Network::Bitcoin => Self::MAINNET,
+ Network::Testnet(TestnetVersion::V3) => Self::TESTNET3,
+ Network::Testnet(TestnetVersion::V4) => Self::TESTNET4,
+ Network::Signet => Self::SIGNET,
+ Network::Regtest => Self::REGTEST,
}
}
@@ -272,8 +272,8 @@ impl From<&Network> for &'static Params {
fn from(value: &Network) -> Self { value.params() }
}
-impl AsRef<Params> for Params {
- fn as_ref(&self) -> &Params { self }
+impl AsRef<Self> for Params {
+ fn as_ref(&self) -> &Self { self }
}
impl AsRef<Params> for Network {
diff --git a/bitcoin/src/pow.rs b/bitcoin/src/pow.rs
index 0967951f..0abb2098 100644
--- a/bitcoin/src/pow.rs
+++ b/bitcoin/src/pow.rs
@@ -110,13 +110,13 @@ do_impl!(Work);
impl_to_hex_from_lower_hex!(Work, |_| 64);
impl Add for Work {
- type Output = Work;
- fn add(self, rhs: Self) -> Self { Work(self.0 + rhs.0) }
+ type Output = Self;
+ fn add(self, rhs: Self) -> Self { Self(self.0 + rhs.0) }
}
impl Sub for Work {
- type Output = Work;
- fn sub(self, rhs: Self) -> Self { Work(self.0 - rhs.0) }
+ type Output = Self;
+ fn sub(self, rhs: Self) -> Self { Self(self.0 - rhs.0) }
}
/// A 256 bit integer representing target.
@@ -132,7 +132,7 @@ pub struct Target(U256);
impl Target {
/// When parsing nBits, Bitcoin Core converts a negative target threshold into a target of zero.
- pub const ZERO: Target = Target(U256::ZERO);
+ pub const ZERO: Self = Self(U256::ZERO);
/// The maximum possible target.
///
/// This value is used to calculate difficulty, which is defined as how difficult the current
@@ -142,33 +142,33 @@ impl Target {
/// ref: <https://en.bitcoin.it/wiki/Target>
// In Bitcoind this is ~(u256)0 >> 32 stored as a floating-point type so it gets truncated, hence
// the low 208 bits are all zero.
- pub const MAX: Self = Target(U256(0xFFFF_u128 << (208 - 128), 0));
+ pub const MAX: Self = Self(U256(0xFFFF_u128 << (208 - 128), 0));
/// The maximum **attainable** target value on mainnet.
///
/// Not all target values are attainable because consensus code uses the compact format to
/// represent targets (see [`CompactTarget`]).
- pub const MAX_ATTAINABLE_MAINNET: Self = Target(U256(0xFFFF_u128 << (208 - 128), 0));
+ pub const MAX_ATTAINABLE_MAINNET: Self = Self(U256(0xFFFF_u128 << (208 - 128), 0));
/// The proof of work limit on testnet.
// Taken from Bitcoin Core but had lossy conversion to/from compact form.
// https://github.com/bitcoin/bitcoin/blob/8105bce5b384c72cf08b25b7c5343622754e7337/src/kernel/chainparams.cpp#L208
- pub const MAX_ATTAINABLE_TESTNET: Self = Target(U256(0xFFFF_u128 << (208 - 128), 0));
+ pub const MAX_ATTAINABLE_TESTNET: Self = Self(U256(0xFFFF_u128 << (208 - 128), 0));
/// The proof of work limit on regtest.
// Taken from Bitcoin Core but had lossy conversion to/from compact form.
// https://github.com/bitcoin/bitcoin/blob/8105bce5b384c72cf08b25b7c5343622754e7337/src/kernel/chainparams.cpp#L411
- pub const MAX_ATTAINABLE_REGTEST: Self = Target(U256(0x7FFF_FF00u128 << 96, 0));
+ pub const MAX_ATTAINABLE_REGTEST: Self = Self(U256(0x7FFF_FF00u128 << 96, 0));
/// The proof of work limit on signet.
// Taken from Bitcoin Core but had lossy conversion to/from compact form.
// https://github.com/bitcoin/bitcoin/blob/8105bce5b384c72cf08b25b7c5343622754e7337/src/kernel/chainparams.cpp#L348
- pub const MAX_ATTAINABLE_SIGNET: Self = Target(U256(0x0377_ae00 << 80, 0));
+ pub const MAX_ATTAINABLE_SIGNET: Self = Self(U256(0x0377_ae00 << 80, 0));
/// Computes the [`Target`] value from a compact representation.
///
/// ref: <https://developer.bitcoin.org/reference/block_chain.html#target-nbits>
- pub fn from_compact(c: CompactTarget) -> Target {
+ pub fn from_compact(c: CompactTarget) -> Self {
let bits = c.to_consensus();
// This is a floating-point "compact" encoding originally used by
// OpenSSL, which satoshi put into consensus code, so we're stuck
@@ -185,9 +185,9 @@ impl Target {
// The mantissa is signed but may not be negative.
if mant > 0x7F_FFFF {
- Target::ZERO
+ Self::ZERO
} else {
- Target(U256::from(mant) << expt)
+ Self(U256::from(mant) << expt)
}
}
@@ -439,7 +439,7 @@ mod sealed {
}
impl From<CompactTarget> for Target {
- fn from(c: CompactTarget) -> Self { Target::from_compact(c) }
+ fn from(c: CompactTarget) -> Self { Self::from_compact(c) }
}
impl Encodable for CompactTarget {
@@ -452,7 +452,7 @@ impl Encodable for CompactTarget {
impl Decodable for CompactTarget {
#[inline]
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- u32::consensus_decode(r).map(CompactTarget::from_consensus)
+ u32::consensus_decode(r).map(Self::from_consensus)
}
}
@@ -462,23 +462,23 @@ impl Decodable for CompactTarget {
struct U256(u128, u128);
impl U256 {
- const MAX: U256 =
- U256(0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff, 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff);
+ const MAX: Self =
+ Self(0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff, 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff);
- const ZERO: U256 = U256(0, 0);
+ const ZERO: Self = Self(0, 0);
- const ONE: U256 = U256(0, 1);
+ const ONE: Self = Self(0, 1);
/// Constructs a new `U256` from a prefixed hex string.
fn from_hex(s: &str) -> Result<Self, PrefixedHexError> {
let checked = parse_int::hex_remove_prefix(s)?;
- Ok(U256::from_hex_internal(checked)?)
+ Ok(Self::from_hex_internal(checked)?)
}
/// Constructs a new `U256` from an unprefixed hex string.
fn from_unprefixed_hex(s: &str) -> Result<Self, UnprefixedHexError> {
let checked = parse_int::hex_check_unprefixed(s)?;
- Ok(U256::from_hex_internal(checked)?)
+ Ok(Self::from_hex_internal(checked)?)
}
// Caller to ensure `s` does not contain a prefix.
@@ -496,23 +496,23 @@ impl U256 {
(high, low)
};
- Ok(U256(high, low))
+ Ok(Self(high, low))
}
/// Constructs a new `U256` from a big-endian array of `u8`s.
- fn from_be_bytes(a: [u8; 32]) -> U256 {
+ fn from_be_bytes(a: [u8; 32]) -> Self {
let (high, low) = split_in_half(a);
let big = u128::from_be_bytes(high);
let little = u128::from_be_bytes(low);
- U256(big, little)
+ Self(big, little)
}
/// Constructs a new `U256` from a little-endian array of `u8`s.
- fn from_le_bytes(a: [u8; 32]) -> U256 {
+ fn from_le_bytes(a: [u8; 32]) -> Self {
let (high, low) = split_in_half(a);
let little = u128::from_le_bytes(high);
let big = u128::from_le_bytes(low);
- U256(big, little)
+ Self(big, little)
}
/// Converts `U256` to a big-endian array of `u8`s.
@@ -536,19 +536,19 @@ impl U256 {
/// 2**256 / (x + 1) == ~x / (x + 1) + 1
///
/// (Equation shamelessly stolen from bitcoind)
- fn inverse(&self) -> U256 {
+ fn inverse(&self) -> Self {
// We should never have a target/work of zero so this doesn't matter
// that much but we define the inverse of 0 as max.
if self.is_zero() {
- return U256::MAX;
+ return Self::MAX;
}
// We define the inverse of 1 as max.
if self.is_one() {
- return U256::MAX;
+ return Self::MAX;
}
// We define the inverse of max as 1.
if self.is_max() {
- return U256::ONE;
+ return Self::ONE;
}
let ret = !*self / self.wrapping_inc();
@@ -573,7 +573,7 @@ impl U256 {
/// Returns this `U256` as a `u128` saturating to `u128::MAX` if `self` is too big.
// Mutagen gives false positive because >= and > both return u128::MAX
fn saturating_to_u128(&self) -> u128 {
- if *self > U256::from(u128::MAX) {
+ if *self > Self::from(u128::MAX) {
u128::MAX
} else {
self.low_u128()
@@ -595,7 +595,7 @@ impl U256 {
///
/// The multiplication result along with a boolean indicating whether an arithmetic overflow
/// occurred. If an overflow occurred then the wrapped value is returned.
- fn mul_u64(self, rhs: u64) -> (U256, bool) {
+ fn mul_u64(self, rhs: u64) -> (Self, bool) {
let mut carry: u128 = 0;
let mut split_le =
[self.1 as u64, (self.1 >> 64) as u64, self.0 as u64, (self.0 >> 64) as u64];
@@ -635,7 +635,7 @@ impl U256 {
// Early return in case we are dividing by a larger number than us
if my_bits < your_bits {
- return (U256::ZERO, sub_copy);
+ return (Self::ZERO, sub_copy);
}
// Bitwise long division
@@ -653,7 +653,7 @@ impl U256 {
shift -= 1;
}
- (U256(ret[0], ret[1]), sub_copy)
+ (Self(ret[0], ret[1]), sub_copy)
}
/// Calculates `self` + `rhs`
@@ -662,7 +662,7 @@ impl U256 {
/// overflow would occur. If an overflow would have occurred then the wrapped value is returned.
#[must_use = "this returns the result of the operation, without modifying the original"]
fn overflowing_add(self, rhs: Self) -> (Self, bool) {
- let mut ret = U256::ZERO;
+ let mut ret = Self::ZERO;
let mut ret_overflow = false;
let (high, overflow) = self.0.overflowing_add(rhs.0);
@@ -698,7 +698,7 @@ impl U256 {
/// overflow would have occurred then the wrapped value is returned.
#[must_use = "this returns the result of the operation, without modifying the original"]
fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
- let mut ret = U256::ZERO;
+ let mut ret = Self::ZERO;
let mut ret_overflow = false;
for i in 0..3 {
@@ -744,8 +744,8 @@ impl U256 {
/// Returns `self` incremented by 1 wrapping around at the boundary of the type.
#[must_use = "this returns the result of the increment, without modifying the original"]
- fn wrapping_inc(&self) -> U256 {
- let mut ret = U256::ZERO;
+ fn wrapping_inc(&self) -> Self {
+ let mut ret = Self::ZERO;
ret.1 = self.1.wrapping_add(1);
if ret.1 == 0 {
@@ -766,7 +766,7 @@ impl U256 {
fn wrapping_shl(self, rhs: u32) -> Self {
let shift = rhs & 0x000000ff;
- let mut ret = U256::ZERO;
+ let mut ret = Self::ZERO;
let word_shift = shift >= 128;
let bit_shift = shift % 128;
@@ -792,7 +792,7 @@ impl U256 {
fn wrapping_shr(self, rhs: u32) -> Self {
let shift = rhs & 0x000000ff;
- let mut ret = U256::ZERO;
+ let mut ret = Self::ZERO;
let word_shift = shift >= 128;
let bit_shift = shift % 128;
@@ -868,7 +868,7 @@ impl U256 {
}
impl<T: Into<u128>> From<T> for U256 {
- fn from(x: T) -> Self { U256(0, x.into()) }
+ fn from(x: T) -> Self { Self(0, x.into()) }
}
impl Add for U256 {
@@ -911,17 +911,17 @@ impl Rem for U256 {
impl Not for U256 {
type Output = Self;
- fn not(self) -> Self { U256(!self.0, !self.1) }
+ fn not(self) -> Self { Self(!self.0, !self.1) }
}
impl Shl<u32> for U256 {
type Output = Self;
- fn shl(self, shift: u32) -> U256 { self.wrapping_shl(shift) }
+ fn shl(self, shift: u32) -> Self { self.wrapping_shl(shift) }
}
impl Shr<u32> for U256 {
type Output = Self;
- fn shr(self, shift: u32) -> U256 { self.wrapping_shr(shift) }
+ fn shr(self, shift: u32) -> Self { self.wrapping_shr(shift) }
}
impl fmt::Display for U256 {
@@ -1100,7 +1100,7 @@ mod tests {
/// Constructs a new U256 from a big-endian array of u64's
fn from_array(a: [u64; 4]) -> Self {
- let mut ret = U256::ZERO;
+ let mut ret = Self::ZERO;
ret.0 = ((a[0] as u128) << 64) ^ (a[1] as u128);
ret.1 = ((a[2] as u128) << 64) ^ (a[3] as u128);
ret
diff --git a/bitcoin/src/psbt/error.rs b/bitcoin/src/psbt/error.rs
index e97188ba..b84b9322 100644
--- a/bitcoin/src/psbt/error.rs
+++ b/bitcoin/src/psbt/error.rs
@@ -235,21 +235,21 @@ impl std::error::Error for Error {
}
impl From<core::array::TryFromSliceError> for Error {
- fn from(e: core::array::TryFromSliceError) -> Error { Error::InvalidHash(e) }
+ fn from(e: core::array::TryFromSliceError) -> Self { Self::InvalidHash(e) }
}
impl From<encode::Error> for Error {
- fn from(e: encode::Error) -> Self { Error::ConsensusEncoding(e) }
+ fn from(e: encode::Error) -> Self { Self::ConsensusEncoding(e) }
}
impl From<encode::DeserializeError> for Error {
- fn from(e: encode::DeserializeError) -> Self { Error::ConsensusDeserialize(e) }
+ fn from(e: encode::DeserializeError) -> Self { Self::ConsensusDeserialize(e) }
}
impl From<encode::ParseError> for Error {
- fn from(e: encode::ParseError) -> Self { Error::ConsensusParse(e) }
+ fn from(e: encode::ParseError) -> Self { Self::ConsensusParse(e) }
}
impl From<io::Error> for Error {
- fn from(e: io::Error) -> Self { Error::Io(e) }
+ fn from(e: io::Error) -> Self { Self::Io(e) }
}
diff --git a/bitcoin/src/psbt/map/global.rs b/bitcoin/src/psbt/map/global.rs
index 2e277d34..6a24c131 100644
--- a/bitcoin/src/psbt/map/global.rs
+++ b/bitcoin/src/psbt/map/global.rs
@@ -199,7 +199,7 @@ impl Psbt {
}
if let Some(tx) = tx {
- Ok(Psbt {
+ Ok(Self {
unsigned_tx: tx,
version: version.unwrap_or(0),
xpub: xpub_map,
diff --git a/bitcoin/src/psbt/map/input.rs b/bitcoin/src/psbt/map/input.rs
index 4ee4f3fb..e38c87dd 100644
--- a/bitcoin/src/psbt/map/input.rs
+++ b/bitcoin/src/psbt/map/input.rs
@@ -169,7 +169,7 @@ impl FromStr for PsbtSighashType {
// We accept non-standard sighash values.
if let Ok(inner) = u32::from_str_radix(s.trim_start_matches("0x"), 16) {
- return Ok(PsbtSighashType { inner });
+ return Ok(Self { inner });
}
Err(SighashTypeParseError { unrecognized: s.to_owned() })
@@ -177,13 +177,13 @@ impl FromStr for PsbtSighashType {
}
impl From<EcdsaSighashType> for PsbtSighashType {
fn from(ecdsa_hash_ty: EcdsaSighashType) -> Self {
- PsbtSighashType { inner: ecdsa_hash_ty as u32 }
+ Self { inner: ecdsa_hash_ty as u32 }
}
}
impl From<TapSighashType> for PsbtSighashType {
fn from(taproot_hash_ty: TapSighashType) -> Self {
- PsbtSighashType { inner: taproot_hash_ty as u32 }
+ Self { inner: taproot_hash_ty as u32 }
}
}
@@ -202,7 +202,7 @@ impl PsbtSighashType {
/// let _ecdsa_sighash_anyone_can_pay: PsbtSighashType = EcdsaSighashType::AllPlusAnyoneCanPay.into();
/// let _tap_sighash_anyone_can_pay: PsbtSighashType = TapSighashType::AllPlusAnyoneCanPay.into();
/// ```
- pub const ALL: PsbtSighashType = PsbtSighashType { inner: 0x01 };
+ pub const ALL: Self = Self { inner: 0x01 };
/// Returns the [`EcdsaSighashType`] if the [`PsbtSighashType`] can be
/// converted to one.
@@ -224,7 +224,7 @@ impl PsbtSighashType {
///
/// Allows construction of a non-standard or non-valid sighash flag
/// ([`EcdsaSighashType`], [`TapSighashType`] respectively).
- pub fn from_u32(n: u32) -> PsbtSighashType { PsbtSighashType { inner: n } }
+ pub fn from_u32(n: u32) -> Self { Self { inner: n } }
/// Converts [`PsbtSighashType`] to a raw `u32` sighash flag.
///
diff --git a/bitcoin/src/psbt/mod.rs b/bitcoin/src/psbt/mod.rs
index 6e5c87a3..cda173cf 100644
--- a/bitcoin/src/psbt/mod.rs
+++ b/bitcoin/src/psbt/mod.rs
@@ -107,7 +107,7 @@ impl Psbt {
///
/// If transactions is not unsigned.
pub fn from_unsigned_tx(tx: Transaction) -> Result<Self, Error> {
- let psbt = Psbt {
+ let psbt = Self {
inputs: vec![Default::default(); tx.inputs.len()],
outputs: vec![Default::default(); tx.outputs.len()],
@@ -1138,11 +1138,11 @@ impl From<sighash::P2wpkhError> for SignError {
}
impl From<IndexOutOfBoundsError> for SignError {
- fn from(e: IndexOutOfBoundsError) -> Self { SignError::IndexOutOfBounds(e) }
+ fn from(e: IndexOutOfBoundsError) -> Self { Self::IndexOutOfBounds(e) }
}
impl From<sighash::TaprootError> for SignError {
- fn from(e: sighash::TaprootError) -> Self { SignError::TaprootError(e) }
+ fn from(e: sighash::TaprootError) -> Self { Self::TaprootError(e) }
}
/// This error is returned when extracting a [`Transaction`] from a [`Psbt`].
@@ -1319,7 +1319,7 @@ mod display_from_str {
fn from_str(s: &str) -> Result<Self, Self::Err> {
let data = BASE64_STANDARD.decode(s).map_err(PsbtParseError::Base64Encoding)?;
- Psbt::deserialize(&data).map_err(PsbtParseError::PsbtEncoding)
+ Self::deserialize(&data).map_err(PsbtParseError::PsbtEncoding)
}
}
}
diff --git a/bitcoin/src/psbt/raw.rs b/bitcoin/src/psbt/raw.rs
index df8dfa84..33f6a1c5 100644
--- a/bitcoin/src/psbt/raw.rs
+++ b/bitcoin/src/psbt/raw.rs
@@ -91,7 +91,7 @@ impl Key {
key_data.push(Decodable::consensus_decode(r)?);
}
- Ok(Key { type_value, key_data })
+ Ok(Self { type_value, key_data })
}
}
@@ -123,13 +123,13 @@ impl Serialize for Pair {
impl Deserialize for Pair {
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
let mut decoder = bytes;
- Pair::decode(&mut decoder)
+ Self::decode(&mut decoder)
}
}
impl Pair {
pub(crate) fn decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
- Ok(Pair { key: Key::decode(r)?, value: Decodable::consensus_decode(r)? })
+ Ok(Self { key: Key::decode(r)?, value: Decodable::consensus_decode(r)? })
}
}
@@ -159,7 +159,7 @@ where
let mut key = vec![];
let _ = r.read_to_limit(&mut key, 1024)?;
- Ok(ProprietaryKey { prefix, subtype, key })
+ Ok(Self { prefix, subtype, key })
}
}
@@ -194,7 +194,7 @@ where
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for ProprietaryKey {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(ProprietaryKey {
+ Ok(Self {
prefix: Vec::<u8>::arbitrary(u)?,
subtype: u64::arbitrary(u)?,
key: Vec::<u8>::arbitrary(u)?,
@@ -205,6 +205,6 @@ impl<'a> Arbitrary<'a> for ProprietaryKey {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Key {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(Key { type_value: u.arbitrary()?, key_data: Vec::<u8>::arbitrary(u)? })
+ Ok(Self { type_value: u.arbitrary()?, key_data: Vec::<u8>::arbitrary(u)? })
}
}
diff --git a/bitcoin/src/psbt/serialize.rs b/bitcoin/src/psbt/serialize.rs
index 709401f4..64833a48 100644
--- a/bitcoin/src/psbt/serialize.rs
+++ b/bitcoin/src/psbt/serialize.rs
@@ -95,7 +95,7 @@ impl Psbt {
return Err(Error::InvalidSeparator);
}
- let mut global = Psbt::decode_global(r)?;
+ let mut global = Self::decode_global(r)?;
global.unsigned_tx_checks()?;
let inputs: Vec<Input> = {
@@ -170,7 +170,7 @@ impl Serialize for PublicKey {
impl Deserialize for PublicKey {
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
- PublicKey::from_slice(bytes).map_err(Error::InvalidPublicKey)
+ Self::from_slice(bytes).map_err(Error::InvalidPublicKey)
}
}
@@ -180,7 +180,7 @@ impl Serialize for secp256k1::PublicKey {
impl Deserialize for secp256k1::PublicKey {
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
- secp256k1::PublicKey::from_slice(bytes).map_err(Error::InvalidSecp256k1PublicKey)
+ Self::from_slice(bytes).map_err(Error::InvalidSecp256k1PublicKey)
}
}
@@ -225,7 +225,7 @@ impl Deserialize for ecdsa::Signature {
// also has a field sighash_u32 (See BIP-0141). For example, when signing with non-standard
// 0x05, the sighash message would have the last field as 0x05u32 while, the verification
// would check the signature assuming sighash_u32 as `0x01`.
- ecdsa::Signature::from_slice(bytes).map_err(|e| match e {
+ Self::from_slice(bytes).map_err(|e| match e {
ecdsa::DecodeError::EmptySignature => Error::InvalidEcdsaSignature(e),
ecdsa::DecodeError::SighashType(err) => Error::NonStandardSighashType(err.0),
ecdsa::DecodeError::Secp256k1(..) => Error::InvalidEcdsaSignature(e),
@@ -282,18 +282,18 @@ impl Serialize for PsbtSighashType {
impl Deserialize for PsbtSighashType {
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
let raw: u32 = encode::deserialize(bytes)?;
- Ok(PsbtSighashType { inner: raw })
+ Ok(Self { inner: raw })
}
}
// Taproot related ser/deser
impl Serialize for XOnlyPublicKey {
- fn serialize(&self) -> Vec<u8> { XOnlyPublicKey::serialize(self).to_vec() }
+ fn serialize(&self) -> Vec<u8> { Self::serialize(self).to_vec() }
}
impl Deserialize for XOnlyPublicKey {
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
- XOnlyPublicKey::from_byte_array(bytes.try_into().map_err(|_| Error::InvalidXOnlyPublicKey)?)
+ Self::from_byte_array(bytes.try_into().map_err(|_| Error::InvalidXOnlyPublicKey)?)
.map_err(|_| Error::InvalidXOnlyPublicKey)
}
}
@@ -306,7 +306,7 @@ impl Deserialize for taproot::Signature {
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
use taproot::SigFromSliceError::*;
- taproot::Signature::from_slice(bytes).map_err(|e| match e {
+ Self::from_slice(bytes).map_err(|e| match e {
SighashType(err) => Error::NonStandardSighashType(err.0),
InvalidSignatureSize(_) => Error::InvalidTaprootSignature(e),
Secp256k1(..) => Error::InvalidTaprootSignature(e),
@@ -336,7 +336,7 @@ impl Deserialize for (XOnlyPublicKey, TapLeafHash) {
}
impl Serialize for ControlBlock {
- fn serialize(&self) -> Vec<u8> { ControlBlock::serialize(self) }
+ fn serialize(&self) -> Vec<u8> { Self::serialize(self) }
}
impl Deserialize for ControlBlock {
@@ -425,7 +425,7 @@ impl Deserialize for TapTree {
.add_leaf_with_ver(*depth, script, leaf_version)
.map_err(|_| Error::Taproot("Tree not in DFS order"))?;
}
- TapTree::try_from(builder).map_err(Error::TapTree)
+ Self::try_from(builder).map_err(Error::TapTree)
}
}
diff --git a/bitcoin/src/sign_message.rs b/bitcoin/src/sign_message.rs
index 14cb7e32..4468b0e3 100644
--- a/bitcoin/src/sign_message.rs
+++ b/bitcoin/src/sign_message.rs
@@ -76,8 +76,8 @@ mod message_signing {
}
impl From<secp256k1::Error> for MessageSignatureError {
- fn from(e: secp256k1::Error) -> MessageSignatureError {
- MessageSignatureError::InvalidEncoding(e)
+ fn from(e: secp256k1::Error) -> Self {
+ Self::InvalidEncoding(e)
}
}
@@ -96,8 +96,8 @@ mod message_signing {
impl MessageSignature {
/// Constructs a new [MessageSignature].
- pub fn new(signature: RecoverableSignature, compressed: bool) -> MessageSignature {
- MessageSignature { signature, compressed }
+ pub fn new(signature: RecoverableSignature, compressed: bool) -> Self {
+ Self { signature, compressed }
}
/// Serializes to bytes.
@@ -110,13 +110,13 @@ mod message_signing {
}
/// Constructs a new `MessageSignature` from a fixed-length array.
- pub fn from_byte_array(bytes: &[u8; 65]) -> Result<MessageSignature, secp256k1::Error> {
+ pub fn from_byte_array(bytes: &[u8; 65]) -> Result<Self, secp256k1::Error> {
// We just check this here so we can safely subtract further.
if bytes[0] < 27 {
return Err(secp256k1::Error::InvalidRecoveryId);
};
let recid = RecoveryId::try_from(((bytes[0] - 27) & 0x03) as i32)?;
- Ok(MessageSignature {
+ Ok(Self {
signature: RecoverableSignature::from_compact(&bytes[1..], recid)?,
compressed: ((bytes[0] - 27) & 0x04) != 0,
})
@@ -124,7 +124,7 @@ mod message_signing {
/// Constructs a new `MessageSignature` from a byte slice.
#[deprecated(since = "TBD", note = "use `from_byte_array` instead")]
- pub fn from_slice(bytes: &[u8]) -> Result<MessageSignature, MessageSignatureError> {
+ pub fn from_slice(bytes: &[u8]) -> Result<Self, MessageSignatureError> {
let byte_array: [u8; 65] =
bytes.try_into().map_err(|_| MessageSignatureError::InvalidLength)?;
Self::from_byte_array(&byte_array).map_err(MessageSignatureError::from)
@@ -173,7 +173,7 @@ mod message_signing {
impl MessageSignature {
/// Converts a signature from base64 encoding.
- pub fn from_base64(s: &str) -> Result<MessageSignature, MessageSignatureError> {
+ pub fn from_base64(s: &str) -> Result<Self, MessageSignatureError> {
if s.len() != 88 {
return Err(MessageSignatureError::InvalidLength);
}
@@ -181,7 +181,7 @@ mod message_signing {
BASE64_STANDARD
.decode_slice_unchecked(s, &mut byte_array)
.map_err(|_| MessageSignatureError::InvalidBase64)?;
- MessageSignature::from_byte_array(&byte_array).map_err(MessageSignatureError::from)
+ Self::from_byte_array(&byte_array).map_err(MessageSignatureError::from)
}
/// Converts to base64 encoding.
@@ -198,8 +198,8 @@ mod message_signing {
impl core::str::FromStr for MessageSignature {
type Err = MessageSignatureError;
- fn from_str(s: &str) -> Result<MessageSignature, MessageSignatureError> {
- MessageSignature::from_base64(s)
+ fn from_str(s: &str) -> Result<Self, MessageSignatureError> {
+ Self::from_base64(s)
}
}
}
diff --git a/bitcoin/src/taproot/merkle_branch/borrowed.rs b/bitcoin/src/taproot/merkle_branch/borrowed.rs
index 37e6179d..dea3a5dd 100644
--- a/bitcoin/src/taproot/merkle_branch/borrowed.rs
+++ b/bitcoin/src/taproot/merkle_branch/borrowed.rs
@@ -116,12 +116,12 @@ impl Default for &'_ TaprootMerkleBranch {
fn default() -> Self { TaprootMerkleBranch::new() }
}
-impl AsRef<TaprootMerkleBranch> for TaprootMerkleBranch {
- fn as_ref(&self) -> &TaprootMerkleBranch { self }
+impl AsRef<Self> for TaprootMerkleBranch {
+ fn as_ref(&self) -> &Self { self }
}
-impl AsMut<TaprootMerkleBranch> for TaprootMerkleBranch {
- fn as_mut(&mut self) -> &mut TaprootMerkleBranch { self }
+impl AsMut<Self> for TaprootMerkleBranch {
+ fn as_mut(&mut self) -> &mut Self { self }
}
impl AsRef<TaprootMerkleBranch> for TaprootMerkleBranchBuf {
diff --git a/bitcoin/src/taproot/merkle_branch/buf.rs b/bitcoin/src/taproot/merkle_branch/buf.rs
index 11b2850c..4655b604 100644
--- a/bitcoin/src/taproot/merkle_branch/buf.rs
+++ b/bitcoin/src/taproot/merkle_branch/buf.rs
@@ -64,7 +64,7 @@ impl TaprootMerkleBranchBuf {
if collection.as_ref().len() > TAPROOT_CONTROL_MAX_NODE_COUNT {
Err(InvalidMerkleTreeDepthError(collection.as_ref().len()))
} else {
- Ok(TaprootMerkleBranchBuf(collection.into()))
+ Ok(Self(collection.into()))
}
}
diff --git a/bitcoin/src/taproot/mod.rs b/bitcoin/src/taproot/mod.rs
index 11d4b5bc..0ed4a512 100644
--- a/bitcoin/src/taproot/mod.rs
+++ b/bitcoin/src/taproot/mod.rs
@@ -91,7 +91,7 @@ hashes::impl_hex_for_newtype!(TapTweakHash);
hashes::impl_serde_for_newtype!(TapTweakHash);
impl From<TapLeafHash> for TapNodeHash {
- fn from(leaf: TapLeafHash) -> TapNodeHash { TapNodeHash::from_byte_array(leaf.to_byte_array()) }
+ fn from(leaf: TapLeafHash) -> Self { Self::from_byte_array(leaf.to_byte_array()) }
}
impl TapTweakHash {
@@ -100,7 +100,7 @@ impl TapTweakHash {
pub fn from_key_and_merkle_root<K: Into<UntweakedPublicKey>>(
internal_key: K,
merkle_root: Option<TapNodeHash>,
- ) -> TapTweakHash {
+ ) -> Self {
let internal_key = internal_key.into();
let mut eng = sha256t::Hash::<TapTweakTag>::engine();
// always hash the key
@@ -111,7 +111,7 @@ impl TapTweakHash {
// nothing to hash
}
let inner = sha256t::Hash::<TapTweakTag>::from_engine(eng);
- TapTweakHash::from_byte_array(inner.to_byte_array())
+ Self::from_byte_array(inner.to_byte_array())
}
/// Converts a `TapTweakHash` into a `Scalar` ready for use with key tweaking API.
@@ -123,26 +123,26 @@ impl TapTweakHash {
impl TapLeafHash {
/// Computes the leaf hash from components.
- pub fn from_script(script: &TapScript, ver: LeafVersion) -> TapLeafHash {
+ pub fn from_script(script: &TapScript, ver: LeafVersion) -> Self {
let mut eng = sha256t::Hash::<TapLeafTag>::engine();
ver.to_consensus().consensus_encode(&mut eng).expect("engines don't error");
script.consensus_encode(&mut eng).expect("engines don't error");
let inner = sha256t::Hash::<TapLeafTag>::from_engine(eng);
- TapLeafHash::from_byte_array(inner.to_byte_array())
+ Self::from_byte_array(inner.to_byte_array())
}
}
impl From<LeafNode> for TapNodeHash {
- fn from(leaf: LeafNode) -> TapNodeHash { leaf.node_hash() }
+ fn from(leaf: LeafNode) -> Self { leaf.node_hash() }
}
impl From<&LeafNode> for TapNodeHash {
- fn from(leaf: &LeafNode) -> TapNodeHash { leaf.node_hash() }
+ fn from(leaf: &LeafNode) -> Self { leaf.node_hash() }
}
impl TapNodeHash {
/// Computes branch hash given two hashes of the nodes underneath it.
- pub fn from_node_hashes(a: TapNodeHash, b: TapNodeHash) -> TapNodeHash {
+ pub fn from_node_hashes(a: Self, b: Self) -> Self {
combine_node_hashes(a, b).0
}
@@ -151,11 +151,11 @@ impl TapNodeHash {
/// Similar to [`TapLeafHash::from_byte_array`], but explicitly conveys that the
/// hash is constructed from a hidden node. This also has better ergonomics
/// because it does not require the caller to import the Hash trait.
- pub fn assume_hidden(hash: [u8; 32]) -> TapNodeHash { TapNodeHash::from_byte_array(hash) }
+ pub fn assume_hidden(hash: [u8; 32]) -> Self { Self::from_byte_array(hash) }
/// Computes the [`TapNodeHash`] from a script and a leaf version.
- pub fn from_script(script: &TapScript, ver: LeafVersion) -> TapNodeHash {
- TapNodeHash::from(TapLeafHash::from_script(script, ver))
+ pub fn from_script(script: &TapScript, ver: LeafVersion) -> Self {
+ Self::from(TapLeafHash::from_script(script, ver))
}
}
@@ -320,10 +320,10 @@ impl TaprootSpendInfo {
secp: &Secp256k1<C>,
internal_key: K,
node: NodeInfo,
- ) -> TaprootSpendInfo {
+ ) -> Self {
// Create as if it is a key spend path with the given Merkle root
let root_hash = Some(node.hash);
- let mut info = TaprootSpendInfo::new_key_spend(secp, internal_key, root_hash);
+ let mut info = Self::new_key_spend(secp, internal_key, root_hash);
for leaves in node.leaves {
match leaves.leaf {
@@ -372,11 +372,11 @@ impl TaprootSpendInfo {
}
impl From<TaprootSpendInfo> for TapTweakHash {
- fn from(spend_info: TaprootSpendInfo) -> TapTweakHash { spend_info.tap_tweak() }
+ fn from(spend_info: TaprootSpendInfo) -> Self { spend_info.tap_tweak() }
}
impl From<&TaprootSpendInfo> for TapTweakHash {
- fn from(spend_info: &TaprootSpendInfo) -> TapTweakHash { spend_info.tap_tweak() }
+ fn from(spend_info: &TaprootSpendInfo) -> Self { spend_info.tap_tweak() }
}
/// Builder for building Taproot iteratively. Users can specify tap leaf or omitted/hidden branches
@@ -423,13 +423,13 @@ pub struct TaprootBuilder {
impl TaprootBuilder {
/// Constructs a new instance of [`TaprootBuilder`].
- pub fn new() -> Self { TaprootBuilder { branch: vec![] } }
+ pub fn new() -> Self { Self { branch: vec![] } }
/// Constructs a new instance of [`TaprootBuilder`] with a capacity hint for `size` elements.
///
/// The size here should be maximum depth of the tree.
pub fn with_capacity(size: usize) -> Self {
- TaprootBuilder { branch: Vec::with_capacity(size) }
+ Self { branch: Vec::with_capacity(size) }
}
/// Constructs a new [`TaprootSpendInfo`] from a list of scripts (with default script version) and
@@ -480,7 +480,7 @@ impl TaprootBuilder {
// Therefore, the loop will eventually terminate with exactly 1 element
debug_assert_eq!(node_weights.len(), 1);
let node = node_weights.pop().expect("Huffman tree algorithm is broken").1;
- Ok(TaprootBuilder { branch: vec![Some(node)] })
+ Ok(Self { branch: vec![Some(node)] })
}
/// Adds a leaf script at `depth` to the builder with script version `ver`.
@@ -571,7 +571,7 @@ impl TaprootBuilder {
let node = self.try_into_node_info()?;
if node.has_hidden_nodes {
// Reconstruct the builder as it was if it has hidden nodes
- return Err(IncompleteBuilderError::HiddenParts(TaprootBuilder {
+ return Err(IncompleteBuilderError::HiddenParts(Self {
branch: vec![Some(node)],
}));
}
@@ -591,7 +591,7 @@ impl TaprootBuilder {
mut self,
secp: &Secp256k1<C>,
internal_key: K,
- ) -> Result<TaprootSpendInfo, TaprootBuilder> {
+ ) -> Result<TaprootSpendInfo, Self> {
let internal_key = internal_key.into();
match self.branch.len() {
0 => Ok(TaprootSpendInfo::new_key_spend(secp, internal_key, None)),
@@ -815,7 +815,7 @@ impl TryFrom<NodeInfo> for TapTree {
if node_info.has_hidden_nodes {
Err(HiddenNodesError::HiddenParts(node_info))
} else {
- Ok(TapTree(node_info))
+ Ok(Self(node_info))
}
}
}
@@ -905,7 +905,7 @@ impl Ord for NodeInfo {
}
impl PartialOrd for NodeInfo {
- fn partial_cmp(&self, other: &NodeInfo) -> Option<Ordering> { Some(self.cmp(other)) }
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
}
impl PartialEq for NodeInfo {
@@ -1198,7 +1198,7 @@ impl ControlBlock {
/// - [`TaprootError::InvalidTaprootLeafVersion`] if first byte of `sl` is not a valid leaf version.
/// - [`TaprootError::InvalidInternalKey`] if internal key is invalid (first 32 bytes after the parity byte).
/// - [`TaprootError::InvalidMerkleTreeDepth`] if Merkle tree is too deep (more than 128 levels).
- pub fn decode(sl: &[u8]) -> Result<ControlBlock, TaprootError> {
+ pub fn decode(sl: &[u8]) -> Result<Self, TaprootError> {
use alloc::borrow::ToOwned;
let ControlBlock { leaf_version, output_key_parity, internal_key, merkle_branch } =
@@ -1207,13 +1207,13 @@ impl ControlBlock {
let internal_key = internal_key.to_validated().map_err(TaprootError::InvalidInternalKey)?;
let merkle_branch = merkle_branch.to_owned();
- Ok(ControlBlock { leaf_version, output_key_parity, internal_key, merkle_branch })
+ Ok(Self { leaf_version, output_key_parity, internal_key, merkle_branch })
}
/// Constructs a new [`ControlBlock`] from a hex string.
pub fn from_hex(hex: &str) -> Result<Self, TaprootError> {
let vec = Vec::from_hex(hex).map_err(TaprootError::InvalidControlBlockHex)?;
- ControlBlock::decode(vec.as_slice())
+ Self::decode(vec.as_slice())
}
}
@@ -1237,7 +1237,7 @@ impl<B, K> ControlBlock<B, K> {
let leaf_version = LeafVersion::from_consensus(first & TAPROOT_LEAF_MASK)?;
let internal_key = SerializedXOnlyPublicKey::from_bytes_ref(internal_key).into();
let merkle_branch = TaprootMerkleBranch::decode(merkle_branch)?.into();
- Ok(ControlBlock { leaf_version, output_key_parity, internal_key, merkle_branch })
+ Ok(Self { leaf_version, output_key_parity, internal_key, merkle_branch })
}
}
@@ -1324,14 +1324,14 @@ pub struct FutureLeafVersion(u8);
impl FutureLeafVersion {
pub(self) fn from_consensus(
version: u8,
- ) -> Result<FutureLeafVersion, InvalidTaprootLeafVersionError> {
+ ) -> Result<Self, InvalidTaprootLeafVersionError> {
match version {
TAPROOT_LEAF_TAPSCRIPT => unreachable!(
"FutureLeafVersion::from_consensus should never be called for 0xC0 value"
),
TAPROOT_ANNEX_PREFIX => Err(InvalidTaprootLeafVersionError(TAPROOT_ANNEX_PREFIX)),
odd if odd & 0xFE != odd => Err(InvalidTaprootLeafVersionError(odd)),
- even => Ok(FutureLeafVersion(even)),
+ even => Ok(Self(even)),
}
}
@@ -1375,7 +1375,7 @@ impl LeafVersion {
/// - If the `version` is 0x50 ([`TAPROOT_ANNEX_PREFIX`]).
pub fn from_consensus(version: u8) -> Result<Self, InvalidTaprootLeafVersionError> {
match version {
- TAPROOT_LEAF_TAPSCRIPT => Ok(LeafVersion::TapScript),
+ TAPROOT_LEAF_TAPSCRIPT => Ok(Self::TapScript),
TAPROOT_ANNEX_PREFIX => Err(InvalidTaprootLeafVersionError(TAPROOT_ANNEX_PREFIX)),
future => FutureLeafVersion::from_consensus(future).map(LeafVersion::Future),
}
@@ -1384,8 +1384,8 @@ impl LeafVersion {
/// Returns the consensus representation of this [`LeafVersion`].
pub fn to_consensus(self) -> u8 {
match self {
- LeafVersion::TapScript => TAPROOT_LEAF_TAPSCRIPT,
- LeafVersion::Future(version) => version.to_consensus(),
+ Self::TapScript => TAPROOT_LEAF_TAPSCRIPT,
+ Self::Future(version) => version.to_consensus(),
}
}
}
@@ -1393,10 +1393,10 @@ impl LeafVersion {
impl fmt::Display for LeafVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match (self, f.alternate()) {
- (LeafVersion::TapScript, true) => f.write_str("tapscript"),
- (LeafVersion::TapScript, false) => fmt::Display::fmt(&TAPROOT_LEAF_TAPSCRIPT, f),
- (LeafVersion::Future(version), true) => write!(f, "future_script_{:#02x}", version.0),
- (LeafVersion::Future(version), false) => fmt::Display::fmt(version, f),
+ (Self::TapScript, true) => f.write_str("tapscript"),
+ (Self::TapScript, false) => fmt::Display::fmt(&TAPROOT_LEAF_TAPSCRIPT, f),
+ (Self::Future(version), true) => write!(f, "future_script_{:#02x}", version.0),
+ (Self::Future(version), false) => fmt::Display::fmt(version, f),
}
}
}
diff --git a/bitcoin/src/taproot/serialized_signature.rs b/bitcoin/src/taproot/serialized_signature.rs
index 60a71584..839fc5bf 100644
--- a/bitcoin/src/taproot/serialized_signature.rs
+++ b/bitcoin/src/taproot/serialized_signature.rs
@@ -34,7 +34,7 @@ impl fmt::Display for SerializedSignature {
impl PartialEq for SerializedSignature {
#[inline]
- fn eq(&self, other: &SerializedSignature) -> bool { **self == **other }
+ fn eq(&self, other: &Self) -> bool { **self == **other }
}
impl PartialEq<[u8]> for SerializedSignature {
@@ -48,13 +48,13 @@ impl PartialEq<SerializedSignature> for [u8] {
}
impl PartialOrd for SerializedSignature {
- fn partial_cmp(&self, other: &SerializedSignature) -> Option<core::cmp::Ordering> {
+ fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for SerializedSignature {
- fn cmp(&self, other: &SerializedSignature) -> core::cmp::Ordering { (**self).cmp(&**other) }
+ fn cmp(&self, other: &Self) -> core::cmp::Ordering { (**self).cmp(&**other) }
}
impl PartialOrd<[u8]> for SerializedSignature {
@@ -139,7 +139,7 @@ impl SerializedSignature {
#[inline]
pub(crate) fn from_raw_parts(data: [u8; MAX_LEN], len: usize) -> Self {
assert!(len <= MAX_LEN, "attempt to set length to {} but the maximum is {}", len, MAX_LEN);
- SerializedSignature { data, len }
+ Self { data, len }
}
/// Get the len of the used data.
@@ -162,7 +162,7 @@ impl SerializedSignature {
/// Constructs a new SerializedSignature from a Signature.
/// (this serializes it)
#[inline]
- pub fn from_signature(sig: Signature) -> SerializedSignature { sig.serialize() }
+ pub fn from_signature(sig: Signature) -> Self { sig.serialize() }
/// Writes this serialized signature to a `writer`.
#[inline]
@@ -190,7 +190,7 @@ mod into_iter {
impl IntoIter {
#[inline]
pub(crate) fn new(signature: SerializedSignature) -> Self {
- IntoIter {
+ Self {
signature,
// for all unsigned n: 0 <= n
pos: 0,
Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.