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 signature_hash xfield and #36

Merged
merged 5 commits into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
61 changes: 58 additions & 3 deletions src/blockdata/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@ use std::str::FromStr;

use hashes::{Hash, HashEngine};
use hashes::hex::FromHex;
use hash_types::{Wtxid, BlockHash, BlockSigHash, TxMerkleNode, WitnessMerkleNode, WitnessCommitment};
use hash_types::{Wtxid, BlockHash, BlockSigHash, TxMerkleNode, WitnessMerkleNode, WitnessCommitment, XFieldHash};
use consensus::{serialize, encode, Decodable, Encodable};
use consensus::encode::Error;
use consensus::encode::serialize_hex;
use blockdata::constants::WITNESS_SCALE_FACTOR;
use blockdata::transaction::Transaction;
Expand All @@ -40,6 +41,7 @@ use util::key::PublicKey;
use util::signature::Signature;
use VarInt;


/// A block header, which contains all the block's information except
/// the actual transactions
#[derive(PartialEq, Eq, Clone, Debug)]
Expand Down Expand Up @@ -155,6 +157,16 @@ impl XField {
XField::Unknown(_, _) => 0,
}
}

/// Return hash of serialized XField for signing
pub fn signature_hash(&self) ->Result<XFieldHash, Error> {
match self {
XField::None => Ok(XFieldHash::from_str("").unwrap()),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code is intended to return a hash of an empty string, but it actually panics at XFieldHash::from_str("").unwrap(). And test case xfield_signature_hash_test_none also seems to expect that.

If you want to generate an error when None, XFieldHash::from_str("") is not necessary. On the other hand, if you return a hash for empty data, there should be no error.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea was to return an empty string as the hash. But the hash constructor rejects it after checking the length. I never realised it as it doesn't happen in any real test scenario. I'll return error and fix the unit test.

XField::AggregatePublicKey(_) => Ok(XFieldHash::hash(&serialize(self))),
XField::MaxBlockSize(_) => Ok(XFieldHash::hash(&serialize(self))),
XField::Unknown(i, _) => Err(Error::UnknownXField(*i)),
}
}
azuchi marked this conversation as resolved.
Show resolved Hide resolved
}

impl FromStr for XField {
Expand Down Expand Up @@ -388,9 +400,9 @@ mod tests {
use std::str::FromStr;

use blockdata::block::{Block, XField};
use consensus::encode::{deserialize, serialize};
use consensus::encode::{deserialize, serialize, Error};
use util::key::PublicKey;
use hash_types::BlockSigHash;
use hash_types::{BlockSigHash, XFieldHash};
use hashes::hex::FromHex;

#[test]
Expand Down Expand Up @@ -603,4 +615,47 @@ mod tests {
assert!(decode.is_ok());
assert_eq!(decode.unwrap().header.signature_hash(), BlockSigHash::from_hex("3d856f50e0718f72bab6516c1ab020ce3390ebc97490b6d2bad4054dc7a40a93").unwrap());
}

#[test]
fn xfield_signature_hash_test_aggpubkey() {
let xfield = XField::AggregatePublicKey(PublicKey::from_str("02459adb8a8f052be94874aef7d4c3d3ddb71fcdaa869b1d515a92d63cb29c2806").unwrap());
assert_eq!(serialize(&xfield), Vec::<u8>::from_hex("012102459adb8a8f052be94874aef7d4c3d3ddb71fcdaa869b1d515a92d63cb29c2806").unwrap());
assert_eq!(xfield.signature_hash().unwrap(), XFieldHash::from_hex("5eb6038f90ec3b530ebed8789afd4f3f49af83fa4b00f34238c93ce0327ff9ad").unwrap());
}

#[test]
fn xfield_signature_hash_test_maxblocksize() {
let xfield = XField::MaxBlockSize(200000);
assert_eq!(serialize(&xfield), Vec::<u8>::from_hex("02400d0300").unwrap());
assert_eq!(xfield.signature_hash().unwrap(), XFieldHash::from_hex("b2a51fb82acc2125508f323fa9567340c32257997dfd4af4e70788031d5b1915").unwrap());
}

#[test]
fn xfield_signature_hash_test_aggpubkey1() {
let xfield = XField::AggregatePublicKey(PublicKey::from_str("0376c3265e7d81839c1b2312b95697d47cc5b3ab3369a92a5af52ef1c945792f50").unwrap());
assert_eq!(serialize(&xfield), Vec::<u8>::from_hex("01210376c3265e7d81839c1b2312b95697d47cc5b3ab3369a92a5af52ef1c945792f50").unwrap());
assert_eq!(xfield.signature_hash().unwrap(), XFieldHash::from_hex("e70d5478d63e19ab2d9aa059340785b810f82cc288e83752e726a0f9817fcc88").unwrap());
}

#[test]
fn xfield_signature_hash_test_maxblocksize1() {
let xfield = XField::MaxBlockSize(400000);
assert_eq!(serialize(&xfield), Vec::<u8>::from_hex("02801a0600").unwrap());
assert_eq!(xfield.signature_hash().unwrap(), XFieldHash::from_hex("7b5a43d2dae273d564ec0db616efe75a31725707fc3865124e3477684f5faec0").unwrap());
}

#[test]
#[should_panic]
fn xfield_signature_hash_test_none() {
let xfield = XField::None;
xfield.signature_hash();
}

#[test]
fn xfield_signature_hash_test_unknown() {
let xfield = XField::Unknown{0:3, 1:Vec::<u8>::from_hex("012345").unwrap()};
let result = xfield.signature_hash();

assert!(matches!(result, Err(Error::UnknownXField(3))));
}
}
6 changes: 5 additions & 1 deletion src/consensus/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ pub enum Error {
UnrecognizedNetworkCommand(String),
/// Invalid Inventory type
UnknownInventoryType(u32),
/// Invalid Xfield
UnknownXField(u8),
}

impl fmt::Display for Error {
Expand All @@ -110,6 +112,7 @@ impl fmt::Display for Error {
Error::UnrecognizedNetworkCommand(ref nwcmd) => write!(f,
"unrecognized network command: {}", nwcmd),
Error::UnknownInventoryType(ref tp) => write!(f, "Unknown Inventory type: {}", tp),
Error::UnknownXField(ref tp) => write!(f, "Unknown Xfield. Xfield type: {}", tp)
}
}
}
Expand All @@ -129,7 +132,8 @@ impl error::Error for Error {
| Error::ParseFailed(..)
| Error::UnsupportedSegwitFlag(..)
| Error::UnrecognizedNetworkCommand(..)
| Error::UnknownInventoryType(..) => None,
| Error::UnknownInventoryType(..)
| Error::UnknownXField(_)=> None,
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/hash_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ hash_newtype!(Txid, sha256d::Hash, 32, doc="A bitcoin transaction hash/transacti
hash_newtype!(Wtxid, sha256d::Hash, 32, doc="A bitcoin witness transaction ID.");
hash_newtype!(BlockHash, sha256d::Hash, 32, doc="A bitcoin block hash.");
hash_newtype!(BlockSigHash, sha256d::Hash, 32, doc="Hash of the block for sigining.");
hash_newtype!(XFieldHash, sha256d::Hash, 32, doc="Hash of the xfield for signing");
hash_newtype!(SigHash, sha256d::Hash, 32, doc="Hash of the transaction according to the signature algorithm");

hash_newtype!(PubkeyHash, hash160::Hash, 20, doc="A hash of a public key.");
Expand All @@ -61,6 +62,7 @@ impl_hashencode!(Wtxid);
impl_hashencode!(SigHash);
impl_hashencode!(BlockHash);
impl_hashencode!(BlockSigHash);
impl_hashencode!(XFieldHash);
impl_hashencode!(TxMerkleNode);
impl_hashencode!(WitnessMerkleNode);
impl_hashencode!(FilterHash);