Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 6 additions & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion packages/rs-dpp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ authors = [
]

[dependencies]
secp256k1 = { workspace = true }
# Reach dash-pkc through rust-dashcore so the crates.io release it requires is the
# only one in the lockfile; a second version would duplicate dash-pkc.
dashcore-crypto = { workspace = true, optional = true }
Expand Down Expand Up @@ -101,6 +100,7 @@ tracing = { version = "0.1.41" }
grovedb-commitment-tree = { workspace = true, optional = true }

[dev-dependencies]
secp256k1 = { workspace = true }
tokio = { workspace = true, features = ["full"] }
pretty_assertions = { version = "1.4.1" }
dpp = { path = ".", default-features = false, features = [
Expand Down
54 changes: 27 additions & 27 deletions packages/rs-dpp/src/identity/identity_public_key/key_type.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
#[cfg(feature = "random-public-keys")]
use crate::util::ecdsa::random_secret_key;
use crate::util::hash::ripemd160_sha256;
use anyhow::bail;
use bincode::{Decode, DecodeUntrusted, Encode};
#[cfg(feature = "cbor")]
use ciborium::value::Value as CborValue;
use dashcore::crypto::ecdsa::EcdsaSecretKey;
#[cfg(feature = "random-public-keys")]
use dashcore::key::rand::rngs::StdRng as EcdsaRng;
#[cfg(feature = "random-public-keys")]
use dashcore::key::rand::SeedableRng;
use dashcore::Network;
use itertools::Itertools;
use lazy_static::lazy_static;
#[cfg(feature = "random-public-keys")]
use secp256k1::rand::rngs::StdRng as EcdsaRng;
#[cfg(feature = "random-public-keys")]
use secp256k1::rand::SeedableRng;

#[cfg(feature = "bls-signatures")]
use crate::bls::{self, BlsError};
Expand Down Expand Up @@ -163,9 +166,9 @@ impl KeyType {
let mut seed = [0u8; 32];
rng.fill(&mut seed);
let mut rng = EcdsaRng::from_seed(seed);
let secret_key = secp256k1::SecretKey::new(&mut rng);
let public_key = secp256k1::PublicKey::from_secret_key(&secret_key);
public_key.serialize().to_vec()
let secret_key = random_secret_key(&mut rng);
let public_key = secret_key.public_key();
public_key.to_compressed().to_vec()
}
KeyType::BLS12_381 => {
let private_key = bls::SecretKey::random(rng);
Expand Down Expand Up @@ -207,11 +210,11 @@ impl KeyType {
) -> Result<Vec<u8>, ProtocolError> {
match self {
KeyType::ECDSA_SECP256K1 => {
let secret_key = secp256k1::SecretKey::from_secret_bytes(*private_key_bytes)
let secret_key = EcdsaSecretKey::from_bytes(private_key_bytes)
.map_err(|e| ProtocolError::Generic(e.to_string()))?;
let public_key = secp256k1::PublicKey::from_secret_key(&secret_key);
let public_key = secret_key.public_key();

Ok(public_key.serialize().to_vec())
Ok(public_key.to_compressed().to_vec())
}
KeyType::BLS12_381 => {
#[cfg(feature = "bls-signatures")]
Expand All @@ -233,11 +236,11 @@ impl KeyType {
));
}
KeyType::ECDSA_HASH160 => {
let secret_key = secp256k1::SecretKey::from_secret_bytes(*private_key_bytes)
let secret_key = EcdsaSecretKey::from_bytes(private_key_bytes)
.map_err(|e| ProtocolError::Generic(e.to_string()))?;
let public_key = secp256k1::PublicKey::from_secret_key(&secret_key);
let public_key = secret_key.public_key();

Ok(ripemd160_sha256(public_key.serialize().as_slice()).to_vec())
Ok(ripemd160_sha256(public_key.to_compressed().as_slice()).to_vec())
}
KeyType::EDDSA_25519_HASH160 => {
#[cfg(feature = "ed25519-dalek")]
Expand All @@ -264,12 +267,9 @@ impl KeyType {
let mut seed = [0u8; 32];
rng.fill(&mut seed);
let mut rng = EcdsaRng::from_seed(seed);
let secret_key = secp256k1::SecretKey::new(&mut rng);
let public_key = secp256k1::PublicKey::from_secret_key(&secret_key);
(
public_key.serialize().to_vec(),
secret_key.to_secret_bytes(),
)
let secret_key = random_secret_key(&mut rng);
let public_key = secret_key.public_key();
(public_key.to_compressed().to_vec(), *secret_key.to_bytes())
}
KeyType::BLS12_381 => {
let private_key = crate::bls::SecretKey::random(rng);
Expand All @@ -280,11 +280,11 @@ impl KeyType {
let mut seed = [0u8; 32];
rng.fill(&mut seed);
let mut rng = EcdsaRng::from_seed(seed);
let secret_key = secp256k1::SecretKey::new(&mut rng);
let public_key = secp256k1::PublicKey::from_secret_key(&secret_key);
let secret_key = random_secret_key(&mut rng);
let public_key = secret_key.public_key();
(
ripemd160_sha256(public_key.serialize().as_slice()).to_vec(),
secret_key.to_secret_bytes(),
ripemd160_sha256(public_key.to_compressed().as_slice()).to_vec(),
*secret_key.to_bytes(),
)
}
KeyType::EDDSA_25519_HASH160 => {
Expand All @@ -299,11 +299,11 @@ impl KeyType {
let mut seed = [0u8; 32];
rng.fill(&mut seed);
let mut rng = EcdsaRng::from_seed(seed);
let secret_key = secp256k1::SecretKey::new(&mut rng);
let public_key = secp256k1::PublicKey::from_secret_key(&secret_key);
let secret_key = random_secret_key(&mut rng);
let public_key = secret_key.public_key();
(
ripemd160_sha256(public_key.serialize().as_slice()).to_vec(),
secret_key.to_secret_bytes(),
ripemd160_sha256(public_key.to_compressed().as_slice()).to_vec(),
*secret_key.to_bytes(),
)
}
}
Expand Down
17 changes: 10 additions & 7 deletions packages/rs-dpp/src/identity/identity_public_key/v0/methods/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ use crate::identity::KeyType;
use crate::util::hash::ripemd160_sha256;
use crate::ProtocolError;
use anyhow::anyhow;
use dashcore::crypto::ecdsa::EcdsaSecretKey;
use dashcore::{Network, PublicKey as ECDSAPublicKey};
use platform_value::{BinaryData, Bytes20};
use secp256k1::SecretKey;
impl IdentityPublicKeyHashMethodsV0 for IdentityPublicKeyV0 {
/// Get the original public key hash
fn public_key_hash(&self) -> Result<[u8; 20], ProtocolError> {
Expand Down Expand Up @@ -81,13 +81,13 @@ pub(in crate::identity::identity_public_key) fn validate_private_key_bytes_for_k
) -> Result<bool, ProtocolError> {
match key_type {
KeyType::ECDSA_SECP256K1 => {
let secret_key = match SecretKey::from_secret_bytes(*private_key_bytes) {
let secret_key = match EcdsaSecretKey::from_bytes(private_key_bytes) {
Ok(secret_key) => secret_key,
Err(_) => return Ok(false),
};
let public_key = secp256k1::PublicKey::from_secret_key(&secret_key);
let public_key = secret_key.public_key();

Ok(public_key.serialize().as_slice() == data.as_slice())
Ok(public_key.to_compressed().as_slice() == data.as_slice())
}
KeyType::BLS12_381 => {
#[cfg(feature = "bls-signatures")]
Expand All @@ -107,13 +107,16 @@ pub(in crate::identity::identity_public_key) fn validate_private_key_bytes_for_k
));
}
KeyType::ECDSA_HASH160 => {
let secret_key = match SecretKey::from_secret_bytes(*private_key_bytes) {
let secret_key = match EcdsaSecretKey::from_bytes(private_key_bytes) {
Ok(secret_key) => secret_key,
Err(_) => return Ok(false),
};
let public_key = secp256k1::PublicKey::from_secret_key(&secret_key);
let public_key = secret_key.public_key();

Ok(ripemd160_sha256(public_key.serialize().as_slice()).as_slice() == data.as_slice())
Ok(
ripemd160_sha256(public_key.to_compressed().as_slice()).as_slice()
== data.as_slice(),
)
}
KeyType::EDDSA_25519_HASH160 => {
#[cfg(feature = "ed25519-dalek")]
Expand Down
2 changes: 0 additions & 2 deletions packages/rs-dpp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
extern crate core;

pub use dashcore;
/// Low-level ECDSA primitives used by Platform signature validation.
pub use secp256k1;

#[cfg(feature = "core_key_wallet")]
pub use key_wallet;
Expand Down
60 changes: 17 additions & 43 deletions packages/rs-dpp/src/state_transition/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ use platform_value::{BinaryData, Identifier};
pub use state_transition_types::*;

use bincode::{Decode, DecodeUntrusted, Encode};
#[cfg(all(feature = "state-transition-signing", feature = "core_key_wallet"))]
use dashcore::crypto::ecdsa::{EcdsaPublicKey, EcdsaRecSignature};
#[cfg(any(
feature = "state-transition-signing",
feature = "state-transition-validation"
Expand Down Expand Up @@ -2331,15 +2333,10 @@ impl StateTransition {
path: &::key_wallet::bip32::DerivationPath,
signer: &S,
) -> Result<(), ProtocolError> {
use dashcore::crypto::ecdsa::EcdsaRecSignature;
use dashcore::signer::double_sha;
use secp256k1::ecdsa::{RecoverableSignature, RecoveryId};
use secp256k1::Message;

let data = self.signable_bytes()?;
// Pre-image transform matches `dashcore::signer::sign`: double-SHA256
// of the signable bytes is the actual ECDSA message digest.
let data_hash = double_sha(&data);
let data_hash = signer::double_sha(&data);
let digest: [u8; 32] = data_hash.as_slice().try_into().map_err(|_| {
ProtocolError::Generic("double_sha did not return 32 bytes".to_string())
})?;
Expand All @@ -2349,32 +2346,20 @@ impl StateTransition {
.await
.map_err(|e| ProtocolError::ExternalSignerError(format!("signer failed: {}", e)))?;

// The signer returns a non-recoverable signature. The legacy path
// stores a 65-byte recoverable compact signature, so we brute-force
// the recovery id (0..3) by reconstructing a `RecoverableSignature`
// and comparing the recovered public key with the one the signer
// returned. Byte parity with `dashcore::signer::sign` requires the
// same deterministic nonce without low-R grinding, as well as low-S
// normalization. Core `sign_recoverable` meets that contract; `sign`
// performs low-R grinding and may produce different bytes.
let compact_64 = signature.to_bytes();
let msg = Message::from_digest(digest);

let mut found: Option<RecoverableSignature> = None;
for id in 0..4i32 {
let recid = match RecoveryId::try_from(id) {
Ok(r) => r,
Err(_) => continue,
};
let candidate = match RecoverableSignature::from_compact(&compact_64, recid) {
Ok(s) => s,
// The signer returns a non-recoverable signature, but the stored form is the 65-byte
// recoverable compact signature, so find the recovery id (0..3) whose recovered key is the
// one the signer returned; the signer's `r || s` bytes are kept as they are. Byte parity
// with `dashcore::signer::sign` needs the same deterministic nonce without low-R grinding,
// plus low-S: Core `sign_recoverable` meets that contract, `sign` grinds low-R.
let mut found = None;
for id in 0..4 {
let candidate = match EcdsaRecSignature::from_parts(signature, id, true) {
Ok(candidate) => candidate,
Err(_) => continue,
};
if let Ok(recovered) = candidate.recover_ecdsa(msg) {
if recovered == public_key.into() {
found = Some(candidate);
break;
}
if EcdsaPublicKey::recover(&digest, &candidate).is_ok_and(|key| key == public_key) {
found = Some(candidate);
break;
}
}
let recoverable = found.ok_or_else(|| {
Expand All @@ -2388,18 +2373,7 @@ impl StateTransition {
)
})?;

// Compressed-pubkey convention matches `dashcore::signer::sign`, which
// always passes `true` regardless of the underlying key encoding. The
// signer's `sign_ecdsa` returns the compressed `secp256k1::PublicKey`,
// so this is consistent.
let (recovery_id, _) = recoverable.serialize_compact();
let compact_65 = EcdsaRecSignature::from_parts(
recoverable.to_standard().into(),
recovery_id.to_u8(),
true,
)
.map_err(|e| ProtocolError::ExternalSignerError(e.to_string()))?
.to_bytes();
let compact_65 = recoverable.to_bytes();

if !self.set_signature(compact_65.to_vec().into()) {
return Err(ProtocolError::InvalidVerificationWrongNumberOfElements {
Expand Down Expand Up @@ -3451,7 +3425,7 @@ mod tests {
.as_slice()
.to_vec();
let s: [u8; 32] = high_s[33..].try_into().expect("a 65-byte signature");
let negated = crate::secp256k1::SecretKey::from_secret_bytes(s)
let negated = secp256k1::SecretKey::from_secret_bytes(s)
.expect("S is a valid scalar")
.negate();
high_s[33..].copy_from_slice(&negated.to_secret_bytes());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::consensus::signature::{
InvalidSignaturePublicKeySecurityLevelError, PublicKeyIsDisabledError,
};
use anyhow::anyhow;
use secp256k1::{PublicKey as RawPublicKey, SecretKey as RawSecretKey};
use dashcore::crypto::ecdsa::{EcdsaError, EcdsaSecretKey};

#[cfg(feature = "state-transition-validation")]
use crate::state_transition::errors::WrongPublicKeyPurposeError;
Expand Down Expand Up @@ -107,11 +107,11 @@ pub trait StateTransitionIdentitySigned: StateTransitionLike {

pub fn get_compressed_public_ec_key(private_key: &[u8]) -> Result<[u8; 33], ProtocolError> {
let sk = <[u8; 32]>::try_from(private_key)
.map_err(|_| secp256k1::Error::InvalidSecretKey)
.and_then(RawSecretKey::from_secret_bytes)
.map_err(|_| EcdsaError::InvalidSecretKey)
.and_then(|bytes| EcdsaSecretKey::from_bytes(&bytes))
.map_err(|e| anyhow!("Invalid ECDSA private key: {}", e))?;

let public_key_compressed = RawPublicKey::from_secret_key(&sk).serialize();
let public_key_compressed = sk.public_key().to_compressed();
Ok(public_key_compressed)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use secp256k1::SecretKey;
use dashcore::crypto::ecdsa::EcdsaSecretKey;
use std::str::FromStr;

use dashcore::bls_sig_utils::BLSSignature;
Expand All @@ -10,7 +10,6 @@ use dashcore::transaction::special_transaction::TransactionPayload;
use dashcore::{
InstantLock, Network, OutPoint, PrivateKey, ScriptBuf, Transaction, TxIn, TxOut, Txid,
};
use secp256k1::rand::rng;

use crate::identity::state_transition::asset_lock_proof::{AssetLockProof, InstantAssetLockProof};

Expand Down Expand Up @@ -55,16 +54,14 @@ pub fn instant_asset_lock_proof_transaction_fixture_with_inputs(
amount: Option<Duffs>,
input_count: u32,
) -> Transaction {
let mut rng = rng();

let private_key_hex = "cSBnVM4xvxarwGQuAfQFwqDg9k5tErHUHzgWsEfD4zdwUasvqRVY";
let private_key = PrivateKey::from_str(private_key_hex).unwrap();
let public_key = private_key.public_key();
let public_key_hash = public_key.pubkey_hash();
//let from_address = Address::p2pkh(&public_key, Network::Testnet);
let secret_key = SecretKey::new(&mut rng);
let secret_key = EcdsaSecretKey::generate();
let one_time_private_key = one_time_private_key.unwrap_or_else(|| {
PrivateKey::from_byte_array(secret_key.as_secret_bytes(), Network::Testnet)
PrivateKey::from_byte_array(&secret_key.to_bytes(), Network::Testnet)
.expect("valid test secret key")
});
let one_time_public_key = one_time_private_key.public_key();
Expand Down
Loading
Loading