Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add xfield to block header #43

Merged
merged 6 commits into from
Jun 10, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
9 changes: 4 additions & 5 deletions tapyrus/src/bip152.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ impl HeaderAndShortIds {
}

Ok(HeaderAndShortIds {
header: block.header,
header: block.header.clone(),
nonce,
// Provide coinbase prefilled.
prefilled_txs: prefilled,
Expand Down Expand Up @@ -376,12 +376,10 @@ mod test {
use crate::blockdata::locktime::absolute;
use crate::blockdata::transaction;
use crate::consensus::encode::{deserialize, serialize};
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 All @@ -405,6 +403,7 @@ mod test {
merkle_root: TxMerkleNode::hash(&[1]),
im_merkle_root: TxMerkleNode::hash(&[1]),
time: 2,
xfield: block::XField::AggregatePublicKey(PublicKey::generator()),
proof: Some(Signature::default()),
},
txdata: vec![dummy_tx(&[2]), dummy_tx(&[3]), dummy_tx(&[4])],
Expand Down
249 changes: 235 additions & 14 deletions tapyrus/src/blockdata/block.rs

Large diffs are not rendered by default.

34 changes: 24 additions & 10 deletions tapyrus/src/blockdata/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,19 @@
//!
use core::default::Default;
use core::str::FromStr;

use hashes::{sha256d, Hash};
use hex_lit::hex;
use internals::impl_array_newtype;

use crate::blockdata::block::{self, Block};
use crate::blockdata::block::{self, Block, XField};
use crate::blockdata::locktime::absolute;
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;
Expand Down Expand Up @@ -91,6 +93,9 @@ pub fn genesis_block(network: Network) -> Block {
let txdata = vec![bitcoin_genesis_tx()];
let hash: sha256d::Hash = txdata[0].txid().into();
let merkle_root = hash.into();
let public_key =
PublicKey::from_str("032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af")
.unwrap();
match network {
Network::Bitcoin => Block {
header: block::Header {
Expand All @@ -99,6 +104,7 @@ pub fn genesis_block(network: Network) -> Block {
merkle_root,
im_merkle_root: txdata[0].ntxid().into(),
time: 1231006505,
xfield: XField::AggregatePublicKey(public_key),
proof: Some(Signature::default()),
},
txdata,
Expand All @@ -110,6 +116,7 @@ pub fn genesis_block(network: Network) -> Block {
merkle_root,
im_merkle_root: txdata[0].ntxid().into(),
time: 1296688602,
xfield: XField::AggregatePublicKey(public_key),
proof: Some(Signature::default()),
},
txdata,
Expand All @@ -121,6 +128,7 @@ pub fn genesis_block(network: Network) -> Block {
merkle_root,
im_merkle_root: txdata[0].ntxid().into(),
time: 1598918400,
xfield: XField::AggregatePublicKey(public_key),
proof: Some(Signature::default()),
},
txdata,
Expand All @@ -132,6 +140,7 @@ pub fn genesis_block(network: Network) -> Block {
merkle_root,
im_merkle_root: txdata[0].ntxid().into(),
time: 1296688602,
xfield: XField::AggregatePublicKey(public_key),
proof: Some(Signature::default()),
},
txdata,
Expand All @@ -145,6 +154,7 @@ pub fn genesis_block(network: Network) -> Block {
merkle_root,
im_merkle_root: txdata[0].ntxid().into(),
time: 1562925929,
xfield: XField::AggregatePublicKey(public_key),
proof: Some(Signature::default()),
},
txdata,
Expand Down Expand Up @@ -183,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 @@ -254,7 +264,7 @@ mod test {
assert_eq!(gen.header.time, 1231006505);
assert_eq!(
gen.header.block_hash().to_string(),
"3c8890361aca183ecb0059ae78e4e57dc514a689588aa7cb97fdc3a6601d08a4"
"1c184bf287b15f641f8b063aab2af4123519d227e8681463b91d675192f6279c"
);
}

Expand All @@ -271,7 +281,7 @@ mod test {
assert_eq!(gen.header.time, 1296688602);
assert_eq!(
gen.header.block_hash().to_string(),
"2f90e0d9843be35112f9830d6e86bf2ef4dd92836979ac4aae1a6f41e0797588"
"13530b95110ac11ae2d22d82acc5ad00a3510bb340c9667309cb811c2883cdc5"
);
}

Expand All @@ -288,7 +298,7 @@ mod test {
assert_eq!(gen.header.time, 1598918400);
assert_eq!(
gen.header.block_hash().to_string(),
"00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6"
"abbaa74c35c0467802e1dfd8a20150ea7c0ac529feb245933702832d112c6b16".to_string()
);
}

Expand All @@ -298,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
17 changes: 11 additions & 6 deletions tapyrus/src/consensus/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ use crate::taproot::TapLeafHash;
pub enum Error {
/// And I/O error.
Io(io::Error),
/// key error
Key(crate::crypto::key::Error),
/// Tried to allocate an oversized vector.
OversizedVectorAllocation {
/// The capacity requested.
Expand Down Expand Up @@ -69,6 +71,7 @@ impl fmt::Display for Error {

match *self {
Io(ref e) => write_err!(f, "IO error"; e),
Error::Key(ref e) => write!(f, "Key error: {}", e),
OversizedVectorAllocation { requested: ref r, max: ref m } =>
write!(f, "allocation of oversized vector: requested {}, maximum {}", r, m),
InvalidChecksum { expected: ref e, actual: ref a } =>
Expand All @@ -88,6 +91,7 @@ impl std::error::Error for Error {

match self {
Io(e) => Some(e),
Error::Key(ref e) => Some(e),
OversizedVectorAllocation { .. }
| InvalidChecksum { .. }
| NonMinimalVarInt
Expand Down Expand Up @@ -855,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 @@ -1294,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,
}
},
}
}
}
1 change: 1 addition & 0 deletions tapyrus/src/consensus/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,7 @@ enum DecodeError<E> {
fn consensus_error_into_serde<E: serde::de::Error>(error: ConsensusError) -> E {
match error {
ConsensusError::Io(error) => panic!("unexpected IO error {:?}", error),
ConsensusError::Key(error) => E::custom(format_args!("unexpected Key error: {}", error)),
ConsensusError::OversizedVectorAllocation { requested, max } => E::custom(format_args!(
"the requested allocation of {} items exceeds maximum of {}",
requested, max
Expand Down
33 changes: 33 additions & 0 deletions tapyrus/src/crypto/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ 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::*;
Expand Down Expand Up @@ -429,6 +430,21 @@ impl<'de> serde::Deserialize<'de> for PrivateKey {
}
}

impl Decodable for PublicKey {
#[inline]
fn consensus_decode<D: io::Read + ?Sized>(d: &mut D) -> Result<Self, encode::Error> {
let s: Vec<u8> = Decodable::consensus_decode(d)?;
PublicKey::from_slice(&s[..]).map_err(encode::Error::Key)
}
}

impl Encodable for PublicKey {
#[inline]
fn consensus_encode<S: io::Write + ?Sized>(&self, mut s: &mut S) -> Result<usize, io::Error> {
self.to_bytes().consensus_encode(&mut s)
}
}

#[cfg(feature = "serde")]
#[allow(clippy::collapsible_else_if)] // Aids readability.
impl serde::Serialize for PublicKey {
Expand Down Expand Up @@ -1119,4 +1135,21 @@ mod tests {
expected.extend(&secp256k1::constants::GENERATOR_Y);
assert_eq!(&expected[..], &g.inner.serialize_uncompressed()[..]);
}

#[test]
fn test_encode() {
use crate::consensus::encode::{Decodable, Encodable};

let pk = PublicKey::from_str(
"032e58afe51f9ed8ad3cc7897f634d881fdbe49a81564629ded8156bebd2ffd1af",
)
.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 decoded = PublicKey::consensus_decode(&mut &s[..]).unwrap();
assert_eq!(decoded, pk);
}
}
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
Loading