From a4b7cf91801c3b37b15b73ce21c9884b69d462b4 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:07:23 +0000 Subject: [PATCH 1/3] feat(key-wallet): verify owner authorization of a pending spend `verify_input_authorization` checks that a transaction input carries a valid P2PKH / `SIGHASH_ALL` owner signature for the funding output it claims. A wallet can use it to decide whether a pending spend may reserve one of its coins before the spend is final. Unsupported funding scripts and signature hash types return a typed `SpendAuthorizationError`, so a caller does not release an existing hold by mistake. Malformed or invalid signatures return `false`. The check covers authorization only: it validates neither amounts nor consensus rules, and it is no evidence of finality. Co-Authored-By: Claude Opus 5.5 --- key-wallet/Cargo.toml | 1 + key-wallet/src/transaction_checking/mod.rs | 3 + .../spend_authorization.rs | 403 ++++++++++++++++++ 3 files changed, 407 insertions(+) create mode 100644 key-wallet/src/transaction_checking/spend_authorization.rs diff --git a/key-wallet/Cargo.toml b/key-wallet/Cargo.toml index 4ce1d3615..c9140f522 100644 --- a/key-wallet/Cargo.toml +++ b/key-wallet/Cargo.toml @@ -72,6 +72,7 @@ hex-conservative = { workspace = true } zeroize = { workspace = true } tracing = { workspace = true } async-trait = { workspace = true } +thiserror = { workspace = true } [dev-dependencies] bincode = { workspace = true, features = ["serde"] } diff --git a/key-wallet/src/transaction_checking/mod.rs b/key-wallet/src/transaction_checking/mod.rs index 0ccb2048d..cd08380da 100644 --- a/key-wallet/src/transaction_checking/mod.rs +++ b/key-wallet/src/transaction_checking/mod.rs @@ -17,3 +17,6 @@ pub use platform_checker::WalletPlatformChecker; pub use transaction_context::{BlockInfo, TransactionContext}; pub use transaction_router::{PlatformAccountConversionError, TransactionRouter, TransactionType}; pub use wallet_checker::WalletTransactionChecker; + +/// Owner authorization for pending Core coin reservations. +pub mod spend_authorization; diff --git a/key-wallet/src/transaction_checking/spend_authorization.rs b/key-wallet/src/transaction_checking/spend_authorization.rs new file mode 100644 index 000000000..cac69b190 --- /dev/null +++ b/key-wallet/src/transaction_checking/spend_authorization.rs @@ -0,0 +1,403 @@ +//! Authorization evidence for reserving a wallet coin before Core finality. + +use dashcore::crypto::ecdsa::{EcdsaPublicKey, EcdsaSignature}; +use dashcore::ecdsa::Signature; +use dashcore::hashes::hash160; +use dashcore::script::Instruction; +use dashcore::sighash::{EcdsaSighashType, SighashCache}; +use dashcore::{Transaction, TxOut}; +use thiserror::Error; + +/// A pending spend whose authorization cannot be decided by the wallet signer contract. +#[derive(Debug, Error, PartialEq, Eq)] +pub enum SpendAuthorizationError { + /// The funding script requires a different authorization verifier. + #[error("pending spend uses an unsupported funding script")] + UnsupportedScript, + /// The signature does not commit to the complete transaction. + #[error("pending spend uses unsupported signature hash type {0:#x}")] + UnsupportedSighash(u8), +} + +/// Checks P2PKH/SIGHASH_ALL authorization to reserve one input's funding coin. +/// +/// The caller must obtain `prevout` from the funding transaction identified by +/// this input, and bind its outpoint to the wallet coin being reserved. A valid +/// signature proves authorization only: other inputs, amounts and consensus +/// rules are not validated, and this result supplies no finality evidence. +/// Unsupported forms return an error so an existing pending hold is not +/// silently released. Malformed or invalid supported authorizations return false. +pub fn verify_input_authorization( + transaction: &Transaction, + input_index: usize, + prevout: &TxOut, +) -> Result { + let Some(input) = transaction.input.get(input_index) else { + return Ok(false); + }; + if transaction + .input + .iter() + .filter(|candidate| candidate.previous_output == input.previous_output) + .count() + != 1 + { + return Ok(false); + } + let Some(public_key_hash) = prevout.script_pubkey.p2pkh_public_key_hash_bytes() else { + return Err(SpendAuthorizationError::UnsupportedScript); + }; + let mut instructions = input.script_sig.instructions(); + let (Some(Ok(Instruction::PushBytes(signature))), Some(Ok(Instruction::PushBytes(public_key)))) = + (instructions.next(), instructions.next()) + else { + return Ok(false); + }; + if instructions.next().is_some() { + return Ok(false); + } + let public_key_bytes = public_key.as_bytes(); + if hash160::Hash::hash(public_key_bytes).as_byte_array().as_slice() != public_key_hash { + return Ok(false); + } + let Ok(public_key) = EcdsaPublicKey::from_bytes(public_key_bytes) else { + return Ok(false); + }; + let Some((&mode, _)) = signature.as_bytes().split_last() else { + return Ok(false); + }; + let Ok(mut signature) = Signature::from_slice(signature.as_bytes()) else { + return Ok(false); + }; + // Both S encodings prove ownership; normalization preserves authorization. + signature.signature.normalize_s(); + let signature = EcdsaSignature::from(signature.signature); + let Ok(hash) = SighashCache::new(transaction).legacy_signature_hash( + input_index, + &prevout.script_pubkey, + u32::from(mode), + ) else { + return Ok(false); + }; + if public_key.verify(&hash.to_byte_array(), signature).is_err() { + return Ok(false); + } + // Other modes can authorize only part of a transaction; SINGLE can even + // produce a constant digest. They cannot authorize this durable reservation. + if u32::from(mode) != EcdsaSighashType::All.to_u32() { + return Err(SpendAuthorizationError::UnsupportedSighash(mode)); + } + Ok(true) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::managed_account::managed_account_trait::ManagedAccountTrait; + use crate::test_utils::TestWalletContext; + use crate::wallet::managed_wallet_info::transaction_builder::TransactionSigner; + use dashcore::blockdata::transaction::special_transaction::{ + asset_lock::AssetLockPayload, TransactionPayload, + }; + use dashcore::crypto::ecdsa::EcdsaSecretKey; + use dashcore::script::{Builder, PushBytesBuf}; + use dashcore::{OutPoint, ScriptBuf, TxIn, Txid, Witness}; + + fn signed(uncompressed: bool) -> (Transaction, TxOut) { + let key = EcdsaSecretKey::from_bytes(&[7; 32]).unwrap(); + let public_key = if uncompressed { + key.public_key().to_uncompressed().to_vec() + } else { + key.public_key().to_compressed().to_vec() + }; + let prevout = TxOut { + value: 100_000, + script_pubkey: ScriptBuf::new_p2pkh(&hash160::Hash::hash(&public_key).into()), + }; + let mut tx = Transaction { + version: 1, + lock_time: 0, + input: vec![TxIn { + previous_output: OutPoint { + txid: Txid::from_byte_array([3; 32]), + vout: 2, + }, + ..Default::default() + }], + output: vec![TxOut { + value: 90_000, + script_pubkey: prevout.script_pubkey.clone(), + }], + special_transaction_payload: None, + }; + sign(&mut tx, &prevout, &key, &public_key, 1); + (tx, prevout) + } + + fn sign( + tx: &mut Transaction, + prevout: &TxOut, + key: &EcdsaSecretKey, + public_key: &[u8], + mode: u8, + ) { + sign_input(tx, 0, prevout, key, public_key, mode); + } + + fn sign_input( + tx: &mut Transaction, + input_index: usize, + prevout: &TxOut, + key: &EcdsaSecretKey, + public_key: &[u8], + mode: u8, + ) { + let hash = SighashCache::new(&*tx) + .legacy_signature_hash(input_index, &prevout.script_pubkey, u32::from(mode)) + .unwrap(); + let mut signature = key.sign(&hash.to_byte_array()).with_der(|der| der.to_vec()); + signature.push(mode); + tx.input[input_index].script_sig = Builder::new() + .push_slice(PushBytesBuf::try_from(signature).unwrap()) + .push_slice(PushBytesBuf::try_from(public_key.to_vec()).unwrap()) + .into_script(); + } + + /// Two inputs funded by different owners, each signed by its own. + fn signed_by_two_owners() -> (Transaction, Vec) { + let keys = [[7; 32], [9; 32]].map(|bytes| EcdsaSecretKey::from_bytes(&bytes).unwrap()); + let public_keys = + keys.iter().map(|key| key.public_key().to_compressed()).collect::>(); + let prevouts = public_keys + .iter() + .map(|public_key| TxOut { + value: 100_000, + script_pubkey: ScriptBuf::new_p2pkh(&hash160::Hash::hash(public_key).into()), + }) + .collect::>(); + let mut tx = Transaction { + version: 1, + lock_time: 0, + input: (0..2) + .map(|vout| TxIn { + previous_output: OutPoint { + txid: Txid::from_byte_array([3; 32]), + vout, + }, + ..Default::default() + }) + .collect(), + output: vec![TxOut { + value: 190_000, + script_pubkey: prevouts[0].script_pubkey.clone(), + }], + special_transaction_payload: None, + }; + for index in 0..2 { + sign_input(&mut tx, index, &prevouts[index], &keys[index], &public_keys[index], 1); + } + (tx, prevouts) + } + + #[test] + fn should_authorize_each_input_only_against_its_own_funding_output() { + let (tx, prevouts) = signed_by_two_owners(); + for index in 0..2 { + assert_eq!(verify_input_authorization(&tx, index, &prevouts[index]), Ok(true)); + assert_eq!(verify_input_authorization(&tx, index, &prevouts[1 - index]), Ok(false)); + } + + // SIGHASH_ALL commits to every input, so changing one input revokes the other's. + let mut resequenced = tx.clone(); + resequenced.input[1].sequence = 7; + assert_eq!(verify_input_authorization(&resequenced, 0, &prevouts[0]), Ok(false)); + + // A signature does not follow its input to another position. + let mut reordered = tx; + reordered.input.swap(0, 1); + for index in 0..2 { + assert_eq!( + verify_input_authorization(&reordered, index, &prevouts[1 - index]), + Ok(false) + ); + } + } + + #[test] + fn should_accept_compressed_and_uncompressed_owner_signatures() { + for uncompressed in [false, true] { + let (tx, prevout) = signed(uncompressed); + assert_eq!(verify_input_authorization(&tx, 0, &prevout), Ok(true)); + } + } + + #[tokio::test] + async fn should_accept_what_the_wallet_signer_produces() { + let (ctx, _) = TestWalletContext::new_random().with_mempool_funding(100_000).await; + let utxo = ctx.first_utxo().clone(); + let path = ctx.bip44_account().address_derivation_path(&utxo.address).unwrap(); + let mut unsigned = Transaction::dummy_empty(); + unsigned.input.push(TxIn { + previous_output: utxo.outpoint, + ..Default::default() + }); + unsigned.output.push(TxOut { + value: 90_000, + script_pubkey: utxo.txout.script_pubkey.clone(), + }); + let signed = ctx + .wallet + .sign_tx(unsigned, vec![utxo.clone()], move |_| Some(path.clone())) + .await + .unwrap(); + assert_eq!(verify_input_authorization(&signed, 0, &utxo.txout), Ok(true)); + } + + #[test] + fn should_reject_unsigned_tampered_and_wrong_funding_claims() { + let (tx, prevout) = signed(false); + let mut unsigned = tx.clone(); + unsigned.input[0].script_sig = ScriptBuf::new(); + assert_eq!(verify_input_authorization(&unsigned, 0, &prevout), Ok(false)); + let mut changed = tx.clone(); + changed.output[0].value -= 1; + assert_eq!(verify_input_authorization(&changed, 0, &prevout), Ok(false)); + changed = tx.clone(); + changed.input[0].previous_output.vout += 1; + assert_eq!(verify_input_authorization(&changed, 0, &prevout), Ok(false)); + let (_, different_encoding) = signed(true); + assert_eq!(verify_input_authorization(&tx, 0, &different_encoding), Ok(false)); + assert_eq!(verify_input_authorization(&tx, 1, &prevout), Ok(false)); + changed = tx.clone(); + changed.input.push(tx.input[0].clone()); + assert_eq!(verify_input_authorization(&changed, 0, &prevout), Ok(false)); + } + + #[test] + fn should_reject_extra_script_instructions_and_malformed_signature() { + let (mut tx, prevout) = signed(false); + let mut bytes = tx.input[0].script_sig.as_bytes().to_vec(); + bytes.push(0); + tx.input[0].script_sig = ScriptBuf::from_bytes(bytes); + assert_eq!(verify_input_authorization(&tx, 0, &prevout), Ok(false)); + tx.input[0].script_sig = ScriptBuf::from_bytes(vec![1, 1, 1, 2]); + assert_eq!(verify_input_authorization(&tx, 0, &prevout), Ok(false)); + } + + #[test] + fn should_bind_asset_lock_payload_to_authorization() { + let (mut tx, prevout) = signed(false); + let key = EcdsaSecretKey::from_bytes(&[7; 32]).unwrap(); + tx.version = 3; + tx.special_transaction_payload = + Some(TransactionPayload::AssetLockPayloadType(AssetLockPayload::new(vec![ + prevout.clone() + ]))); + sign(&mut tx, &prevout, &key, &key.public_key().to_compressed(), 1); + assert_eq!(verify_input_authorization(&tx, 0, &prevout), Ok(true)); + if let Some(TransactionPayload::AssetLockPayloadType(payload)) = + &mut tx.special_transaction_payload + { + payload.credit_outputs[0].value -= 1; + } + assert_eq!(verify_input_authorization(&tx, 0, &prevout), Ok(false)); + } + + #[test] + fn should_not_turn_an_unauthenticated_hash_flag_into_an_unsupported_error() { + let (mut tx, prevout) = signed(false); + let original = tx.input[0].script_sig.as_bytes().to_vec(); + for mode in [0, 0x82, 0xff] { + let mut bytes = original.clone(); + let signature_len = usize::from(bytes[0]); + bytes[signature_len] = mode; + tx.input[0].script_sig = ScriptBuf::from_bytes(bytes); + assert_eq!(verify_input_authorization(&tx, 0, &prevout), Ok(false)); + } + } + + #[test] + fn should_preserve_authorization_with_uncommitted_witness() { + let (mut tx, prevout) = signed(false); + let original_txid = tx.txid(); + tx.input[0].witness = Witness::from_slice(&[b"peer-attached witness"]); + assert_eq!(tx.txid(), original_txid); + assert_eq!(verify_input_authorization(&tx, 0, &prevout), Ok(true)); + } + + #[test] + fn should_accept_high_s_owner_authorization() { + let (mut tx, prevout) = signed(false); + let key = EcdsaSecretKey::from_bytes(&[7; 32]).unwrap(); + let hash = + SighashCache::new(&tx).legacy_signature_hash(0, &prevout.script_pubkey, 1).unwrap(); + let low = key.sign(&hash.to_byte_array()); + let mut compact = low.to_bytes(); + // secp256k1 group order: (r, n-s) is the high-S form of (r, s). + let order = hex_conservative::decode_to_vec( + "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", + ) + .unwrap(); + let mut borrow = false; + for i in (0..32).rev() { + let (difference, first_borrow) = order[i].overflowing_sub(compact[32 + i]); + let (difference, second_borrow) = difference.overflowing_sub(u8::from(borrow)); + compact[32 + i] = difference; + borrow = first_borrow || second_borrow; + } + let high = EcdsaSignature::from_bytes(&compact).unwrap(); + assert!(!high.is_low_s()); + let mut signature = high.with_der(|der| der.to_vec()); + signature.push(1); + tx.input[0].script_sig = Builder::new() + .push_slice(PushBytesBuf::try_from(signature).unwrap()) + .push_slice(key.public_key().to_compressed()) + .into_script(); + assert_eq!(verify_input_authorization(&tx, 0, &prevout), Ok(true)); + tx.output[0].value -= 1; + assert_eq!(verify_input_authorization(&tx, 0, &prevout), Ok(false)); + } + + #[test] + fn should_never_authorize_the_sighash_single_bug_digest() { + let (mut tx, prevout) = signed(false); + let key = EcdsaSecretKey::from_bytes(&[7; 32]).unwrap(); + // Input 0 has no matching output, so SINGLE signs the constant digest 1, + // which commits to nothing in the transaction. + tx.output.clear(); + for mode in [3, 0x83] { + sign(&mut tx, &prevout, &key, &key.public_key().to_compressed(), mode); + assert_eq!( + verify_input_authorization(&tx, 0, &prevout), + Err(SpendAuthorizationError::UnsupportedSighash(mode)) + ); + let mut replayed = tx.clone(); + replayed.lock_time += 1; + assert_eq!( + verify_input_authorization(&replayed, 0, &prevout), + Err(SpendAuthorizationError::UnsupportedSighash(mode)) + ); + } + } + + #[test] + fn should_preserve_unsupported_authorization_as_an_error() { + let (mut tx, prevout) = signed(false); + let key = EcdsaSecretKey::from_bytes(&[7; 32]).unwrap(); + for mode in [0, 2, 3, 4, 0x81, 0x82, 0x83, 0xff] { + sign(&mut tx, &prevout, &key, &key.public_key().to_compressed(), mode); + assert_eq!( + verify_input_authorization(&tx, 0, &prevout), + Err(SpendAuthorizationError::UnsupportedSighash(mode)) + ); + } + let unknown = TxOut { + value: prevout.value, + script_pubkey: ScriptBuf::new(), + }; + assert_eq!( + verify_input_authorization(&tx, 0, &unknown), + Err(SpendAuthorizationError::UnsupportedScript) + ); + } +} From 10bbbb9cc7fe94fd8bdb5ac32aefe48175c5efec Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:38:41 +0000 Subject: [PATCH 2/3] test(key-wallet): sign a transaction that repeats the funding outpoint The repeated-outpoint case appended the duplicate input after signing, so the signature check alone rejected it and no test failed without the uniqueness guard. The owner now signs the transaction with the outpoint already listed twice, so only the guard rejects it. Co-Authored-By: Claude Opus 5.5 --- key-wallet/src/transaction_checking/spend_authorization.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/key-wallet/src/transaction_checking/spend_authorization.rs b/key-wallet/src/transaction_checking/spend_authorization.rs index cac69b190..b1eb430be 100644 --- a/key-wallet/src/transaction_checking/spend_authorization.rs +++ b/key-wallet/src/transaction_checking/spend_authorization.rs @@ -268,8 +268,11 @@ mod tests { let (_, different_encoding) = signed(true); assert_eq!(verify_input_authorization(&tx, 0, &different_encoding), Ok(false)); assert_eq!(verify_input_authorization(&tx, 1, &prevout), Ok(false)); + // The owner signs a transaction that lists the outpoint twice. + let key = EcdsaSecretKey::from_bytes(&[7; 32]).unwrap(); changed = tx.clone(); changed.input.push(tx.input[0].clone()); + sign(&mut changed, &prevout, &key, &key.public_key().to_compressed(), 1); assert_eq!(verify_input_authorization(&changed, 0, &prevout), Ok(false)); } From 5e9a97575bd9107daedc32fc9415cc9456078972 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:50:34 +0000 Subject: [PATCH 3/3] refactor(key-wallet): drop the no-op S normalization `EcdsaPublicKey::verify` already accepts high-S signatures, which `dashcore-crypto`'s `verify_accepts_high_s` covers, so the `normalize_s` call before it changed nothing and `should_accept_high_s_owner_authorization` passed without it. Both are removed, along with that test's copy of the group-order subtraction. The doc comment of `verify_input_authorization` is cut to three lines. The scope caveats it dropped are in the PR description. Co-Authored-By: Claude Opus 5.5 --- .../spend_authorization.rs | 48 ++----------------- 1 file changed, 4 insertions(+), 44 deletions(-) diff --git a/key-wallet/src/transaction_checking/spend_authorization.rs b/key-wallet/src/transaction_checking/spend_authorization.rs index b1eb430be..7cfee5f1a 100644 --- a/key-wallet/src/transaction_checking/spend_authorization.rs +++ b/key-wallet/src/transaction_checking/spend_authorization.rs @@ -19,14 +19,9 @@ pub enum SpendAuthorizationError { UnsupportedSighash(u8), } -/// Checks P2PKH/SIGHASH_ALL authorization to reserve one input's funding coin. -/// -/// The caller must obtain `prevout` from the funding transaction identified by -/// this input, and bind its outpoint to the wallet coin being reserved. A valid -/// signature proves authorization only: other inputs, amounts and consensus -/// rules are not validated, and this result supplies no finality evidence. -/// Unsupported forms return an error so an existing pending hold is not -/// silently released. Malformed or invalid supported authorizations return false. +/// Whether input `input_index` carries the owner's P2PKH `SIGHASH_ALL` signature for `prevout`. +/// The caller takes `prevout` from the funding transaction of that input's outpoint. +/// Unsupported forms return an error so an existing pending hold is not silently released. pub fn verify_input_authorization( transaction: &Transaction, input_index: usize, @@ -66,11 +61,9 @@ pub fn verify_input_authorization( let Some((&mode, _)) = signature.as_bytes().split_last() else { return Ok(false); }; - let Ok(mut signature) = Signature::from_slice(signature.as_bytes()) else { + let Ok(signature) = Signature::from_slice(signature.as_bytes()) else { return Ok(false); }; - // Both S encodings prove ownership; normalization preserves authorization. - signature.signature.normalize_s(); let signature = EcdsaSignature::from(signature.signature); let Ok(hash) = SighashCache::new(transaction).legacy_signature_hash( input_index, @@ -328,39 +321,6 @@ mod tests { assert_eq!(verify_input_authorization(&tx, 0, &prevout), Ok(true)); } - #[test] - fn should_accept_high_s_owner_authorization() { - let (mut tx, prevout) = signed(false); - let key = EcdsaSecretKey::from_bytes(&[7; 32]).unwrap(); - let hash = - SighashCache::new(&tx).legacy_signature_hash(0, &prevout.script_pubkey, 1).unwrap(); - let low = key.sign(&hash.to_byte_array()); - let mut compact = low.to_bytes(); - // secp256k1 group order: (r, n-s) is the high-S form of (r, s). - let order = hex_conservative::decode_to_vec( - "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", - ) - .unwrap(); - let mut borrow = false; - for i in (0..32).rev() { - let (difference, first_borrow) = order[i].overflowing_sub(compact[32 + i]); - let (difference, second_borrow) = difference.overflowing_sub(u8::from(borrow)); - compact[32 + i] = difference; - borrow = first_borrow || second_borrow; - } - let high = EcdsaSignature::from_bytes(&compact).unwrap(); - assert!(!high.is_low_s()); - let mut signature = high.with_der(|der| der.to_vec()); - signature.push(1); - tx.input[0].script_sig = Builder::new() - .push_slice(PushBytesBuf::try_from(signature).unwrap()) - .push_slice(key.public_key().to_compressed()) - .into_script(); - assert_eq!(verify_input_authorization(&tx, 0, &prevout), Ok(true)); - tx.output[0].value -= 1; - assert_eq!(verify_input_authorization(&tx, 0, &prevout), Ok(false)); - } - #[test] fn should_never_authorize_the_sighash_single_bug_digest() { let (mut tx, prevout) = signed(false);