Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
cc3f148
build(deps)!: update Platform to v5.1-dev 063589bf
lklimek Oct 24, 2026
82eecdd
refactor: adapt to the rust-dashcore cryptography API
lklimek Oct 24, 2026
e18e7f2
fix: adapt to protocol version 14 upstream types
lklimek Oct 24, 2026
2bb9fed
fix(sdk): follow the network's protocol version
lklimek Oct 24, 2026
173a135
test(platform): guard the protocol 13 tables and transitions
lklimek Oct 24, 2026
6a4e6e7
fix(errors): explain protocol 14 refusals that existing actions can hit
lklimek Oct 24, 2026
d75a159
docs: record the Platform v5.1-dev bump and protocol tracking
lklimek Oct 24, 2026
74695e7
fix(errors): explain moderation, gas sponsorship and distribution lim…
lklimek Oct 24, 2026
53d3fb2
fix(context): keep one system contract set per protocol version
lklimek Oct 25, 2026
e698c7a
fix(platform): confirm only a verified protocol version without the e…
lklimek Oct 25, 2026
4abf4d5
fix(wallet): erase the secp256k1 signing key after use
lklimek Oct 25, 2026
5536745
test(protocol): guard a contested name built with the contest fund at…
lklimek Oct 25, 2026
93cea96
fix(ui): say plainly what the app cannot edit or sign yet
lklimek Oct 25, 2026
16c1c7f
chore: keep AGENTS.md and the marketplace comment as on v1.0-dev
lklimek Oct 25, 2026
407bbaa
fix(test): prove the protocol version the headless refresh learns
lklimek Oct 25, 2026
9c54f99
test: drop the protocol 13 transition encoding tests
lklimek Oct 26, 2026
0555714
refactor(context): read the network's protocol version from the SDK
lklimek Oct 26, 2026
e7a9a45
refactor(context): set the fee multiplier from each proved epoch read
lklimek Oct 26, 2026
318ef38
docs(context): say why proved epochs need no ordering
lklimek Oct 26, 2026
8a18bff
test: drop the protocol 13 client tables snapshot
lklimek Oct 26, 2026
325ec45
fix(context): decode saved contracts at the proof verifier's version
lklimek Oct 26, 2026
7db8d30
fix(wallet): report a failed signed-message envelope instead of panic…
lklimek Oct 26, 2026
749f8bd
style: drop blank lines left by the removed secp256k1 context
lklimek Oct 26, 2026
bd23edc
fix(security): erase every secp256k1 secret key copy after use
lklimek Oct 26, 2026
b898864
Merge branch 'v1.0-dev' (squash of #1114) into fix/erase-secp256k1-ke…
lklimek Oct 26, 2026
ceba7ee
Merge branch 'v1.0-dev' into fix/erase-secp256k1-key-copies
lklimek Oct 26, 2026
ae64628
refactor(security): sign with the self-erasing EcdsaSecretKey
lklimek Oct 26, 2026
7e96b99
Merge branch 'v1.0-dev' into fix/erase-secp256k1-key-copies
lklimek Oct 26, 2026
100ce29
refactor(security): implement Zeroize for the ECDH key and keep DIP-1…
lklimek Oct 26, 2026
49b6796
Merge remote-tracking branch 'origin/fix/erase-secp256k1-key-copies' …
lklimek Oct 26, 2026
72cae69
fix(security): erase the local SecretKey copy when building the ECDH key
lklimek Oct 26, 2026
116b1b1
Merge branch 'v1.0-dev' into fix/erase-secp256k1-key-copies
lklimek Oct 26, 2026
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
69 changes: 62 additions & 7 deletions src/backend_task/dashpay/auto_accept_proof.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::backend_task::error::TaskError;
use crate::model::dashpay_derivation::derive_auto_accept_key;
use crate::model::qualified_identity::QualifiedIdentity;
use dash_sdk::dpp::dashcore::ecdsa::EcdsaSecretKey;
use dash_sdk::dpp::identity::accessors::IdentityGettersV0;
use dash_sdk::dpp::identity::{KeyType, Purpose, SecurityLevel};
use dash_sdk::dpp::secp256k1::Message;
Expand Down Expand Up @@ -209,15 +210,13 @@ pub fn create_auto_accept_proof_bytes_with_key(
hasher.update(&message_data);
let message_hash = hasher.finalize();

// Create secp256k1 message and sign

let message = Message::from_digest(message_hash.into());

let secret_key = dash_sdk::dpp::secp256k1::SecretKey::from_secret_bytes(*(signing_key_bytes))
// Sign the digest. The key erases itself when it drops. The signature is
// low-S with a low R ground as Dash Core grinds it; any ECDSA verifier
// accepts it.
let secret_key = EcdsaSecretKey::from_bytes(signing_key_bytes)
.map_err(|e| format!("Failed to create secret key: {}", e))?;

let signature = dash_sdk::dpp::secp256k1::ecdsa::sign(message, &secret_key);
let sig_bytes = signature.serialize_compact();
let sig_bytes = secret_key.sign(&message_hash.into()).to_bytes();

// Build the proof bytes
let mut proof_bytes = Vec::new();
Expand Down Expand Up @@ -308,3 +307,59 @@ pub async fn verify_auto_accept_proof(
}

// No local persistence required

#[cfg(test)]
mod tests {
use super::*;
use dash_sdk::dpp::secp256k1::{PublicKey, SecretKey, ecdsa};

/// The proof's signature verifies, the way `verify_auto_accept_proof`
/// checks it, against the public key of the key it was signed with. The
/// signature is low-S with a low R ground as Dash Core grinds it; R lands
/// low half the time on its own, so this signs for many accounts.
#[test]
fn proof_signature_verifies_and_has_low_r() {
let key_bytes = [0x2Bu8; 32];
let public_key =
PublicKey::from_secret_key(&SecretKey::from_secret_bytes(key_bytes).expect("valid"));
let sender = Identifier::from([0x01; 32]);
let recipient = Identifier::from([0x02; 32]);
let expires_at = 1_900_000_000u64;

for account_reference in 0..32u32 {
let proof = create_auto_accept_proof_bytes_with_key(
expires_at,
&key_bytes,
&sender,
&recipient,
account_reference,
)
.expect("proof");

assert_eq!(proof[0], 0, "key type");
assert_eq!(
&proof[1..5],
&(expires_at as u32).to_be_bytes(),
"key index"
);
assert_eq!(proof[5], 64, "signature size");
assert_eq!(proof.len(), 6 + 64);

let mut message_data = Vec::new();
message_data.extend_from_slice(&sender.to_buffer());
message_data.extend_from_slice(&recipient.to_buffer());
message_data.extend_from_slice(&account_reference.to_le_bytes());
let digest: [u8; 32] = Sha256::digest(&message_data).into();

let signature = ecdsa::Signature::from_compact(&proof[6..]).expect("compact");
let mut normalized = signature;
normalized.normalize_s();
assert_eq!(normalized, signature, "high S for {account_reference}");
assert!(
ecdsa::verify(&signature, Message::from_digest(digest), &public_key).is_ok(),
"proof does not verify for {account_reference}"
);
assert!(proof[6] < 0x80, "R is not low for {account_reference}");
}
}
}
76 changes: 66 additions & 10 deletions src/backend_task/dashpay/encryption.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,49 @@ use cbc;
use dash_sdk::dpp::identity::IdentityPublicKey;
use dash_sdk::dpp::identity::KeyType;
use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0;
use dash_sdk::dpp::secp256k1::{PublicKey, SecretKey};
use dash_sdk::dpp::secp256k1::{self, PublicKey};
use sha2::{Digest, Sha256};
use zeroize::Zeroizing;
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};

/// A secp256k1 secret key erased when dropped, for the ECDH below.
///
/// `secp256k1::SecretKey` is `Copy` with no `Drop`, so a plain one would
/// outlive the exchange in freed memory. Everywhere else DET uses the
/// self-erasing `EcdsaSecretKey`, which has no ECDH; this keeps the raw
/// secp256k1 ECDH (unchanged output) and overwrites the key once it is done.
///
/// The erase is best effort: it uses secp256k1's volatile `non_secure_erase`,
/// and the compiler may still have moved the bytes elsewhere before. Not
/// `Clone`/`Copy` on purpose, so the only copy is the one that gets erased.
struct EcdhSecretKey(secp256k1::SecretKey);

impl EcdhSecretKey {
/// Build a secret key from a 32-byte scalar, refusing zero and values not
/// below the curve order.
fn from_secret_bytes(scalar: &[u8; 32]) -> Result<Self, secp256k1::Error> {
let mut source = secp256k1::SecretKey::from_secret_bytes(*scalar)?;
let key = Self(source);
// `SecretKey` is `Copy`, so wrapping it copies the scalar; erase the
// local copy as well so only the wrapped one remains.
source.non_secure_erase();
Ok(key)
}
}

impl Zeroize for EcdhSecretKey {
/// Overwrite the held key through secp256k1's volatile erase.
fn zeroize(&mut self) {
self.0.non_secure_erase();
}
}

impl ZeroizeOnDrop for EcdhSecretKey {}

impl Drop for EcdhSecretKey {
fn drop(&mut self) {
self.zeroize();
}
}

/// Generate ECDH shared key according to DashPay DIP-15
/// Uses libsecp256k1_ecdh method: SHA256((y[31]&0x1|0x2) || x)
Expand All @@ -19,10 +59,8 @@ pub fn generate_ecdh_shared_key(
public_key: &IdentityPublicKey,
) -> Result<Zeroizing<[u8; 32]>, String> {
// Parse the private key
let secret_key = SecretKey::from_secret_bytes(
private_key
.try_into()
.map_err(|_| "Invalid private key length".to_string())?,
let secret_key = EcdhSecretKey::from_secret_bytes(
<&[u8; 32]>::try_from(private_key).map_err(|_| "Invalid private key length".to_string())?,
)
.map_err(|e| format!("Invalid private key: {}", e))?;

Expand All @@ -36,10 +74,7 @@ pub fn generate_ecdh_shared_key(
// Perform ECDH to get shared secret. The 64-byte point is secret;
// hold it in `Zeroizing` so it is wiped once the key is hashed out.
let shared_secret = Zeroizing::new(
dash_sdk::dpp::secp256k1::ecdh::shared_secret_point(
&public_key,
&secret_key,
),
secp256k1::ecdh::shared_secret_point(&public_key, &secret_key.0),
);

// Extract x and y coordinates (64 bytes total: 32 + 32)
Expand Down Expand Up @@ -299,6 +334,27 @@ mod tests {
use bip39::rand::{self, RngCore};
use dash_sdk::dpp::secp256k1::{PublicKey, SecretKey};

/// The zeroize that `Drop` runs leaves none of the original key bytes
/// behind. Checked through `zeroize` itself, because reading a value after
/// its drop has run is not allowed.
#[test]
fn ecdh_secret_key_zeroize_overwrites_the_key() {
let scalar = [0x5a; 32];
let mut key = EcdhSecretKey::from_secret_bytes(&scalar).expect("valid scalar");
assert_eq!(key.0.to_secret_bytes(), scalar);

key.zeroize();

assert_ne!(key.0.to_secret_bytes(), scalar);
}

/// The ECDH key refuses the same invalid scalars secp256k1 does.
#[test]
fn ecdh_secret_key_rejects_invalid_scalar() {
assert!(EcdhSecretKey::from_secret_bytes(&[0; 32]).is_err());
assert!(EcdhSecretKey::from_secret_bytes(&[0xff; 32]).is_err());
}

fn generate_test_shared_key() -> [u8; 32] {
let mut shared_key = [0u8; 32];
rand::thread_rng().fill_bytes(&mut shared_key);
Expand Down
6 changes: 3 additions & 3 deletions src/backend_task/wallet/derive_identity_key_for_display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ impl AppContext {
let network = self.network;
let wif = self
.with_identity_secret_key(identity_id, target.clone(), key_id, |secret_key| {
let private_key =
PrivateKey::from_byte_array(secret_key.as_secret_bytes(), network)
.map_err(|_| TaskError::IdentityKeyMalformed)?;
// Identity keys are compressed by convention. The clone erases
// itself when `private_key` drops.
let private_key = PrivateKey::new(secret_key.clone(), network);
Ok(Secret::new(private_key.to_wif()))
})
.await?;
Expand Down
69 changes: 37 additions & 32 deletions src/backend_task/wallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,14 @@ use crate::model::qualified_identity::PrivateKeyTarget;
use crate::model::wallet::WalletSeedHash;
use dash_sdk::dpp::address_funds::PlatformAddress;
use dash_sdk::dpp::balances::credits::Credits;
use dash_sdk::dpp::dashcore::ecdsa::EcdsaRecSignature;
use dash_sdk::dpp::dashcore::ecdsa::{EcdsaRecSignature, EcdsaSecretKey};
use dash_sdk::dpp::dashcore::hashes::Hash;
use dash_sdk::dpp::dashcore::sign_message::{self, signed_msg_hash};
use dash_sdk::dpp::dashcore::{OutPoint, PrivateKey};
use dash_sdk::dpp::identity::core_script::CoreScript;
use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0;
use dash_sdk::dpp::identity::{KeyID, KeyType};
use dash_sdk::dpp::key_wallet::bip32::DerivationPath;
use dash_sdk::dpp::secp256k1::{Message, SecretKey};
use dash_sdk::platform::Identifier;
use std::collections::BTreeMap;
use std::sync::Arc;
Expand All @@ -37,30 +36,30 @@ use std::sync::Arc;
/// a verifier can recover the signer's public key from the signature alone.
/// Shared by the wallet-key and identity-key message-signing tasks.
///
/// The recoverable signature is plain RFC 6979 (no low-R grinding), so the
/// envelope bytes match every earlier build. [`EcdsaSecretKey`] marks every
/// key compressed, so the envelope is rebuilt with the caller's flag.
///
/// # Errors
///
/// [`TaskError::WalletMessageSigningFailed`] if the signature cannot be put
/// in the envelope; the detail is logged.
pub(crate) fn dash_signed_message(
message: &str,
secret_key: &SecretKey,
secret_key: &EcdsaSecretKey,
compressed: bool,
) -> Result<String, TaskError> {
let message_hash = signed_msg_hash(message);
let digest = Message::from_digest(*message_hash.as_byte_array());
let recoverable = dash_sdk::dpp::secp256k1::ecdsa::RecoverableSignature::sign_ecdsa_recoverable(
digest, secret_key,
);
let (recovery_id, _) = recoverable.serialize_compact();
let envelope = EcdsaRecSignature::from_parts(
recoverable.to_standard().into(),
recovery_id.to_u8(),
compressed,
)
.map_err(|detail| {
tracing::warn!(error = %detail, "Sign-message envelope construction failed");
TaskError::WalletMessageSigningFailed
})?;
let recoverable = secret_key.sign_recoverable(message_hash.as_byte_array());
let envelope = recoverable
.signature()
.and_then(|signature| {
EcdsaRecSignature::from_parts(signature, recoverable.recovery_id()?, compressed)
})
.map_err(|detail| {
tracing::warn!(error = %detail, "Sign-message envelope construction failed");
TaskError::WalletMessageSigningFailed
})?;
Ok(sign_message::to_base64(envelope))
}

Expand Down Expand Up @@ -118,10 +117,10 @@ impl AppContext {
}

/// Resolve the vault-backed identity key at `(identity_id, target,
/// key_id)` through the JIT chokepoint and hand its `SecretKey` to `f`.
/// The raw key zeroizes when the closure returns — only `f`'s result
/// crosses back to the caller. Shared by the identity-key sign and
/// display tasks.
/// key_id)` through the JIT chokepoint and lend it to `f` as an
/// [`EcdsaSecretKey`]. The raw key and the parsed key are both wiped when
/// the closure returns — only `f`'s result crosses back to the caller.
/// Shared by the identity-key sign and display tasks.
///
/// The placement is the caller's word, and it addresses the vault label
/// directly, so the bytes are matched against the public key the stored
Expand Down Expand Up @@ -150,7 +149,7 @@ impl AppContext {
identity_id: Identifier,
target: PrivateKeyTarget,
key_id: KeyID,
f: impl FnOnce(SecretKey) -> Result<T, TaskError>,
f: impl FnOnce(&EcdsaSecretKey) -> Result<T, TaskError>,
) -> Result<T, TaskError> {
let identity = self
.get_local_qualified_identity(&identity_id)?
Expand Down Expand Up @@ -200,7 +199,7 @@ impl AppContext {
.ok_or(TaskError::IdentityKeyMissing)?;
// Present-but-malformed key bytes are distinct from a
// genuinely absent key and from a signing/derivation failure.
let secret_key = SecretKey::from_secret_bytes(*key).map_err(|detail| {
let secret_key = EcdsaSecretKey::from_bytes(key).map_err(|detail| {
tracing::warn!(error = %detail, "Identity-key secret construction failed");
TaskError::IdentityKeyMalformed
})?;
Expand All @@ -216,7 +215,7 @@ impl AppContext {
);
return Err(TaskError::IdentityKeyMismatch);
}
f(secret_key)
f(&secret_key)
})
.await
}
Expand Down Expand Up @@ -398,7 +397,7 @@ mod tests {
use dash_sdk::dpp::identity::{Identity, Purpose, SecurityLevel};
use dash_sdk::dpp::key_wallet::bip32::ChildNumber;
use dash_sdk::dpp::platform_value::BinaryData;
use dash_sdk::dpp::secp256k1::PublicKey;
use dash_sdk::dpp::secp256k1::{PublicKey, SecretKey};
use dash_sdk::dpp::version::PlatformVersion;
use dash_sdk::platform::IdentityPublicKey;
use std::sync::atomic::{AtomicBool, Ordering};
Expand Down Expand Up @@ -523,8 +522,10 @@ mod tests {
/// hardcoded recovery header would fail ~50% of the time here. Both the
/// wallet-key and identity-key signers call this one helper.
fn assert_recovers(compressed: bool) {
let secret_key = SecretKey::from_secret_bytes([0x42u8; 32]).expect("valid secret");
let expected_pubkey = PublicKey::from_secret_key(&secret_key);
let secret_key = EcdsaSecretKey::from_bytes(&[0x42u8; 32]).expect("valid secret");
let expected_pubkey = PublicKey::from_secret_key(
&SecretKey::from_secret_bytes([0x42u8; 32]).expect("valid secret"),
);
let message = "Bilby was here";

let base64 = dash_signed_message(message, &secret_key, compressed).expect("signs");
Expand All @@ -539,16 +540,20 @@ mod tests {

/// The envelope keeps the layout the previous encoder produced: a header
/// byte `27 + recovery id` (`+ 4` when compressed), then the compact
/// `r || s` of the same deterministic signature.
/// `r || s` of the same deterministic signature. The reference signs with
/// the raw secp256k1 primitive, so this also proves the signature bytes
/// did not change when signing moved to `EcdsaSecretKey`.
#[test]
fn the_envelope_keeps_its_byte_layout() {
use dash_sdk::dpp::secp256k1::Message;
use dash_sdk::dpp::secp256k1::ecdsa::RecoverableSignature;
let message = "Bilby was here";
let secret_key = SecretKey::from_secret_bytes([0x42u8; 32]).expect("valid secret");
let reference_key = SecretKey::from_secret_bytes([0x42u8; 32]).expect("valid secret");
let secret_key = EcdsaSecretKey::from_bytes(&[0x42u8; 32]).expect("valid secret");
let digest = Message::from_digest(*signed_msg_hash(message).as_byte_array());
let (recovery_id, compact) =
RecoverableSignature::sign_ecdsa_recoverable(digest, &secret_key).serialize_compact();
RecoverableSignature::sign_ecdsa_recoverable(digest, &reference_key)
.serialize_compact();
for compressed in [false, true] {
let mut expected = [0u8; 65];
expected[0] = 27 + recovery_id.to_u8() + if compressed { 4 } else { 0 };
Expand Down Expand Up @@ -642,7 +647,7 @@ mod tests {

let bytes = fixture
.ctx
.with_identity_secret_key(identity_id, MAIN, 7, |key| Ok(key.to_secret_bytes()))
.with_identity_secret_key(identity_id, MAIN, 7, |key| Ok(*key.to_bytes()))
.await
.expect("a key that matches its record must resolve");

Expand Down Expand Up @@ -785,7 +790,7 @@ mod tests {

let bytes = fixture
.ctx
.with_identity_secret_key(identity_id, MAIN, 7, |key| Ok(key.to_secret_bytes()))
.with_identity_secret_key(identity_id, MAIN, 7, |key| Ok(*key.to_bytes()))
.await
.expect("the sibling placement's live bytes must be served");

Expand Down
2 changes: 1 addition & 1 deletion src/backend_task/wallet/sign_message_with_identity_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ impl AppContext {
let signature = self
.with_identity_secret_key(identity_id, target.clone(), key_id, |secret_key| {
// Identity keys are compressed by convention.
dash_signed_message(message.as_str(), &secret_key, true)
dash_signed_message(message.as_str(), secret_key, true)
})
.await?;

Expand Down
Loading
Loading