Skip to content

Commit

Permalink
chore: clean x11 into feature (#40)
Browse files Browse the repository at this point in the history
  • Loading branch information
QuantumExplorer authored Oct 17, 2024
1 parent 648b166 commit 003b1ae
Show file tree
Hide file tree
Showing 13 changed files with 97 additions and 44 deletions.
42 changes: 29 additions & 13 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions dash/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@ edition = "2021"

# Please don't forget to add relevant features to docs.rs below
[features]
default = [ "std", "secp-recovery" ]
default = [ "std", "secp-recovery", "core-block-hash-use-x11" ]
base64 = [ "base64-compat" ]
rand-std = ["secp256k1/rand-std"]
rand-std = ["secp256k1/rand"]
rand = ["secp256k1/rand"]
serde = ["actual-serde", "dashcore_hashes/serde", "secp256k1/serde"]
secp-lowmemory = ["secp256k1/lowmemory"]
secp-recovery = ["secp256k1/recovery"]
signer = ["secp-recovery", "rand"]
core-block-hash-use-x11 = ["dashcore_hashes/x11"]

# At least one of std, no-std must be enabled.
#
Expand All @@ -44,7 +45,7 @@ rustdoc-args = ["--cfg", "docsrs"]
internals = { package = "dashcore-private", version = "0.1.0", path = "../internals" }
bech32 = { version = "0.9.0", default-features = false }
dashcore_hashes = { path = "../hashes", package = "dashcore_hashes", default-features = false }
secp256k1 = { default-features = false, features = ["bitcoin_hashes"], version= "0.27.0" }
secp256k1 = { default-features = false, features = ["hashes"], version= "0.30.0" }
core2 = { version = "0.3.0", optional = true, features = ["alloc"], default-features = false }
rustversion = { version="1.0.9"}
# Do NOT use this as a feature! Use the `serde` feature instead.
Expand All @@ -62,7 +63,7 @@ bincode = { version= "2.0.0-rc.3", optional = true }
serde_json = "1.0.96"
serde_test = "1.0.19"
serde_derive = "1.0.103"
secp256k1 = { features = [ "recovery", "rand-std", "bitcoin_hashes" ], version="0.27.0" }
secp256k1 = { features = [ "recovery", "rand", "hashes" ], version="0.30.0" }
bip39 = "2.0.0"
bincode = "1.3.1"

Expand Down
6 changes: 3 additions & 3 deletions dash/src/bip32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use secp256k1::{self, Secp256k1, XOnlyPublicKey};
use serde;

use crate::base58;
use crate::crypto::key::{self, KeyPair, PrivateKey, PublicKey};
use crate::crypto::key::{self, Keypair, PrivateKey, PublicKey};
use crate::hash_types::XpubIdentifier;
use crate::internal_macros::impl_bytes_newtype;
use crate::io::Write;
Expand Down Expand Up @@ -547,8 +547,8 @@ impl ExtendedPrivKey {

/// Constructs BIP340 keypair for Schnorr signatures and Taproot use matching the internal
/// secret key representation.
pub fn to_keypair<C: secp256k1::Signing>(&self, secp: &Secp256k1<C>) -> KeyPair {
KeyPair::from_seckey_slice(secp, &self.private_key[..])
pub fn to_keypair<C: secp256k1::Signing>(&self, secp: &Secp256k1<C>) -> Keypair {
Keypair::from_seckey_slice(secp, &self.private_key[..])
.expect("BIP32 internal private key representation is broken")
}

Expand Down
6 changes: 5 additions & 1 deletion dash/src/consensus/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@
use core::convert::From;
use core::{fmt, mem, u32};

use hashes::{Hash, hash_x11, hash160, sha256, sha256d};
#[cfg(feature = "core-block-hash-use-x11")]
use hashes::hash_x11;
use hashes::{Hash, hash160, sha256, sha256d};
use internals::write_err;

use crate::bip152::{PrefilledTransaction, ShortId};
Expand Down Expand Up @@ -841,12 +843,14 @@ tuple_encode!(T0, T1, T2, T3, T4, T5);
tuple_encode!(T0, T1, T2, T3, T4, T5, T6);
tuple_encode!(T0, T1, T2, T3, T4, T5, T6, T7);

#[cfg(feature = "core-block-hash-use-x11")]
impl Decodable for hash_x11::Hash {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
Ok(Self::from_byte_array(<<Self as Hash>::Bytes>::consensus_decode(r)?))
}
}

#[cfg(feature = "core-block-hash-use-x11")]
impl Encodable for hash_x11::Hash {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
self.as_byte_array().consensus_encode(w)
Expand Down
14 changes: 7 additions & 7 deletions dash/src/crypto/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use core::str::FromStr;
use hashes::hex::FromHex;
use hashes::{Hash, hash160, hex};
use internals::write_err;
pub use secp256k1::{self, KeyPair, Parity, Secp256k1, Verification, XOnlyPublicKey, constants};
pub use secp256k1::{self, Keypair, Parity, Secp256k1, Verification, XOnlyPublicKey, constants};

use crate::hash_types::{PubkeyHash, WPubkeyHash};
use crate::network::constants::Network;
Expand Down Expand Up @@ -542,7 +542,7 @@ impl fmt::Display for TweakedPublicKey {
}

/// Untweaked BIP-340 key pair
pub type UntweakedKeyPair = KeyPair;
pub type UntweakedKeyPair = Keypair;

/// Tweaked BIP-340 key pair
///
Expand All @@ -563,7 +563,7 @@ pub type UntweakedKeyPair = KeyPair;
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct TweakedKeyPair(KeyPair);
pub struct TweakedKeyPair(Keypair);

/// A trait for tweaking BIP340 key types (x-only public keys and key pairs).
pub trait TapTweak {
Expand Down Expand Up @@ -693,11 +693,11 @@ 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) -> TweakedKeyPair { TweakedKeyPair(pair) }

/// Returns the underlying key pair.
#[inline]
pub fn to_inner(self) -> KeyPair { self.0 }
pub fn to_inner(self) -> Keypair { self.0 }

/// Returns the [`TweakedPublicKey`] and its [`Parity`] for this [`TweakedKeyPair`].
#[inline]
Expand All @@ -712,7 +712,7 @@ impl From<TweakedPublicKey> for XOnlyPublicKey {
fn from(pair: TweakedPublicKey) -> Self { pair.0 }
}

impl From<TweakedKeyPair> for KeyPair {
impl From<TweakedKeyPair> for Keypair {
#[inline]
fn from(pair: TweakedKeyPair) -> Self { pair.0 }
}
Expand Down Expand Up @@ -1048,7 +1048,7 @@ mod tests {
use secp256k1::rand;

let secp = Secp256k1::new();
let kp = KeyPair::new(&secp, &mut rand::thread_rng());
let kp = Keypair::new(&secp, &mut rand::thread_rng());

let _ = PublicKey::new(kp);
let _ = PublicKey::new_uncompressed(kp);
Expand Down
26 changes: 21 additions & 5 deletions dash/src/hash_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,18 +71,36 @@ mod newtypes {
use crate::alloc::string::ToString;

use core::str::FromStr;
use hashes::{sha256, sha256d, hash160, hash_x11, hash_newtype};
use hashes::{sha256, sha256d, hash160, hash_newtype};
use hashes::hex::Error;
use crate::prelude::String;
#[cfg(feature = "core-block-hash-use-x11")]
use hashes::hash_x11;

#[cfg(feature = "core-block-hash-use-x11")]
hash_newtype! {
/// A dash block hash.
pub struct BlockHash(hash_x11::Hash);
/// CycleHash is a cycle hash
pub struct CycleHash(hash_x11::Hash);
}
#[cfg(not(feature = "core-block-hash-use-x11"))]
hash_newtype! {
/// A dash block hash.
pub struct BlockHash(sha256d::Hash);
/// CycleHash is a cycle hash
pub struct CycleHash(sha256d::Hash);
}

hash_newtype! {
/// A dash transaction hash/transaction ID.
pub struct Txid(sha256d::Hash);

/// A dash witness transaction ID.
pub struct Wtxid(sha256d::Hash);
/// A dash block hash.
pub struct BlockHash(hash_x11::Hash);




/// A hash of a public key.
pub struct PubkeyHash(hash160::Hash);
Expand Down Expand Up @@ -127,8 +145,6 @@ mod newtypes {
/// ProTxHash is a pro-tx hash
#[hash_newtype(forward)]
pub struct ProTxHash(sha256d::Hash);
/// CycleHash is a cycle hash
pub struct CycleHash(hash_x11::Hash);
}

impl_hashencode!(Txid);
Expand Down
7 changes: 7 additions & 0 deletions dash/src/network/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,7 @@ mod test {
use std::net::Ipv4Addr;

use hashes::Hash as HashTrait;
#[cfg(feature = "core-block-hash-use-x11")]
use hashes::hash_x11::Hash as X11Hash;
use hashes::sha256d::Hash;

Expand All @@ -535,9 +536,15 @@ mod test {
};

fn hash(slice: [u8; 32]) -> Hash { Hash::from_slice(&slice).unwrap() }

#[cfg(feature = "core-block-hash-use-x11")]
fn hash_x11(slice: [u8; 32]) -> X11Hash { X11Hash::from_slice(&slice).unwrap() }

#[cfg(not(feature = "core-block-hash-use-x11"))]
fn hash_x11(slice: [u8; 32]) -> Hash { Hash::from_slice(&slice).unwrap() }

#[test]
#[cfg(feature = "core-block-hash-use-x11")]
fn full_round_ser_der_raw_network_message_test() {
// TODO: Impl Rand traits here to easily generate random values.
let version_msg: VersionMessage = deserialize(&hex!("721101000100000000000000e6e0845300000000010000000000000000000000000000000000ffff0000000000000100000000000000fd87d87eeb4364f22cf54dca59412db7208d47d920cffce83ee8102f5361746f7368693a302e392e39392f2c9f040001")).unwrap();
Expand Down
16 changes: 11 additions & 5 deletions dash/src/network/message_network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@
//! capabilities.
//!

use hashes::hash_x11;
#[cfg(feature = "core-block-hash-use-x11")]
use hashes::hash_x11 as hashType;
#[cfg(not(feature = "core-block-hash-use-x11"))]
use hashes::sha256d as hashType;

use crate::consensus::{Decodable, Encodable, ReadExt, encode};
use crate::internal_macros::impl_consensus_encoding;
Expand Down Expand Up @@ -149,14 +152,17 @@ pub struct Reject {
/// reason of rejectection
pub reason: Cow<'static, str>,
/// reference to rejected item
pub hash: hash_x11::Hash,
pub hash: hashType::Hash,
}

impl_consensus_encoding!(Reject, message, ccode, reason, hash);

#[cfg(test)]
mod tests {
use hashes::hash_x11;
#[cfg(feature = "core-block-hash-use-x11")]
use hashes::hash_x11 as hashType;
#[cfg(not(feature = "core-block-hash-use-x11"))]
use hashes::sha256d as hashType;

use super::{Reject, RejectReason, VersionMessage};
use crate::consensus::encode::{deserialize, serialize};
Expand Down Expand Up @@ -206,7 +212,7 @@ mod tests {
assert_eq!("txn-mempool-conflict", conflict.reason);
assert_eq!(
"0470f4f2dc4191221b59884bcffaaf00932748ab46356a80413c0b86d354df05"
.parse::<hash_x11::Hash>()
.parse::<hashType::Hash>()
.unwrap(),
conflict.hash
);
Expand All @@ -217,7 +223,7 @@ mod tests {
assert_eq!("non-final", nonfinal.reason);
assert_eq!(
"0b46a539138b5fde4e341b37f2d945c23d41193b30caa7fcbd8bdb836cbe9b25"
.parse::<hash_x11::Hash>()
.parse::<hashType::Hash>()
.unwrap(),
nonfinal.hash
);
Expand Down
4 changes: 2 additions & 2 deletions dash/src/sign_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ mod message_signing {
let (recid, raw) = self.signature.serialize_compact();
let mut serialized = [0u8; 65];
serialized[0] = 27;
serialized[0] += recid.to_i32() as u8;
serialized[0] += <RecoveryId as Into<i32>>::into(recid) as u8;
if self.compressed {
serialized[0] += 4;
}
Expand All @@ -135,7 +135,7 @@ mod message_signing {
secp256k1::Error::InvalidRecoveryId,
));
};
let recid = RecoveryId::from_i32(((bytes[0] - 27) & 0x03) as i32)?;
let recid = RecoveryId::try_from(((bytes[0] - 27) & 0x03) as i32)?;
Ok(MessageSignature {
signature: RecoverableSignature::from_compact(&bytes[1..], recid)?,
compressed: ((bytes[0] - 27) & 0x04) != 0,
Expand Down
4 changes: 2 additions & 2 deletions dash/src/signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,14 +103,14 @@ impl CompactSignature for RecoverableSignature {

RecoverableSignature::from_compact(
&signature.as_ref()[1..],
RecoveryId::from_i32(i).unwrap(),
RecoveryId::try_from(i).unwrap(),
)
.map_err(anyhow::Error::msg)
}

fn to_compact_signature(&self, is_compressed: bool) -> [u8; 65] {
let (recovery_byte, signature) = self.serialize_compact();
let mut val = recovery_byte.to_i32() + 27 + 4;
let mut val = <RecoveryId as Into<i32>>::into(recovery_byte) + 27 + 4;
if !is_compressed {
val -= 4;
}
Expand Down
Loading

0 comments on commit 003b1ae

Please sign in to comment.