Skip to content

Commit

Permalink
Fix build errors and testcasese
Browse files Browse the repository at this point in the history
* Format code with 'cargo +nightly fmt'
  • Loading branch information
Yamaguchi committed Jun 9, 2024
1 parent 40cf091 commit f6c691a
Show file tree
Hide file tree
Showing 19 changed files with 186 additions and 159 deletions.
4 changes: 2 additions & 2 deletions tapyrus/src/address/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -490,11 +490,11 @@ impl<V: NetworkValidation> Address<V> {
Network::Testnet | Network::Signet | Network::Regtest => PUBKEY_ADDRESS_PREFIX_TEST,
};
let p2sh_prefix = match self.network() {
Network::Bitcoin | Network::Paradium => SCRIPT_ADDRESS_PREFIX_MAIN,
Network::Bitcoin | Network::Paradium => SCRIPT_ADDRESS_PREFIX_MAIN,
Network::Testnet | Network::Signet | Network::Regtest => SCRIPT_ADDRESS_PREFIX_TEST,
};
let hrp = match self.network() {
Network::Bitcoin | Network::Paradium => hrp::BC,
Network::Bitcoin | Network::Paradium => hrp::BC,
Network::Testnet | Network::Signet => hrp::TB,
Network::Regtest => hrp::BCRT,
};
Expand Down
7 changes: 2 additions & 5 deletions tapyrus/src/bip152.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ pub struct HeaderAndShortIds {
pub prefilled_txs: Vec<PrefilledTransaction>,
}
impl_consensus_encoding!(HeaderAndShortIds, header, nonce, short_ids, prefilled_txs);

impl HeaderAndShortIds {
/// Create a new [HeaderAndShortIds] from a full block.
///
Expand Down Expand Up @@ -379,10 +379,7 @@ mod test {
use crate::crypto::key::PublicKey;
use crate::crypto::schnorr::Signature;
use crate::hash_types::TxMerkleNode;
use crate::{
Amount, OutPoint, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Txid,
Witness,
};
use crate::{Amount, OutPoint, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Txid, Witness};

fn dummy_tx(nonce: &[u8]) -> Transaction {
Transaction {
Expand Down
55 changes: 36 additions & 19 deletions tapyrus/src/blockdata/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,21 @@
use core::fmt;
use std::str::FromStr;

use hashes::{Hash, HashEngine};
use hashes::hex::FromHex;
use hashes::{Hash, HashEngine};

use super::Weight;
use crate::blockdata::script;
use crate::blockdata::transaction::Transaction;
use crate::crypto::schnorr::Signature;
use crate::consensus::{encode, Decodable, Encodable};
use crate::consensus::encode::serialize_hex;
use crate::consensus::{encode, Decodable, Encodable};
use crate::crypto::key::PublicKey;
use crate::crypto::schnorr::Signature;
pub use crate::hash_types::BlockHash;
use crate::hash_types::{TxMerkleNode, WitnessCommitment, WitnessMerkleNode, Wtxid};
use crate::internal_macros::impl_consensus_encoding;
use crate::{crypto, prelude::*};
use crate::{io, merkle_tree, VarInt};
use crate::crypto::key::PublicKey;
use crate::prelude::*;
use crate::{crypto, io, merkle_tree, VarInt};

/// Bitcoin block header.
///
Expand Down Expand Up @@ -70,7 +70,16 @@ impl Header {
}
}

impl_consensus_encoding!(Header, version, prev_blockhash, merkle_root, im_merkle_root, time, xfield, proof);
impl_consensus_encoding!(
Header,
version,
prev_blockhash,
merkle_root,
im_merkle_root,
time,
xfield,
proof
);

impl fmt::Debug for Header {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Expand Down Expand Up @@ -100,7 +109,7 @@ impl fmt::Debug for Header {
///
/// * [BIP9 - Version bits with timeout and delay](https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki) (current usage)
/// * [BIP34 - Block v2, Height in Coinbase](https://github.com/bitcoin/bips/blob/master/bip-0034.mediawiki)
#[derive(Copy, PartialEq, Eq, Clone, Debug, PartialOrd, Ord, Hash)]
#[derive(PartialEq, Eq, Clone, Debug, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
pub struct Version(i32);
Expand Down Expand Up @@ -212,7 +221,8 @@ impl XField {
impl FromStr for XField {
type Err = encode::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let bytes: Vec<u8> = Vec::from_hex(&s[..]).map_err(|_| encode::Error::ParseFailed("invalid hex string"))?;
let bytes: Vec<u8> =
Vec::from_hex(&s[..]).map_err(|_| encode::Error::ParseFailed("invalid hex string"))?;
XField::consensus_decode(&mut &bytes[..])
}
}
Expand Down Expand Up @@ -280,11 +290,11 @@ impl Decodable for XField {
let pk = PublicKey::from_slice(&bytes)
.map_err(|_| encode::Error::ParseFailed("aggregate public key"))?;
Ok(XField::AggregatePublicKey(pk))
},
}
_ => {
let data: Vec<u8> = Decodable::consensus_decode(&mut d)?;
Ok(XField::Unknown(x_type, data))
},
}
}
}
}
Expand All @@ -298,7 +308,7 @@ impl Encodable for XField {
XField::AggregatePublicKey(pk) => {
let len = pk.to_bytes().consensus_encode(&mut s)?;
Ok(1 + len)
},
}
XField::Unknown(_type, data) => {
let len = data.consensus_encode(&mut s)?;
Ok(1 + len)
Expand Down Expand Up @@ -592,9 +602,10 @@ impl std::error::Error for ValidationError {

#[cfg(test)]
mod tests {
use hex::{test_hex_unwrap as hex, FromHex};
use std::str::FromStr;

use hex::{test_hex_unwrap as hex, FromHex};

use super::*;
use crate::consensus::encode::{deserialize, serialize};

Expand Down Expand Up @@ -627,9 +638,9 @@ mod tests {
let prevhash = hex!("4ddccd549d28f385ab457e98d1b11ce80bfea2c5ab93015ade4973e400000000");
let merkle = hex!("bf4473e53794beae34e64fccc471dace6ae544180816f89591894e0f417a914c");
let pk = PublicKey::from_str(
"032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af",
)
.unwrap();
"032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af",
)
.unwrap();
let decode: Result<Block, _> = deserialize(&some_block);
let bad_decode: Result<Block, _> = deserialize(&cutoff_block);

Expand Down Expand Up @@ -672,7 +683,9 @@ mod tests {

#[test]
fn xfield_aggregate_public_key_test() {
let bytes = Vec::from_hex("0121032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af").unwrap();
let bytes =
Vec::from_hex("0121032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af")
.unwrap();
let decode: XField = deserialize(&bytes).unwrap();
assert_eq!(serialize(&decode), bytes);

Expand All @@ -682,7 +695,9 @@ mod tests {
.unwrap();
assert_eq!(decode, XField::AggregatePublicKey(pk));

let xfield = XField::from_str("0121032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af");
let xfield = XField::from_str(
"0121032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af",
);
assert_eq!(xfield.unwrap(), XField::AggregatePublicKey(pk));
}

Expand All @@ -705,7 +720,9 @@ mod tests {
let decode: XField = deserialize(&xfield).unwrap();
serde_round_trip!(decode);

let xfield = Vec::from_hex("0121032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af").unwrap();
let xfield =
Vec::from_hex("0121032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af")
.unwrap();
let decode: XField = deserialize(&xfield).unwrap();
serde_round_trip!(decode);
}
Expand Down
18 changes: 11 additions & 7 deletions tapyrus/src/blockdata/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ use crate::blockdata::opcodes::all::*;
use crate::blockdata::script;
use crate::blockdata::transaction::{self, OutPoint, Sequence, Transaction, TxIn, TxOut};
use crate::blockdata::witness::Witness;
use crate::crypto::key::PublicKey;
use crate::crypto::schnorr::Signature;
use crate::internal_macros::impl_bytes_newtype;
use crate::network::Network;
use crate::Amount;
use crate::crypto::key::PublicKey;

#[deprecated(since = "0.31.0", note = "Use Weight::MAX_BLOCK instead")]
/// The maximum allowed weight for a block, see BIP 141 (network rule).
Expand Down Expand Up @@ -193,8 +193,8 @@ impl ChainHash {
]);
/// `ChainHash` for paradium.
pub const PARADIUM: Self = Self([
78, 211, 5, 161, 211, 211, 27, 104, 188, 53, 3, 225, 191, 239, 71, 184,13, 111, 154, 223,
143, 185, 20, 76, 57, 231, 161, 17, 182, 77, 190, 120
78, 211, 5, 161, 211, 211, 27, 104, 188, 53, 3, 225, 191, 239, 71, 184, 13, 111, 154, 223,
143, 185, 20, 76, 57, 231, 161, 17, 182, 77, 190, 120,
]);

/// Returns the hash of the `network` genesis block for use as a chain hash.
Expand Down Expand Up @@ -308,11 +308,15 @@ mod test {
let gen = genesis_block(Network::Paradium);
assert_eq!(gen.header.version, block::Version::ONE,);
assert_eq!(gen.header.prev_blockhash, Hash::all_zeros());
assert_eq!(gen.header.merkle_root.to_string(),
"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b");
assert_eq!(
gen.header.merkle_root.to_string(),
"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"
);
assert_eq!(gen.header.time, 1562925929);
assert_eq!(gen.header.block_hash().to_string(),
"78be4db611a1e7394c14b98fdf9a6f0db847efbfe10335bc681bd3d3a105d34e");
assert_eq!(
gen.header.block_hash().to_string(),
"78be4db611a1e7394c14b98fdf9a6f0db847efbfe10335bc681bd3d3a105d34e"
);
}

// The *_chain_hash tests are sanity/regression tests, they verify that the const byte array
Expand Down
19 changes: 14 additions & 5 deletions tapyrus/src/blockdata/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -700,7 +700,7 @@ impl Transaction {
Wtxid::from_engine(enc)
}

/// Computes an "immutable TXID". The double SHA256 taken from a transaction
/// Computes an "immutable TXID". The double SHA256 taken from a transaction
/// after stripping it of all input scripts including their length prefixes.
pub fn malfix_txid(&self) -> sha256d::Hash {
let mut enc = sha256d::Hash::engine();
Expand Down Expand Up @@ -1781,11 +1781,20 @@ mod tests {
111825061110d38b3d5b849dd24323d1f5559d88ac00000000"
);
let tx: Transaction = deserialize(&hex_tx).unwrap();
assert_eq!(format!("{:x}", tx.txid()), "efaf069367948e9e4c99ca04cf885f41cd8dce6b9dddd310c9034f5e65396323");
assert_eq!(format!("{:x}", tx.ntxid()), "c12d06b287c4d95968071733c9e0ab33d93e2c354bc77a56dc6119913732a5dc");
assert_eq!(format!("{:x}", tx.malfix_txid()), "18ab15aaa859c9030f8c449fa074a90eb04b02fc2aca5de0ebbe851e6886efd0");
assert_eq!(
format!("{:x}", tx.txid()),
"efaf069367948e9e4c99ca04cf885f41cd8dce6b9dddd310c9034f5e65396323"
);
assert_eq!(
format!("{:x}", tx.ntxid()),
"c12d06b287c4d95968071733c9e0ab33d93e2c354bc77a56dc6119913732a5dc"
);
assert_eq!(
format!("{:x}", tx.malfix_txid()),
"18ab15aaa859c9030f8c449fa074a90eb04b02fc2aca5de0ebbe851e6886efd0"
);
}

#[test]
#[cfg(feature = "serde")]
fn txn_encode_decode() {
Expand Down
13 changes: 7 additions & 6 deletions tapyrus/src/consensus/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -859,7 +859,10 @@ macro_rules! impl_option {
($type: ty) => {
impl Encodable for Option<$type> {
#[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
fn consensus_encode<W: io::Write + ?Sized>(
&self,
w: &mut W,
) -> Result<usize, io::Error> {
let mut len = 0;
match self {
Some(c) => {
Expand Down Expand Up @@ -1298,11 +1301,9 @@ mod tests {

let some: Option<schnorr::Signature> = Some(Default::default());
let expected = vec![
64,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
];
assert_eq!(expected, serialize(&some));
}
Expand Down
2 changes: 1 addition & 1 deletion tapyrus/src/consensus/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ impl Params {
network: Network::Paradium,
rule_change_activation_threshold: 108, // 75%
miner_confirmation_window: 144,
}
},
}
}
}
14 changes: 3 additions & 11 deletions tapyrus/src/crypto/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ use internals::write_err;
pub use secp256k1::rand;
pub use secp256k1::{self, constants, Keypair, Parity, Secp256k1, Verification, XOnlyPublicKey};

use crate::consensus::{encode, Decodable, Encodable};
use crate::crypto::ecdsa;
use crate::network::Network;
use crate::prelude::*;
use crate::taproot::{TapNodeHash, TapTweakHash};
use crate::{base58, io};
use crate::consensus::{encode, Decodable, Encodable};

/// A Bitcoin ECDSA public key
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
Expand Down Expand Up @@ -445,7 +445,6 @@ impl Encodable for PublicKey {
}
}


#[cfg(feature = "serde")]
#[allow(clippy::collapsible_else_if)] // Aids readability.
impl serde::Serialize for PublicKey {
Expand Down Expand Up @@ -1147,15 +1146,8 @@ mod tests {
.unwrap();
let mut s = Vec::new();
let _ = pk.consensus_encode(&mut s);
let encoded = s
.iter()
.map(|x| format!("{:02x}", x))
.collect::<Vec<String>>()
.join("");
assert_eq!(
"21032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af",
encoded
);
let encoded = s.iter().map(|x| format!("{:02x}", x)).collect::<Vec<String>>().join("");
assert_eq!("21032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af", encoded);

let decoded = PublicKey::consensus_decode(&mut &s[..]).unwrap();
assert_eq!(decoded, pk);
Expand Down
4 changes: 2 additions & 2 deletions tapyrus/src/crypto/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ pub mod ecdsa;
pub mod key;
pub mod sighash;
// Contents re-exported in `tapyrus::taproot`.
pub(crate) mod taproot;
pub mod schnorr;
mod prime;
mod rfc6979;
pub mod schnorr;
pub(crate) mod taproot;

#[cfg(test)]
mod test_helpers;
Loading

0 comments on commit f6c691a

Please sign in to comment.