From cc7b73c6e0ce9e30b6b080dced5b51668841441c Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 5 Nov 2026 10:58:49 +0000 Subject: [PATCH 01/38] fix(wallet): authenticate pending spends and InstantLock evidence MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move owner authorization policy into key-wallet. Reject unverified SPV InstantLock events before wallet mutation and expose authenticated, transaction-bound evidence for safely restoring historical records. Add signed test fixtures using the public verification query; preserve unsupported authorization as an error so existing holds remain safe. 🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent Co-Authored-By: Claude gpt-6-astra --- dash-spv/Cargo.toml | 2 + dash-spv/src/client/queries.rs | 20 +- dash-spv/src/lib.rs | 1 + dash-spv/src/sml_engine.rs | 9 + dash-spv/src/sync/mempool/manager.rs | 73 +++++ dash-spv/src/sync/mempool/sync_manager.rs | 2 +- dash-spv/src/test_utils/instant_lock.rs | 98 ++++++ dash-spv/src/test_utils/mod.rs | 2 + dash-spv/src/validation/instantlock.rs | 148 +++++++++- dash-spv/src/validation/mod.rs | 5 +- dash-spv/tests/instant_lock_evidence.rs | 83 ++++++ key-wallet/Cargo.toml | 1 + key-wallet/src/transaction_checking/mod.rs | 3 + .../spend_authorization.rs | 278 ++++++++++++++++++ 14 files changed, 721 insertions(+), 4 deletions(-) create mode 100644 dash-spv/src/test_utils/instant_lock.rs create mode 100644 dash-spv/tests/instant_lock_evidence.rs create mode 100644 key-wallet/src/transaction_checking/spend_authorization.rs diff --git a/dash-spv/Cargo.toml b/dash-spv/Cargo.toml index 8f32f7b74..316b09ada 100644 --- a/dash-spv/Cargo.toml +++ b/dash-spv/Cargo.toml @@ -70,6 +70,7 @@ hex-conservative = { workspace = true } bincode = { workspace = true } # Test utilities (optional) +dash-pkc = { workspace = true, features = ["bls", "std", "portable"], optional = true } tempfile = { workspace = true, optional = true } dashcore-rpc = { workspace = true, optional = true } @@ -127,6 +128,7 @@ test-utils = [ "key-wallet-manager/test-utils", "dep:tempfile", "dep:dashcore-rpc", + "dep:dash-pkc", ] [lints] diff --git a/dash-spv/src/client/queries.rs b/dash-spv/src/client/queries.rs index 2c2221adc..9b26a10f9 100644 --- a/dash-spv/src/client/queries.rs +++ b/dash-spv/src/client/queries.rs @@ -10,10 +10,11 @@ use crate::error::{Result, SpvError}; use crate::network::NetworkManager; use crate::sml_engine::MasternodeListEngine; use crate::storage::PersistentBlockHeaderStorage; +use crate::validation::{InstantLockVerificationError, VerifiedInstantLock}; use dashcore::sml::llmq_type::LLMQType; use dashcore::sml::masternode_list::MasternodeList; use dashcore::sml::quorum_entry::qualified_quorum_entry::QualifiedQuorumEntry; -use dashcore::QuorumHash; +use dashcore::{InstantLock, QuorumHash}; use key_wallet_manager::WalletInterface; use std::sync::Arc; use tokio::sync::RwLock; @@ -42,6 +43,23 @@ impl DashSpvClient { } } + /// Authenticates a lock using the client's synchronized quorum state. + /// + /// Returns `None` while its cycle or the masternode engine is unavailable. + /// Malformed locks and invalid signatures return an error. No network request + /// or wallet mutation is made; callers may retry after masternode sync advances. + /// Fetch this evidence before acquiring wallet or persistence write locks. + pub async fn verify_instant_lock( + &self, + instant_lock: &InstantLock, + ) -> std::result::Result, InstantLockVerificationError> { + let Some(engine) = &self.masternode_engine else { + return VerifiedInstantLock::verify::(instant_lock, None); + }; + let engine = engine.read().await; + VerifiedInstantLock::verify(instant_lock, Some(&*engine)) + } + /// The newest masternode list, `None` while masternode sync is off or has /// not built a list yet. pub async fn latest_masternode_list(&self) -> Option { diff --git a/dash-spv/src/lib.rs b/dash-spv/src/lib.rs index c6a9e8399..8dd47ab61 100644 --- a/dash-spv/src/lib.rs +++ b/dash-spv/src/lib.rs @@ -93,6 +93,7 @@ pub use sync::{ }; pub use tracing::level_filters::LevelFilter; pub use types::{FilterMatch, ValidationMode}; +pub use validation::{InstantLockVerificationError, VerifiedInstantLock}; // Re-export commonly used dashcore types pub use dashcore::{Address, BlockHash, Network, OutPoint, QuorumHash, ScriptBuf}; diff --git a/dash-spv/src/sml_engine.rs b/dash-spv/src/sml_engine.rs index e73497f81..4df647a84 100644 --- a/dash-spv/src/sml_engine.rs +++ b/dash-spv/src/sml_engine.rs @@ -410,6 +410,15 @@ impl MasternodeListEngine { self.rotated_quorums_per_cycle.get(cycle_hash) } + #[cfg(feature = "test-utils")] + pub(crate) fn install_test_instant_lock_cycle( + &mut self, + cycle: BlockHash, + quorums: BTreeMap, + ) { + self.rotated_quorums_per_cycle.insert(cycle, quorums); + } + #[cfg(any(test, feature = "test-utils"))] pub fn rotated_quorums_per_cycle( &self, diff --git a/dash-spv/src/sync/mempool/manager.rs b/dash-spv/src/sync/mempool/manager.rs index 26ce50d72..b90a13816 100644 --- a/dash-spv/src/sync/mempool/manager.rs +++ b/dash-spv/src/sync/mempool/manager.rs @@ -1360,6 +1360,79 @@ mod tests { assert_eq!(locks[0], (txid, Some(dummy_instant_lock(txid)))); } + #[test_case::test_case(true, false; "known pending")] + #[test_case::test_case(true, true; "known uncertain")] + #[test_case::test_case(false, false; "early pending")] + #[test_case::test_case(false, true; "early uncertain")] + #[tokio::test] + async fn should_ignore_unverified_instant_lock(known: bool, uncertain: bool) { + use crate::sync::SyncManager; + let (mut manager, requests, _rx) = create_test_manager(); + let tx = dashcore::Transaction { + version: 1, + lock_time: 0, + input: vec![], + output: vec![], + special_transaction_payload: None, + }; + let txid = tx.txid(); + assert!(manager.start_broadcast(&tx, &requests).await.is_empty()); + if known { + manager.transactions.insert( + txid, + crate::types::UnconfirmedTransaction::new( + tx.clone(), + dashcore::Amount::from_sat(0), + false, + false, + Vec::new(), + 0, + ), + ); + } + let status = if uncertain { + BroadcastStatus::Uncertain + } else { + BroadcastStatus::Pending + }; + manager.broadcasts.get_mut(&txid).unwrap().status = status; + let mut lock = dashcore::InstantLock::dummy(0..1); + lock.txid = txid; + let events = manager + .handle_sync_event( + &SyncEvent::InstantLockReceived { + instant_lock: lock.clone(), + validated: false, + }, + &requests, + ) + .await + .unwrap(); + assert!(events.is_empty(), "unverified locks cannot accept broadcasts"); + assert_eq!(manager.broadcasts.get(&txid).unwrap().status, status); + assert!(manager.pending_is_locks.is_empty()); + assert!(!manager.transactions.get(&txid).is_some_and(|tx| tx.is_instant_send)); + assert!(manager.wallet.read().await.processed_instant_locks.lock().await.is_empty()); + + let events = manager + .handle_sync_event( + &SyncEvent::InstantLockReceived { + instant_lock: lock.clone(), + validated: true, + }, + &requests, + ) + .await + .unwrap(); + assert_eq!(events.len(), 1, "later verification must still accept the broadcast"); + if known { + assert!(manager.transactions.get(&txid).unwrap().is_instant_send); + assert!(!manager.wallet.read().await.processed_instant_locks.lock().await.is_empty()); + } else { + assert_eq!(manager.pending_is_locks.get(&txid).unwrap().0, lock); + } + } + #[tokio::test] async fn test_mark_instant_send_stores_pending_for_unknown() { let (mut manager, _requests, _rx) = create_test_manager(); diff --git a/dash-spv/src/sync/mempool/sync_manager.rs b/dash-spv/src/sync/mempool/sync_manager.rs index 1043591ba..26669aef1 100644 --- a/dash-spv/src/sync/mempool/sync_manager.rs +++ b/dash-spv/src/sync/mempool/sync_manager.rs @@ -131,7 +131,7 @@ impl SyncManager for MempoolManager { } SyncEvent::InstantLockReceived { instant_lock, - .. + validated: true, } => Ok(self.process_instant_send(instant_lock.clone()).await), _ => Ok(vec![]), } diff --git a/dash-spv/src/test_utils/instant_lock.rs b/dash-spv/src/test_utils/instant_lock.rs new file mode 100644 index 000000000..9148ebff1 --- /dev/null +++ b/dash-spv/src/test_utils/instant_lock.rs @@ -0,0 +1,98 @@ +//! Signed fixtures for consumers testing authenticated InstantSend replay. + +use std::collections::BTreeMap; + +use dash_pkc::bls::{BlsError, BlsScIetf, BlsSecretKey}; +use dashcore::bls_sig_utils::{BLSPublicKey, BLSSignature}; +use dashcore::hash_types::QuorumVVecHash; +use dashcore::sml::llmq_entry_verification::LLMQEntryVerificationStatus; +use dashcore::sml::llmq_type::LLMQType; +use dashcore::sml::quorum_entry::qualified_quorum_entry::QualifiedQuorumEntry; +use dashcore::transaction::special_transaction::quorum_commitment::QuorumEntry; +use dashcore::{BlockHash, InstantLock, QuorumHash, Transaction}; +use key_wallet_manager::WalletInterface; + +use crate::client::DashSpvClient; +use crate::error::SpvError; +use crate::network::NetworkManager; + +/// Failure to build a deterministic signed test fixture. +#[derive(Debug, thiserror::Error)] +pub enum InstantLockFixtureError { + /// The fixture key could not be constructed. + #[error("invalid fixture BLS key: {0}")] + Key(#[from] BlsError), + /// The lock signing digest could not be encoded. + #[error("cannot encode fixture signing digest: {0}")] + Encoding(#[from] std::io::Error), +} + +/// A signed lock and synthetic quorum for isolated tests, never a network proof. +/// +/// Install into a temporary test client's engine, then call the client's public +/// `verify_instant_lock` query. This fixture cannot construct a verified token. +#[derive(Debug, Clone)] +pub struct InstantLockFixture { + instant_lock: InstantLock, + quorums: BTreeMap, +} + +impl InstantLockFixture { + /// Signs the transaction's ID and ordered inputs using a deterministic test key. + pub fn new(transaction: &Transaction) -> Result { + let key = BlsSecretKey::::from_bytes(&[1; 32])?; + let llmq_type = LLMQType::LlmqtypeTestDIP0024; + let quorum_hash = QuorumHash::from_byte_array([9; 32]); + let mut instant_lock = InstantLock { + version: 1, + inputs: transaction.input.iter().map(|input| input.previous_output).collect(), + txid: transaction.txid(), + cyclehash: BlockHash::from_byte_array([8; 32]), + signature: BLSSignature::from([0; 96]), + }; + let digest = instant_lock.sign_id(llmq_type, quorum_hash, None)?; + instant_lock.signature = + BLSSignature::from(key.sign_digest(digest.as_byte_array()).to_bytes()); + let quorums = (0..llmq_type.active_quorum_count() as u16) + .map(|index| { + let entry = QuorumEntry { + version: 2, + llmq_type, + quorum_hash, + quorum_index: Some(index as i16), + signers: vec![true; 4], + valid_members: vec![true; 4], + quorum_public_key: BLSPublicKey::from(key.public_key().to_bytes()), + quorum_vvec_hash: QuorumVVecHash::all_zeros(), + threshold_sig: instant_lock.signature, + all_commitment_aggregated_signature: instant_lock.signature, + }; + let mut quorum = QualifiedQuorumEntry::from(entry); + quorum.verified = LLMQEntryVerificationStatus::Verified; + (index, quorum) + }) + .collect(); + Ok(Self { + instant_lock, + quorums, + }) + } + + /// The signed payload to pass through the public verification query. + pub fn instant_lock(&self) -> &InstantLock { + &self.instant_lock + } + + /// Installs this synthetic quorum into an isolated test client's engine. + pub async fn install( + &self, + client: &DashSpvClient, + ) -> Result<(), SpvError> { + let engine = client.masternode_list_engine()?; + engine + .write() + .await + .install_test_instant_lock_cycle(self.instant_lock.cyclehash, self.quorums.clone()); + Ok(()) + } +} diff --git a/dash-spv/src/test_utils/mod.rs b/dash-spv/src/test_utils/mod.rs index 18fc8ec35..8d2c0bdb7 100644 --- a/dash-spv/src/test_utils/mod.rs +++ b/dash-spv/src/test_utils/mod.rs @@ -6,6 +6,7 @@ mod event_handler; mod filter; mod fs_helpers; mod header_storage; +mod instant_lock; pub(crate) mod masternode_network; mod network; mod node; @@ -21,6 +22,7 @@ pub use context::DashdTestContext; pub use event_handler::TestEventHandler; pub use fs_helpers::retain_test_dir; pub use header_storage::MockHeaderStorage; +pub use instant_lock::{InstantLockFixture, InstantLockFixtureError}; pub use masternode_network::{ ControllerInfo, MasternodeInfo, MasternodeTestContext, NetworkMetadata, }; diff --git a/dash-spv/src/validation/instantlock.rs b/dash-spv/src/validation/instantlock.rs index 88982e204..817bff27a 100644 --- a/dash-spv/src/validation/instantlock.rs +++ b/dash-spv/src/validation/instantlock.rs @@ -1,13 +1,84 @@ use std::collections::BTreeMap; use dashcore::bls_sig_utils::BlsScheme; +use dashcore::sml::llmq_entry_verification::LLMQEntryVerificationStatus; use dashcore::sml::message_verification_error::MessageVerificationError; use dashcore::sml::quorum_entry::qualified_quorum_entry::QualifiedQuorumEntry; -use dashcore::{InstantLock, QuorumSigningRequestId}; +use dashcore::{InstantLock, QuorumSigningRequestId, Transaction, Txid}; use crate::error::{ValidationError, ValidationResult}; +use crate::sml_engine::MasternodeListEngine; +use crate::storage::BlockHeaderStorage; use crate::validation::Validator; +/// An InstantLock authenticated against the client's synchronized quorum state. +/// +/// This evidence is process-local: persisted locks must be verified again on load. +/// Obtain it with `DashSpvClient::verify_instant_lock`; a stored context is not proof. +#[derive(Debug, Clone)] +pub struct VerifiedInstantLock { + instant_lock: InstantLock, +} + +/// A stored or received InstantLock failed authentication. +#[derive(Debug, thiserror::Error)] +pub enum InstantLockVerificationError { + /// The lock's fields are malformed. + #[error("malformed InstantLock: {0}")] + Malformed(#[source] ValidationError), + /// The lock is not signed by the selected quorum. + #[error("InstantLock authentication failed: {0}")] + InvalidSignature(#[source] ValidationError), +} + +impl VerifiedInstantLock { + /// The authenticated lock, including its signed inputs. + pub fn instant_lock(&self) -> &InstantLock { + &self.instant_lock + } + + /// The transaction ID covered by the quorum signature. + pub fn txid(&self) -> Txid { + self.instant_lock.txid + } + + /// Binds the evidence to the complete transaction and its ordered inputs. + /// + /// No wallet arithmetic or transaction consensus validation is performed. + pub fn matches_transaction(&self, transaction: &Transaction) -> bool { + self.txid() == transaction.txid() + && self + .instant_lock + .inputs + .iter() + .copied() + .eq(transaction.input.iter().map(|input| input.previous_output)) + } + + pub(crate) fn verify( + instant_lock: &InstantLock, + engine: Option<&MasternodeListEngine>, + ) -> Result, InstantLockVerificationError> { + InstantLockStructureValidator + .validate(instant_lock) + .map_err(InstantLockVerificationError::Malformed)?; + let Some(quorums) = + engine.and_then(|engine| engine.rotated_quorums_of_cycle(&instant_lock.cyclehash)) + else { + return Ok(None); + }; + if quorums.values().any(|quorum| quorum.verified != LLMQEntryVerificationStatus::Verified) { + return Ok(None); + } + InstantLockValidator::new(quorums) + .validate(instant_lock) + .map_err(InstantLockVerificationError::InvalidSignature)?; + Ok(Some(Self { + instant_lock: instant_lock.clone(), + })) + } +} + /// Rejects malformed InstantLocks. Needs no quorum data, so it runs before a /// lock is looked up, queued or cached. /// @@ -149,6 +220,81 @@ mod tests { deserialize(&hex_conservative::decode_to_vec("01018d53e7997ead57409750942af0d5e0aafc06f852a9a52308f4781b6a8220298f00000000c6f9d8c63dd15937ea70aaddb7890daad42c91bf6818e2bf76d183d6f2d9215b4b5f84978fad9dde7ab52bdcc0674be891e9029cc1ef0cb01200000000000000a27c98836c4c04653ab81eb4e07ddfc2c8c2c1036b75247969c05a4f25451cd78913a971f1899d9f2bddec9cf8e0104004f72f20c2856453e5aa3bcd2a8200670ec28feda38f67cc400fc72ef1966956656ec0765478c9d16e9a9e470c07f9ed").unwrap()).unwrap() } + #[test] + fn should_authenticate_stored_lock_only_with_available_cycle() { + let engine = TestEngine::mainnet_fixture(); + let lock = fixture_is_lock(); + assert!(VerifiedInstantLock::verify::(&lock, None,) + .unwrap() + .is_none()); + let empty = TestEngine::empty(dashcore::Network::Mainnet); + assert!(VerifiedInstantLock::verify(&lock, Some(&empty)).unwrap().is_none()); + let verified = VerifiedInstantLock::verify(&lock, Some(&engine)).unwrap().unwrap(); + assert_eq!(verified.txid(), lock.txid); + assert_eq!(verified.instant_lock(), &lock); + let mut unknown_cycle = lock.clone(); + unknown_cycle.cyclehash = dashcore::BlockHash::all_zeros(); + assert!(VerifiedInstantLock::verify(&unknown_cycle, Some(&engine)).unwrap().is_none()); + let mut invalid = lock.clone(); + invalid.txid = dashcore::Txid::from_byte_array([7; 32]); + assert!(matches!( + VerifiedInstantLock::verify(&invalid, Some(&engine)), + Err(InstantLockVerificationError::InvalidSignature(_)) + )); + let mut changed_input = lock.clone(); + changed_input.inputs[0].vout += 1; + assert!(matches!( + VerifiedInstantLock::verify(&changed_input, Some(&engine)), + Err(InstantLockVerificationError::InvalidSignature(_)) + )); + let mut changed_signature = lock.clone(); + changed_signature.signature = dashcore::bls_sig_utils::BLSSignature::from([1; 96]); + assert!(matches!( + VerifiedInstantLock::verify(&changed_signature, Some(&engine)), + Err(InstantLockVerificationError::InvalidSignature(_)) + )); + let mut malformed = lock; + malformed.inputs.clear(); + assert!(matches!( + VerifiedInstantLock::verify(&malformed, Some(&empty)), + Err(InstantLockVerificationError::Malformed(_)) + )); + } + + #[test] + fn should_bind_verified_evidence_without_wallet_arithmetic() { + let transaction = Transaction { + version: 1, + lock_time: 0, + input: vec![dashcore::TxIn { + previous_output: dashcore::OutPoint::new(Txid::from_byte_array([3; 32]), 0), + ..Default::default() + }], + output: vec![ + dashcore::TxOut { + value: u64::MAX, + script_pubkey: dashcore::ScriptBuf::new(), + }; + 2 + ], + special_transaction_payload: None, + }; + // This unit tests binding only; authentication is exercised with the signed fixture. + let mut lock = fixture_is_lock(); + lock.txid = transaction.txid(); + lock.inputs = transaction.input.iter().map(|input| input.previous_output).collect(); + let verified = VerifiedInstantLock { + instant_lock: lock, + }; + assert!(verified.matches_transaction(&transaction)); + let mut changed = transaction.clone(); + changed.output[0].value -= 1; + assert!(!verified.matches_transaction(&changed)); + let mut wrong_inputs = verified.clone(); + wrong_inputs.instant_lock.inputs[0].vout += 1; + assert!(!wrong_inputs.matches_transaction(&transaction)); + } + #[test] fn a_well_formed_lock_passes_the_structure_check() { assert!(InstantLockStructureValidator.validate(&InstantLock::dummy(0..3)).is_ok()); diff --git a/dash-spv/src/validation/mod.rs b/dash-spv/src/validation/mod.rs index 52e6275a1..2984ec543 100644 --- a/dash-spv/src/validation/mod.rs +++ b/dash-spv/src/validation/mod.rs @@ -11,7 +11,10 @@ pub use block::BlockValidator; pub use chainlock::ChainLockValidator; pub use filter::{FilterValidationInput, FilterValidator}; pub use header::BlockHeaderValidator; -pub use instantlock::{InstantLockStructureValidator, InstantLockValidator}; +pub use instantlock::{ + InstantLockStructureValidator, InstantLockValidator, InstantLockVerificationError, + VerifiedInstantLock, +}; pub use masternode_list::MasternodeListValidator; use crate::error::ValidationResult; diff --git a/dash-spv/tests/instant_lock_evidence.rs b/dash-spv/tests/instant_lock_evidence.rs new file mode 100644 index 000000000..a7249f4ed --- /dev/null +++ b/dash-spv/tests/instant_lock_evidence.rs @@ -0,0 +1,83 @@ +#![cfg(feature = "test-utils")] + +use dash_spv::test_utils::{InstantLockFixture, MockNetworkManager}; +use dash_spv::{ClientConfig, DashSpvClient, InstantLockVerificationError, VerifiedInstantLock}; +use dashcore::InstantLock; +use dashcore::{OutPoint, ScriptBuf, Transaction, TxIn, TxOut, Txid}; +use key_wallet_manager::test_utils::MockWallet; +use std::sync::Arc; +use tempfile::TempDir; +use tokio::sync::RwLock; + +#[tokio::test] +async fn should_verify_instant_lock_after_cycle_arrives_without_wallet_arithmetic() { + let directory = TempDir::new().unwrap(); + let config = ClientConfig::mainnet().without_filters().with_storage_path(directory.path()); + let wallet = Arc::new(RwLock::new(MockWallet::new())); + let client = DashSpvClient::new(config, MockNetworkManager::new(), wallet.clone(), vec![]) + .await + .unwrap(); + let transaction = Transaction { + version: 1, + lock_time: 0, + input: vec![TxIn { + previous_output: OutPoint::new(Txid::from_byte_array([3; 32]), 0), + ..Default::default() + }], + output: vec![ + TxOut { + value: u64::MAX, + script_pubkey: ScriptBuf::new() + }; + 2 + ], + special_transaction_payload: None, + }; + let fixture = InstantLockFixture::new(&transaction).unwrap(); + let lock = fixture.instant_lock(); + assert!(client.verify_instant_lock(lock).await.unwrap().is_none()); + fixture.install(&client).await.unwrap(); + let proof: VerifiedInstantLock = client.verify_instant_lock(lock).await.unwrap().unwrap(); + assert!(proof.matches_transaction(&transaction)); + assert_eq!(proof.instant_lock(), lock); + assert_eq!(proof.txid(), transaction.txid()); + assert!(wallet.read().await.processed_instant_locks.lock().await.is_empty()); + + let mut changed_body = transaction.clone(); + changed_body.output[0].value -= 1; + assert!(!proof.matches_transaction(&changed_body)); + let mut wrong_txid = lock.clone(); + wrong_txid.txid = changed_body.txid(); + let mut wrong_input = lock.clone(); + wrong_input.inputs[0].vout += 1; + let mut wrong_signature = lock.clone(); + wrong_signature.signature = dashcore::bls_sig_utils::BLSSignature::from([1; 96]); + for invalid in [wrong_txid, wrong_input, wrong_signature] { + assert!(matches!( + client.verify_instant_lock(&invalid).await, + Err(InstantLockVerificationError::InvalidSignature(_)) + )); + } +} + +#[tokio::test] +async fn should_defer_instant_lock_when_masternodes_are_disabled() { + let directory = TempDir::new().unwrap(); + let config = ClientConfig::mainnet() + .without_filters() + .without_masternodes() + .with_storage_path(directory.path()); + let client = DashSpvClient::new( + config, + MockNetworkManager::new(), + Arc::new(RwLock::new(MockWallet::new())), + vec![], + ) + .await + .unwrap(); + assert!(client.verify_instant_lock(&InstantLock::dummy(0..1)).await.unwrap().is_none()); + assert!(matches!( + client.verify_instant_lock(&InstantLock::default()).await, + Err(InstantLockVerificationError::Malformed(_)) + )); +} diff --git a/key-wallet/Cargo.toml b/key-wallet/Cargo.toml index c172251ab..36f8cd498 100644 --- a/key-wallet/Cargo.toml +++ b/key-wallet/Cargo.toml @@ -70,6 +70,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..6ce4a0db7 --- /dev/null +++ b/key-wallet/src/transaction_checking/spend_authorization.rs @@ -0,0 +1,278 @@ +//! 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); + } + if !prevout.script_pubkey.is_p2pkh() { + 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() + != &prevout.script_pubkey.as_bytes()[3..23] + { + 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 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}; + + 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, + ) { + let hash = SighashCache::new(&*tx) + .legacy_signature_hash(0, &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[0].script_sig = Builder::new() + .push_slice(PushBytesBuf::try_from(signature).unwrap()) + .push_slice(PushBytesBuf::try_from(public_key.to_vec()).unwrap()) + .into_script(); + } + + #[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)); + } + } + + #[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_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_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 f7bb4bad357be190ff2de68fff9d3519cde629d4 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:14:14 +0000 Subject: [PATCH 02/38] fix(spv): defer InstantLocks missing their signing quorum MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Classify an absent selected quorum or empty cycle as unavailable evidence, while retaining errors for malformed locks and invalid BLS signatures. Cover partial-cycle arrival and retry through the public verification API. 🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent Co-Authored-By: Claude gpt-6-astra --- dash-spv/src/test_utils/instant_lock.rs | 6 ++++ dash-spv/src/validation/instantlock.rs | 12 +++++-- dash-spv/tests/instant_lock_evidence.rs | 46 +++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 3 deletions(-) diff --git a/dash-spv/src/test_utils/instant_lock.rs b/dash-spv/src/test_utils/instant_lock.rs index 9148ebff1..4d69fb539 100644 --- a/dash-spv/src/test_utils/instant_lock.rs +++ b/dash-spv/src/test_utils/instant_lock.rs @@ -78,6 +78,12 @@ impl InstantLockFixture { }) } + /// Omits one quorum slot to model a cycle whose synchronization is incomplete. + pub fn without_quorum(mut self, index: u16) -> Self { + self.quorums.remove(&index); + self + } + /// The signed payload to pass through the public verification query. pub fn instant_lock(&self) -> &InstantLock { &self.instant_lock diff --git a/dash-spv/src/validation/instantlock.rs b/dash-spv/src/validation/instantlock.rs index 817bff27a..5e1821d81 100644 --- a/dash-spv/src/validation/instantlock.rs +++ b/dash-spv/src/validation/instantlock.rs @@ -70,9 +70,15 @@ impl VerifiedInstantLock { if quorums.values().any(|quorum| quorum.verified != LLMQEntryVerificationStatus::Verified) { return Ok(None); } - InstantLockValidator::new(quorums) - .validate(instant_lock) - .map_err(InstantLockVerificationError::InvalidSignature)?; + let validator = InstantLockValidator::new(quorums); + if matches!( + validator.signing_quorum(instant_lock), + Err(MessageVerificationError::CycleHashNotPresent(_) + | MessageVerificationError::QuorumIndexNotFound(..)) + ) { + return Ok(None); + } + validator.validate(instant_lock).map_err(InstantLockVerificationError::InvalidSignature)?; Ok(Some(Self { instant_lock: instant_lock.clone(), })) diff --git a/dash-spv/tests/instant_lock_evidence.rs b/dash-spv/tests/instant_lock_evidence.rs index a7249f4ed..e89ae3821 100644 --- a/dash-spv/tests/instant_lock_evidence.rs +++ b/dash-spv/tests/instant_lock_evidence.rs @@ -81,3 +81,49 @@ async fn should_defer_instant_lock_when_masternodes_are_disabled() { Err(InstantLockVerificationError::Malformed(_)) )); } + +#[tokio::test] +async fn should_defer_instant_lock_until_selected_quorum_arrives() { + let directory = TempDir::new().unwrap(); + let config = ClientConfig::mainnet().without_filters().with_storage_path(directory.path()); + let client = DashSpvClient::new( + config, + MockNetworkManager::new(), + Arc::new(RwLock::new(MockWallet::new())), + vec![], + ) + .await + .unwrap(); + let transaction = Transaction { + version: 1, + lock_time: 0, + input: vec![TxIn { + previous_output: OutPoint::new(Txid::from_byte_array([3; 32]), 0), + ..Default::default() + }], + output: vec![], + special_transaction_payload: None, + }; + let fixture = InstantLockFixture::new(&transaction).unwrap(); + let lock = fixture.instant_lock(); + let mut missing = 0; + // The test quorum type has two active slots; exactly one signs this lock. + for index in 0..2 { + fixture.clone().without_quorum(index).install(&client).await.unwrap(); + match client.verify_instant_lock(lock).await { + Ok(None) => missing += 1, + Ok(Some(proof)) => assert!(proof.matches_transaction(&transaction)), + Err(error) => panic!("incomplete quorum data is unavailable, not invalid: {error}"), + } + } + assert_eq!(missing, 1); + fixture.clone().without_quorum(0).without_quorum(1).install(&client).await.unwrap(); + assert!(client.verify_instant_lock(lock).await.unwrap().is_none()); + fixture.install(&client).await.unwrap(); + assert!(client + .verify_instant_lock(lock) + .await + .unwrap() + .unwrap() + .matches_transaction(&transaction)); +} From 2e3a1a701203f27a3d78678f3f18de60dab1d697 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:35:39 +0000 Subject: [PATCH 03/38] test(wallet): retain authorization coverage for witness data MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Witness remains available for legacy transaction encoding and does not contribute to the transaction ID or owner authorization digest. 🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent Co-Authored-By: Claude gpt-6-astra --- .../src/transaction_checking/spend_authorization.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/key-wallet/src/transaction_checking/spend_authorization.rs b/key-wallet/src/transaction_checking/spend_authorization.rs index 6ce4a0db7..61ac3b5ac 100644 --- a/key-wallet/src/transaction_checking/spend_authorization.rs +++ b/key-wallet/src/transaction_checking/spend_authorization.rs @@ -100,7 +100,7 @@ mod tests { }; use dashcore::crypto::ecdsa::EcdsaSecretKey; use dashcore::script::{Builder, PushBytesBuf}; - use dashcore::{OutPoint, ScriptBuf, TxIn, Txid}; + use dashcore::{OutPoint, ScriptBuf, TxIn, Txid, Witness}; fn signed(uncompressed: bool) -> (Transaction, TxOut) { let key = EcdsaSecretKey::from_bytes(&[7; 32]).unwrap(); @@ -222,6 +222,15 @@ mod tests { } } + #[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); From 32cfbe807785c4803ccdefa1ed98eb9e6c89213c Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:36:35 +0000 Subject: [PATCH 04/38] fix(spv): bind verified InstantLocks to their source network MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Retain the verifying engine's network in opaque evidence so wallet replay can reject proofs from another network without trusting caller metadata. Exercise public verification with both Mainnet and Testnet clients. 🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent Co-Authored-By: Claude gpt-6-astra --- dash-spv/src/validation/instantlock.rs | 18 ++++++++--- dash-spv/tests/instant_lock_evidence.rs | 40 ++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 5 deletions(-) diff --git a/dash-spv/src/validation/instantlock.rs b/dash-spv/src/validation/instantlock.rs index 5e1821d81..f99c28084 100644 --- a/dash-spv/src/validation/instantlock.rs +++ b/dash-spv/src/validation/instantlock.rs @@ -4,7 +4,7 @@ use dashcore::bls_sig_utils::BlsScheme; use dashcore::sml::llmq_entry_verification::LLMQEntryVerificationStatus; use dashcore::sml::message_verification_error::MessageVerificationError; use dashcore::sml::quorum_entry::qualified_quorum_entry::QualifiedQuorumEntry; -use dashcore::{InstantLock, QuorumSigningRequestId, Transaction, Txid}; +use dashcore::{InstantLock, Network, QuorumSigningRequestId, Transaction, Txid}; use crate::error::{ValidationError, ValidationResult}; use crate::sml_engine::MasternodeListEngine; @@ -18,6 +18,7 @@ use crate::validation::Validator; #[derive(Debug, Clone)] pub struct VerifiedInstantLock { instant_lock: InstantLock, + network: Network, } /// A stored or received InstantLock failed authentication. @@ -37,6 +38,11 @@ impl VerifiedInstantLock { &self.instant_lock } + /// The network of the client whose quorum state authenticated this lock. + pub fn network(&self) -> Network { + self.network + } + /// The transaction ID covered by the quorum signature. pub fn txid(&self) -> Txid { self.instant_lock.txid @@ -45,6 +51,7 @@ impl VerifiedInstantLock { /// Binds the evidence to the complete transaction and its ordered inputs. /// /// No wallet arithmetic or transaction consensus validation is performed. + /// Consumers must also match `network()` to the wallet receiving the evidence. pub fn matches_transaction(&self, transaction: &Transaction) -> bool { self.txid() == transaction.txid() && self @@ -62,9 +69,10 @@ impl VerifiedInstantLock { InstantLockStructureValidator .validate(instant_lock) .map_err(InstantLockVerificationError::Malformed)?; - let Some(quorums) = - engine.and_then(|engine| engine.rotated_quorums_of_cycle(&instant_lock.cyclehash)) - else { + let Some(engine) = engine else { + return Ok(None); + }; + let Some(quorums) = engine.rotated_quorums_of_cycle(&instant_lock.cyclehash) else { return Ok(None); }; if quorums.values().any(|quorum| quorum.verified != LLMQEntryVerificationStatus::Verified) { @@ -81,6 +89,7 @@ impl VerifiedInstantLock { validator.validate(instant_lock).map_err(InstantLockVerificationError::InvalidSignature)?; Ok(Some(Self { instant_lock: instant_lock.clone(), + network: engine.network(), })) } } @@ -291,6 +300,7 @@ mod tests { lock.inputs = transaction.input.iter().map(|input| input.previous_output).collect(); let verified = VerifiedInstantLock { instant_lock: lock, + network: Network::Mainnet, }; assert!(verified.matches_transaction(&transaction)); let mut changed = transaction.clone(); diff --git a/dash-spv/tests/instant_lock_evidence.rs b/dash-spv/tests/instant_lock_evidence.rs index e89ae3821..e10b8b1b7 100644 --- a/dash-spv/tests/instant_lock_evidence.rs +++ b/dash-spv/tests/instant_lock_evidence.rs @@ -2,7 +2,7 @@ use dash_spv::test_utils::{InstantLockFixture, MockNetworkManager}; use dash_spv::{ClientConfig, DashSpvClient, InstantLockVerificationError, VerifiedInstantLock}; -use dashcore::InstantLock; +use dashcore::{InstantLock, Network}; use dashcore::{OutPoint, ScriptBuf, Transaction, TxIn, TxOut, Txid}; use key_wallet_manager::test_utils::MockWallet; use std::sync::Arc; @@ -127,3 +127,41 @@ async fn should_defer_instant_lock_until_selected_quorum_arrives() { .unwrap() .matches_transaction(&transaction)); } + +#[tokio::test] +async fn should_bind_instant_lock_evidence_to_the_verifying_network() { + let transaction = Transaction { + version: 1, + lock_time: 0, + input: vec![TxIn { + previous_output: OutPoint::new(Txid::from_byte_array([3; 32]), 0), + ..Default::default() + }], + output: vec![], + special_transaction_payload: None, + }; + let fixture = InstantLockFixture::new(&transaction).unwrap(); + for network in [Network::Mainnet, Network::Testnet] { + let directory = TempDir::new().unwrap(); + let config = + ClientConfig::new(network).without_filters().with_storage_path(directory.path()); + let client = DashSpvClient::new( + config, + MockNetworkManager::new(), + Arc::new(RwLock::new(MockWallet::new())), + vec![], + ) + .await + .unwrap(); + fixture.install(&client).await.unwrap(); + let proof = client.verify_instant_lock(fixture.instant_lock()).await.unwrap().unwrap(); + assert!(proof.matches_transaction(&transaction)); + assert_eq!(proof.network(), network); + let other_network = if network == Network::Mainnet { + Network::Testnet + } else { + Network::Mainnet + }; + assert_ne!(proof.network(), other_network); + } +} From 493f66b1231b3b16d851b925ac4840accbbc0e2a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:06:46 +0000 Subject: [PATCH 05/38] test(key-wallet): pin that the SIGHASH_SINGLE bug digest never authorizes a spend Co-Authored-By: Claude Opus 5.5 --- .../spend_authorization.rs | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/key-wallet/src/transaction_checking/spend_authorization.rs b/key-wallet/src/transaction_checking/spend_authorization.rs index 61ac3b5ac..d2daa0ecc 100644 --- a/key-wallet/src/transaction_checking/spend_authorization.rs +++ b/key-wallet/src/transaction_checking/spend_authorization.rs @@ -264,6 +264,28 @@ mod tests { 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); From a487959f9c8e402967fdffe9440eb9cb6b844230 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:06:46 +0000 Subject: [PATCH 06/38] test(dash-spv): reproduce a forged InstantLock shadowing the genuine lock Fails on the PR head: the forged lock is cached as unvalidated and the genuine lock for the same txid is then dropped as a duplicate, so the mempool (which now acts only on validated locks) never sees it. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sync/instantsend/manager.rs | 31 ++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/dash-spv/src/sync/instantsend/manager.rs b/dash-spv/src/sync/instantsend/manager.rs index 2b19acb24..519faa8e9 100644 --- a/dash-spv/src/sync/instantsend/manager.rs +++ b/dash-spv/src/sync/instantsend/manager.rs @@ -504,6 +504,37 @@ mod tests { assert_eq!(manager.pending_count(), 1); } + /// A peer-forged, well-formed lock must not shadow the genuine lock for the + /// same txid: the mempool only acts on validated locks. + #[tokio::test] + async fn should_accept_genuine_lock_after_forged_lock_for_same_txid() { + let engine = TestEngine::mainnet_fixture(); + let mut manager = InstantSendManager::new(Arc::new(RwLock::new(engine))); + // An IS lock of the mainnet fixture's cycle, signed by its quorum at index 23. + let genuine: InstantLock = dashcore::consensus::deserialize(&hex_conservative::decode_to_vec("01018d53e7997ead57409750942af0d5e0aafc06f852a9a52308f4781b6a8220298f00000000c6f9d8c63dd15937ea70aaddb7890daad42c91bf6818e2bf76d183d6f2d9215b4b5f84978fad9dde7ab52bdcc0674be891e9029cc1ef0cb01200000000000000a27c98836c4c04653ab81eb4e07ddfc2c8c2c1036b75247969c05a4f25451cd78913a971f1899d9f2bddec9cf8e0104004f72f20c2856453e5aa3bcd2a8200670ec28feda38f67cc400fc72ef1966956656ec0765478c9d16e9a9e470c07f9ed").unwrap()).unwrap(); + let mut forged = genuine.clone(); + forged.signature = BLSSignature::from([1u8; 96]); + + let events = manager.process_instantlock(&forged).await.unwrap(); + assert!(matches!( + events.as_slice(), + [SyncEvent::InstantLockReceived { + validated: false, + .. + }] + )); + + let events = manager.process_instantlock(&genuine).await.unwrap(); + assert!( + matches!( + events.as_slice(), + [SyncEvent::InstantLockReceived { instant_lock, validated: true }] + if instant_lock == &genuine + ), + "genuine lock was shadowed by the forged one: {events:?}" + ); + } + #[tokio::test] async fn test_instantsend_pending_queue() { let mut manager = create_test_manager(); From 8f75a8af3e8c8dd3090fccd6fd21e20179d88140 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:23:14 +0000 Subject: [PATCH 07/38] feat(dashcore-crypto): add `BlsSecretKey::sign_digest` Signs a 32-byte digest under the key's scheme, so crates that need BLS signatures (such as the dash-spv InstantLock test fixture) go through the `dashcore-crypto` newtypes instead of depending on `dash-pkc` directly. Co-Authored-By: Claude Opus 5.5 --- crypto/src/bls.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/crypto/src/bls.rs b/crypto/src/bls.rs index c4fbd6980..55d7a397b 100644 --- a/crypto/src/bls.rs +++ b/crypto/src/bls.rs @@ -311,6 +311,20 @@ impl BlsSecretKey<'_> { } } + /// Signs a 32-byte message digest, written under the scheme. + /// + /// # Errors + /// + /// Returns `InvalidSecretKey` when the bytes are not a valid scalar. + pub fn sign_digest(self, digest: &[u8; 32]) -> Result { + let signature = match self.scheme { + BlsScheme::Legacy => self.scalar::()?.sign_digest(digest).to_bytes(), + BlsScheme::Modern => self.scalar::()?.sign_digest(digest).to_bytes(), + }; + + Ok(BlsSigBytes::from_bytes(signature)) + } + fn scalar(self) -> Result, BlsError> { PkcSecretKey::::from_bytes(self.bytes.as_bytes()).map_err(|_| BlsError::InvalidSecretKey) } @@ -571,6 +585,23 @@ mod tests { assert_eq!(signature.is_valid(), valid); } + #[test] + fn a_digest_signature_verifies_against_its_key_and_digest() { + let secret = BlsSkBytes::from_bytes([1; BLS_SK_LEN]); + for scheme in [BlsScheme::Modern, BlsScheme::Legacy] { + let key = secret.as_scheme(scheme); + let signature = key.sign_digest(&CHAINLOCK_BLOCK_HASH).unwrap(); + let public_key = key.public_key().unwrap().as_scheme(scheme); + assert!(public_key.verify(&CHAINLOCK_BLOCK_HASH, &signature).is_ok()); + assert!(public_key.verify(&[0; 32], &signature).is_err()); + } + let invalid = BlsSkBytes::from_bytes([0xff; BLS_SK_LEN]); + assert_eq!( + invalid.as_scheme(BlsScheme::Modern).sign_digest(&[0; 32]), + Err(BlsError::InvalidSecretKey) + ); + } + #[test] fn test_legacy_format_detection() { // Test the ability to detect and handle legacy format keys From bbb7a81824a52042b617717700578a8198501392 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:23:14 +0000 Subject: [PATCH 08/38] fix(dash-spv): classify InstantLocks once for live and replay `VerifiedInstantLock::verify` is now the single classifier for both `InstantSendManager` and `DashSpvClient::verify_instant_lock`: verified, deferred while quorum data is missing or incomplete, or rejected when malformed or refuted by a complete, verified cycle. The manager drops rejected locks instead of keeping them pending. The manager deduplicates only against a verified lock or an identical pending one, so a forged, well-formed lock no longer shadows the genuine lock for the same txid. Once a lock for a txid verifies, the other pending locks for it are dropped and never emit. Verification also requires every quorum of the cycle to be of the network's InstantSend quorum type (any rotating type on a devnet without an override). Per-lock signature results log at trace and debug, so re-verifying a wallet's own locks does not write its txids at info or warn. The test fixture signs through `dashcore-crypto` with the given network's InstantSend quorum type, drops the direct `dash-pkc` dependency, and documents that `install` makes its public test key verify on that client. `InstantLockFixture::new` takes the network. Co-Authored-By: Claude Opus 5.5 --- dash-spv/Cargo.toml | 2 - dash-spv/src/client/queries.rs | 7 +- dash-spv/src/sml_engine.rs | 24 +++- dash-spv/src/sync/instantsend/manager.rs | 165 ++++++++++++++++------- dash-spv/src/test_utils/instant_lock.rs | 36 ++--- dash-spv/src/validation/instantlock.rs | 63 ++++----- dash-spv/src/validation/mod.rs | 5 +- dash-spv/tests/instant_lock_evidence.rs | 165 ++++++++--------------- 8 files changed, 250 insertions(+), 217 deletions(-) diff --git a/dash-spv/Cargo.toml b/dash-spv/Cargo.toml index 316b09ada..8f32f7b74 100644 --- a/dash-spv/Cargo.toml +++ b/dash-spv/Cargo.toml @@ -70,7 +70,6 @@ hex-conservative = { workspace = true } bincode = { workspace = true } # Test utilities (optional) -dash-pkc = { workspace = true, features = ["bls", "std", "portable"], optional = true } tempfile = { workspace = true, optional = true } dashcore-rpc = { workspace = true, optional = true } @@ -128,7 +127,6 @@ test-utils = [ "key-wallet-manager/test-utils", "dep:tempfile", "dep:dashcore-rpc", - "dep:dash-pkc", ] [lints] diff --git a/dash-spv/src/client/queries.rs b/dash-spv/src/client/queries.rs index d4564e824..d1dfc4b9a 100644 --- a/dash-spv/src/client/queries.rs +++ b/dash-spv/src/client/queries.rs @@ -46,9 +46,10 @@ impl DashSpvClient { /// Authenticates a lock using the client's synchronized quorum state. /// - /// Returns `None` while its cycle or the masternode engine is unavailable. - /// Malformed locks and invalid signatures return an error. No network request - /// or wallet mutation is made; callers may retry after masternode sync advances. + /// Returns `None` while the masternode engine or the lock's quorum is unavailable. + /// Malformed locks, and signatures a complete cycle of quorums refutes, return an + /// error. No network request or wallet mutation is made; callers may retry after + /// masternode sync advances. /// Fetch this evidence before acquiring wallet or persistence write locks. pub async fn verify_instant_lock( &self, diff --git a/dash-spv/src/sml_engine.rs b/dash-spv/src/sml_engine.rs index 978cd59d5..3fb6162d6 100644 --- a/dash-spv/src/sml_engine.rs +++ b/dash-spv/src/sml_engine.rs @@ -705,7 +705,7 @@ impl MasternodeListEngine { /// `true` when the stored cycle has a `Verified` quorum for every active /// slot. A partial cycle stays open so a later QRInfo can complete it. - fn is_cycle_fully_verified(&self, cycle_hash: &BlockHash) -> bool { + pub(crate) fn is_cycle_fully_verified(&self, cycle_hash: &BlockHash) -> bool { let expected = self.network.isd_llmq_type().active_quorum_count() as usize; self.rotated_quorums_per_cycle.get(cycle_hash).is_some_and(|existing| { existing.len() == expected @@ -893,7 +893,7 @@ impl MasternodeListEngine { /// rotating type the peer serves. fn rotation_quorum_type(&self, served: &[QuorumEntry]) -> LLMQType { let configured = self.network.isd_llmq_type(); - if self.network != Network::Devnet || devnet_isd_type_override().is_some() { + if !self.reads_served_rotation_type() { return configured; } served @@ -903,6 +903,19 @@ impl MasternodeListEngine { .unwrap_or(configured) } + /// Whether a quorum of `llmq_type` can sign this network's IS locks: the + /// configured rotation type, or on a devnet without an override, any rotating type. + pub(crate) fn signs_instant_locks(&self, llmq_type: LLMQType) -> bool { + if self.reads_served_rotation_type() { + return llmq_type.is_rotating_quorum_type(); + } + llmq_type == self.network.isd_llmq_type() + } + + fn reads_served_rotation_type(&self) -> bool { + self.network == Network::Devnet && devnet_isd_type_override().is_none() + } + /// The hash of the newest cycle base in an active set. A failed DKG leaves /// an older cycle's quorum at its index, so a set can span cycles, and the /// newest one is the cycle the set is active for. @@ -1258,7 +1271,7 @@ pub(crate) mod test_support { use dashcore::consensus::deserialize; use dashcore::hash_types::QuorumVVecHash; use dashcore::sml::masternode_list_entry::qualified_masternode_list_entry::QualifiedMasternodeListEntry; - use dashcore::ProTxHash; + use dashcore::{InstantLock, ProTxHash}; pub(crate) type TestEngine = MasternodeListEngine; @@ -1294,6 +1307,11 @@ pub(crate) mod test_support { block_hashes.into_iter().map(|(height, block_hash)| (block_hash, height)).collect() } + /// An IS lock of the mainnet fixture's cycle, signed by its quorum at index 23. + pub(crate) fn mainnet_fixture_is_lock() -> InstantLock { + deserialize(&hex_conservative::decode_to_vec("01018d53e7997ead57409750942af0d5e0aafc06f852a9a52308f4781b6a8220298f00000000c6f9d8c63dd15937ea70aaddb7890daad42c91bf6818e2bf76d183d6f2d9215b4b5f84978fad9dde7ab52bdcc0674be891e9029cc1ef0cb01200000000000000a27c98836c4c04653ab81eb4e07ddfc2c8c2c1036b75247969c05a4f25451cd78913a971f1899d9f2bddec9cf8e0104004f72f20c2856453e5aa3bcd2a8200670ec28feda38f67cc400fc72ef1966956656ec0765478c9d16e9a9e470c07f9ed").unwrap()).unwrap() + } + /// A commitment with one signer and zeroed keys and signatures. pub(crate) fn quorum_entry( llmq_type: LLMQType, diff --git a/dash-spv/src/sync/instantsend/manager.rs b/dash-spv/src/sync/instantsend/manager.rs index 519faa8e9..af436ee30 100644 --- a/dash-spv/src/sync/instantsend/manager.rs +++ b/dash-spv/src/sync/instantsend/manager.rs @@ -3,7 +3,7 @@ //! Handles InstantSendLock messages (islock) from the network. Validates locks //! when masternode data is available, queues them when not. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use std::time::{Duration, Instant, SystemTime}; @@ -15,7 +15,7 @@ use tokio::sync::RwLock; use crate::error::SyncResult; use crate::sync::{InstantSendProgress, SyncEvent, SyncState}; -use crate::validation::{InstantLockStructureValidator, InstantLockValidator, Validator}; +use crate::validation::VerifiedInstantLock; /// Maximum number of pending InstantLocks awaiting validation. const MAX_PENDING_INSTANTLOCKS: usize = 500; @@ -139,48 +139,43 @@ impl InstantSendManager { tracing::info!("Processing InstantLock for txid {}", txid); - // Check for duplicates - if self.instantlocks.contains_key(&txid) { + // Only a verified lock settles its txid: an unverified one, possibly forged, + // must not shadow the genuine lock for the same transaction. + if self.instantlocks.get(&txid).is_some_and(|entry| entry.validated) + || self.pending_instantlocks.iter().any(|pending| pending.instant_lock == *instantlock) + { tracing::debug!("Already have InstantLock for txid {}", txid); return Ok(vec![]); } - // A malformed lock is dropped before it is queued or cached, so it can + // A rejected lock is dropped before it is queued or cached, so it can // neither stay pending nor shadow the genuine lock for its txid. - if let Err(e) = InstantLockStructureValidator.validate(instantlock) { - tracing::warn!("Invalid InstantLock for txid {}: {}", txid, e); - self.progress.add_invalid(1); - return Ok(vec![]); - } - - // Until the engine knows the lock's cycle, or when its signature does not - // verify, the engine may only lack its quorum yet: the lock is kept pending. let engine = self.engine.read().await; - let result = engine - .rotated_quorums_of_cycle(&instantlock.cyclehash) - .map(|quorums| InstantLockValidator::new(quorums).validate(instantlock)); + let result = VerifiedInstantLock::verify(instantlock, Some(&*engine)); drop(engine); let validated = match result { - Some(Ok(())) => true, - Some(Err(e)) => { - tracing::warn!("InstantLock for txid {} not verified yet: {}", txid, e); + Ok(Some(_)) => true, + Ok(None) => { + tracing::debug!("InstantLock for txid {} awaits quorum data", txid); false } - None => { - tracing::debug!("InstantLock for txid {} is of a cycle not known yet", txid); - false + Err(e) => { + tracing::warn!("Rejected InstantLock for txid {}: {}", txid, e); + self.progress.add_invalid(1); + return Ok(vec![]); } }; if validated { self.progress.add_valid(1); + self.pending_instantlocks.retain(|pending| pending.instant_lock.txid != txid); } else { self.queue_pending(PendingInstantLock { instant_lock: instantlock.clone(), first_seen: Instant::now(), }); - self.progress.update_pending(self.pending_instantlocks.len()); } + self.progress.update_pending(self.pending_instantlocks.len()); // Store in cache let entry = InstantLockEntry { @@ -247,6 +242,8 @@ impl InstantSendManager { let pending = std::mem::take(&mut self.pending_instantlocks); let mut events = Vec::new(); + let mut validated_txids = HashSet::new(); + let mut rejected = 0; for pending_lock in pending { let txid = pending_lock.instant_lock.txid; @@ -256,29 +253,41 @@ impl InstantSendManager { self.progress.add_invalid(1); continue; } + if validated_txids.contains(&txid) { + continue; + } - let lock = &pending_lock.instant_lock; - let validated = - self.engine.read().await.rotated_quorums_of_cycle(&lock.cyclehash).is_some_and( - |quorums| InstantLockValidator::new(quorums).validate(lock).is_ok(), - ); - - if validated { - self.progress.add_valid(1); - // Update the cached entry - if let Some(entry) = self.instantlocks.get_mut(&txid) { - entry.validated = true; + let result = VerifiedInstantLock::verify( + &pending_lock.instant_lock, + Some(&*self.engine.read().await), + ); + match result { + Ok(Some(_)) => { + self.progress.add_valid(1); + validated_txids.insert(txid); + if let Some(entry) = self.instantlocks.get_mut(&txid) { + entry.validated = true; + } + events.push(SyncEvent::InstantLockReceived { + instant_lock: pending_lock.instant_lock, + validated: true, + }); } - events.push(SyncEvent::InstantLockReceived { - instant_lock: pending_lock.instant_lock.clone(), - validated: true, - }); - } else { - // Still can't validate, re-queue - self.queue_pending(pending_lock); + Ok(None) => self.queue_pending(pending_lock), + Err(_) => rejected += 1, } } + // Other locks for a txid that just verified are superseded, not pending. + self.pending_instantlocks + .retain(|pending| !validated_txids.contains(&pending.instant_lock.txid)); + if rejected > 0 { + tracing::warn!( + "Dropped {} pending InstantLocks refuted by their complete cycle", + rejected + ); + self.progress.add_invalid(rejected); + } self.last_validated_engine_height = engine_height; self.progress.update_pending(self.pending_instantlocks.len()); Ok(events) @@ -295,11 +304,8 @@ impl InstantSendManager { /// Drop cached InstantLock entries that were never BLS-validated, and clear /// the queued locks that fed them. /// - /// Called on disconnect. The `instantlocks` cache is what - /// [`process_instantlock`](Self::process_instantlock) dedupes against, so if - /// an unvalidated entry survived a disconnect the same lock re-announced - /// after reconnect would be treated as a duplicate and never re-queued or - /// re-validated. Validated entries are kept — their locks are already final. + /// Called on disconnect, so a lock re-announced after reconnect is processed + /// fresh. Validated entries are kept — their locks are already final. pub(super) fn clear_unvalidated_on_disconnect(&mut self) { self.pending_instantlocks.clear(); self.instantlocks.retain(|_, entry| entry.validated); @@ -365,7 +371,7 @@ impl std::fmt::Debug for InstantSendManager { mod tests { use super::*; use crate::network::{MessageType, NetworkManager}; - use crate::sml_engine::test_support::TestEngine; + use crate::sml_engine::test_support::{mainnet_fixture_is_lock, TestEngine}; use crate::sync::{ManagerIdentifier, SyncManager, SyncManagerProgress, SyncState}; use crate::test_utils::MockHeaderStorage; use dashcore::bls_sig_utils::BLSSignature; @@ -510,10 +516,9 @@ mod tests { async fn should_accept_genuine_lock_after_forged_lock_for_same_txid() { let engine = TestEngine::mainnet_fixture(); let mut manager = InstantSendManager::new(Arc::new(RwLock::new(engine))); - // An IS lock of the mainnet fixture's cycle, signed by its quorum at index 23. - let genuine: InstantLock = dashcore::consensus::deserialize(&hex_conservative::decode_to_vec("01018d53e7997ead57409750942af0d5e0aafc06f852a9a52308f4781b6a8220298f00000000c6f9d8c63dd15937ea70aaddb7890daad42c91bf6818e2bf76d183d6f2d9215b4b5f84978fad9dde7ab52bdcc0674be891e9029cc1ef0cb01200000000000000a27c98836c4c04653ab81eb4e07ddfc2c8c2c1036b75247969c05a4f25451cd78913a971f1899d9f2bddec9cf8e0104004f72f20c2856453e5aa3bcd2a8200670ec28feda38f67cc400fc72ef1966956656ec0765478c9d16e9a9e470c07f9ed").unwrap()).unwrap(); + let genuine = mainnet_fixture_is_lock(); let mut forged = genuine.clone(); - forged.signature = BLSSignature::from([1u8; 96]); + forged.cyclehash = CycleHash::from_byte_array([7; 32]); let events = manager.process_instantlock(&forged).await.unwrap(); assert!(matches!( @@ -533,6 +538,66 @@ mod tests { ), "genuine lock was shadowed by the forged one: {events:?}" ); + assert_eq!(manager.pending_count(), 0, "the forged lock no longer awaits quorum data"); + assert!(manager.process_instantlock(&genuine).await.unwrap().is_empty()); + assert!(manager.process_instantlock(&forged).await.unwrap().is_empty()); + } + + /// A lock its complete, verified cycle refutes is rejected, not kept pending. + #[tokio::test] + async fn should_reject_lock_refuted_by_its_complete_cycle() { + let engine = TestEngine::mainnet_fixture(); + let mut manager = InstantSendManager::new(Arc::new(RwLock::new(engine))); + let genuine = mainnet_fixture_is_lock(); + let mut forged = genuine.clone(); + forged.signature = BLSSignature::from([1; 96]); + + assert!(manager.process_instantlock(&forged).await.unwrap().is_empty()); + assert_eq!(manager.pending_count(), 0); + assert!(manager.instantlocks.is_empty(), "a rejected lock is not cached"); + assert_eq!(manager.progress.invalid(), 1); + + let events = manager.process_instantlock(&genuine).await.unwrap(); + assert!(matches!( + events.as_slice(), + [SyncEvent::InstantLockReceived { + validated: true, + .. + }] + )); + } + + /// Once one lock for a txid verifies, its other pending locks never emit. + #[tokio::test] + async fn should_drop_other_pending_locks_of_a_txid_once_one_verifies() { + let mut manager = InstantSendManager::new(Arc::new(RwLock::new(TestEngine::empty( + dashcore::Network::Mainnet, + )))); + let genuine = mainnet_fixture_is_lock(); + let mut other_cycle = genuine.clone(); + other_cycle.cyclehash = CycleHash::from_byte_array([7; 32]); + for lock in [&other_cycle, &genuine] { + let events = manager.process_instantlock(lock).await.unwrap(); + assert!(matches!( + events.as_slice(), + [SyncEvent::InstantLockReceived { + validated: false, + .. + }] + )); + } + assert_eq!(manager.pending_count(), 2); + + *manager.engine.write().await = TestEngine::mainnet_fixture(); + let events = manager.validate_pending(Instant::now()).await.unwrap(); + assert!(matches!( + events.as_slice(), + [SyncEvent::InstantLockReceived { instant_lock, validated: true }] + if instant_lock == &genuine + )); + assert_eq!(manager.pending_count(), 0); + assert!(manager.validate_pending(Instant::now()).await.unwrap().is_empty()); + assert!(manager.process_instantlock(&other_cycle).await.unwrap().is_empty()); } #[tokio::test] diff --git a/dash-spv/src/test_utils/instant_lock.rs b/dash-spv/src/test_utils/instant_lock.rs index 4d69fb539..b39e811b7 100644 --- a/dash-spv/src/test_utils/instant_lock.rs +++ b/dash-spv/src/test_utils/instant_lock.rs @@ -2,14 +2,13 @@ use std::collections::BTreeMap; -use dash_pkc::bls::{BlsError, BlsScIetf, BlsSecretKey}; -use dashcore::bls_sig_utils::{BLSPublicKey, BLSSignature}; +use dashcore::bls_sig_utils::{BLSPublicKey, BLSSignature, BlsError, BlsScheme, BlsSkBytes}; use dashcore::hash_types::QuorumVVecHash; use dashcore::sml::llmq_entry_verification::LLMQEntryVerificationStatus; -use dashcore::sml::llmq_type::LLMQType; +use dashcore::sml::llmq_type::network::NetworkLLMQExt; use dashcore::sml::quorum_entry::qualified_quorum_entry::QualifiedQuorumEntry; use dashcore::transaction::special_transaction::quorum_commitment::QuorumEntry; -use dashcore::{BlockHash, InstantLock, QuorumHash, Transaction}; +use dashcore::{BlockHash, InstantLock, Network, QuorumHash, Transaction}; use key_wallet_manager::WalletInterface; use crate::client::DashSpvClient; @@ -19,7 +18,7 @@ use crate::network::NetworkManager; /// Failure to build a deterministic signed test fixture. #[derive(Debug, thiserror::Error)] pub enum InstantLockFixtureError { - /// The fixture key could not be constructed. + /// The fixture key could not sign. #[error("invalid fixture BLS key: {0}")] Key(#[from] BlsError), /// The lock signing digest could not be encoded. @@ -27,10 +26,10 @@ pub enum InstantLockFixtureError { Encoding(#[from] std::io::Error), } -/// A signed lock and synthetic quorum for isolated tests, never a network proof. +/// A lock signed by a constant, public test key, and a synthetic quorum cycle for it. /// -/// Install into a temporary test client's engine, then call the client's public -/// `verify_instant_lock` query. This fixture cannot construct a verified token. +/// `install` makes every lock signed by that key verify on the client it is installed +/// into, so use it only on throwaway test clients. It is never a network proof. #[derive(Debug, Clone)] pub struct InstantLockFixture { instant_lock: InstantLock, @@ -38,10 +37,15 @@ pub struct InstantLockFixture { } impl InstantLockFixture { - /// Signs the transaction's ID and ordered inputs using a deterministic test key. - pub fn new(transaction: &Transaction) -> Result { - let key = BlsSecretKey::::from_bytes(&[1; 32])?; - let llmq_type = LLMQType::LlmqtypeTestDIP0024; + /// Signs the transaction's ID and ordered inputs with a quorum of `network`'s + /// InstantSend quorum type. + pub fn new( + network: Network, + transaction: &Transaction, + ) -> Result { + let secret = BlsSkBytes::from_bytes([1; 32]); + let key = secret.as_scheme(BlsScheme::Modern); + let llmq_type = network.isd_llmq_type(); let quorum_hash = QuorumHash::from_byte_array([9; 32]); let mut instant_lock = InstantLock { version: 1, @@ -51,8 +55,8 @@ impl InstantLockFixture { signature: BLSSignature::from([0; 96]), }; let digest = instant_lock.sign_id(llmq_type, quorum_hash, None)?; - instant_lock.signature = - BLSSignature::from(key.sign_digest(digest.as_byte_array()).to_bytes()); + instant_lock.signature = key.sign_digest(digest.as_byte_array())?; + let quorum_public_key = BLSPublicKey::from(key.public_key()?); let quorums = (0..llmq_type.active_quorum_count() as u16) .map(|index| { let entry = QuorumEntry { @@ -62,7 +66,7 @@ impl InstantLockFixture { quorum_index: Some(index as i16), signers: vec![true; 4], valid_members: vec![true; 4], - quorum_public_key: BLSPublicKey::from(key.public_key().to_bytes()), + quorum_public_key, quorum_vvec_hash: QuorumVVecHash::all_zeros(), threshold_sig: instant_lock.signature, all_commitment_aggregated_signature: instant_lock.signature, @@ -89,7 +93,7 @@ impl InstantLockFixture { &self.instant_lock } - /// Installs this synthetic quorum into an isolated test client's engine. + /// Installs this synthetic quorum cycle into the client's engine. pub async fn install( &self, client: &DashSpvClient, diff --git a/dash-spv/src/validation/instantlock.rs b/dash-spv/src/validation/instantlock.rs index f99c28084..65337362f 100644 --- a/dash-spv/src/validation/instantlock.rs +++ b/dash-spv/src/validation/instantlock.rs @@ -62,6 +62,10 @@ impl VerifiedInstantLock { .eq(transaction.input.iter().map(|input| input.previous_output)) } + /// Authenticates a lock, or returns `None` while the engine lacks the quorum data to decide. + /// + /// Fails for a malformed lock, or one whose signature a complete, verified cycle of + /// the network's InstantSend quorum type refutes. pub(crate) fn verify( instant_lock: &InstantLock, engine: Option<&MasternodeListEngine>, @@ -75,22 +79,25 @@ impl VerifiedInstantLock { let Some(quorums) = engine.rotated_quorums_of_cycle(&instant_lock.cyclehash) else { return Ok(None); }; - if quorums.values().any(|quorum| quorum.verified != LLMQEntryVerificationStatus::Verified) { + if quorums.values().any(|quorum| { + quorum.verified != LLMQEntryVerificationStatus::Verified + || !engine.signs_instant_locks(quorum.quorum_entry.llmq_type) + }) { return Ok(None); } - let validator = InstantLockValidator::new(quorums); - if matches!( - validator.signing_quorum(instant_lock), - Err(MessageVerificationError::CycleHashNotPresent(_) - | MessageVerificationError::QuorumIndexNotFound(..)) - ) { - return Ok(None); + match InstantLockValidator::new(quorums).validate_signature(instant_lock) { + Ok(()) => Ok(Some(Self { + instant_lock: instant_lock.clone(), + network: engine.network(), + })), + Err( + MessageVerificationError::CycleHashNotPresent(_) + | MessageVerificationError::QuorumIndexNotFound(..), + ) => Ok(None), + // A later QRInfo can still replace the quorums of a partial cycle. + Err(_) if !engine.is_cycle_fully_verified(&instant_lock.cyclehash) => Ok(None), + Err(e) => Err(InstantLockVerificationError::InvalidSignature(signature_error(e))), } - validator.validate(instant_lock).map_err(InstantLockVerificationError::InvalidSignature)?; - Ok(Some(Self { - instant_lock: instant_lock.clone(), - network: engine.network(), - })) } } @@ -146,14 +153,16 @@ pub struct InstantLockValidator<'a> { impl Validator<&InstantLock> for InstantLockValidator<'_> { fn validate(&self, instant_lock: &InstantLock) -> ValidationResult<()> { - self.validate_signature(instant_lock).map_err(|e| { - ValidationError::InvalidSignature(format!( - "InstantLock BLS signature verification failed: {e}" - )) - }) + self.validate_signature(instant_lock).map_err(signature_error) } } +fn signature_error(error: MessageVerificationError) -> ValidationError { + ValidationError::InvalidSignature(format!( + "InstantLock BLS signature verification failed: {error}" + )) +} + impl<'a> InstantLockValidator<'a> { pub fn new(cycle_quorums: &'a BTreeMap) -> Self { Self { @@ -207,11 +216,11 @@ impl<'a> InstantLockValidator<'a> { BlsScheme::Modern, ); match &result { - Ok(()) => tracing::info!( + Ok(()) => tracing::trace!( "IS lock {} verified by quorum {quorum_hash} (index {quorum_index})", instant_lock.txid ), - Err(e) => tracing::warn!( + Err(e) => tracing::debug!( "IS lock {} failed against quorum {quorum_hash} (index {quorum_index}): {e}", instant_lock.txid ), @@ -223,22 +232,16 @@ impl<'a> InstantLockValidator<'a> { #[cfg(test)] mod tests { use super::*; - use crate::sml_engine::test_support::TestEngine; - use dashcore::consensus::deserialize; + use crate::sml_engine::test_support::{mainnet_fixture_is_lock, TestEngine}; use dashcore::sml::llmq_type::LLMQType; use dashcore::QuorumHash; use hex_conservative::DisplayHex; use test_case::test_case; - /// An IS lock of the mainnet fixture's cycle, signed by its quorum at index 23. - fn fixture_is_lock() -> InstantLock { - deserialize(&hex_conservative::decode_to_vec("01018d53e7997ead57409750942af0d5e0aafc06f852a9a52308f4781b6a8220298f00000000c6f9d8c63dd15937ea70aaddb7890daad42c91bf6818e2bf76d183d6f2d9215b4b5f84978fad9dde7ab52bdcc0674be891e9029cc1ef0cb01200000000000000a27c98836c4c04653ab81eb4e07ddfc2c8c2c1036b75247969c05a4f25451cd78913a971f1899d9f2bddec9cf8e0104004f72f20c2856453e5aa3bcd2a8200670ec28feda38f67cc400fc72ef1966956656ec0765478c9d16e9a9e470c07f9ed").unwrap()).unwrap() - } - #[test] fn should_authenticate_stored_lock_only_with_available_cycle() { let engine = TestEngine::mainnet_fixture(); - let lock = fixture_is_lock(); + let lock = mainnet_fixture_is_lock(); assert!(VerifiedInstantLock::verify::(&lock, None,) .unwrap() .is_none()); @@ -295,7 +298,7 @@ mod tests { special_transaction_payload: None, }; // This unit tests binding only; authentication is exercised with the signed fixture. - let mut lock = fixture_is_lock(); + let mut lock = mainnet_fixture_is_lock(); lock.txid = transaction.txid(); lock.inputs = transaction.input.iter().map(|input| input.previous_output).collect(); let verified = VerifiedInstantLock { @@ -333,7 +336,7 @@ mod tests { #[test] fn a_lock_verifies_against_the_quorum_its_request_id_selects() { let engine = TestEngine::mainnet_fixture(); - let lock = fixture_is_lock(); + let lock = mainnet_fixture_is_lock(); let validator = InstantLockValidator::new(engine.rotated_quorums_of_cycle(&lock.cyclehash).unwrap()); diff --git a/dash-spv/src/validation/mod.rs b/dash-spv/src/validation/mod.rs index 2984ec543..803873ef1 100644 --- a/dash-spv/src/validation/mod.rs +++ b/dash-spv/src/validation/mod.rs @@ -11,10 +11,7 @@ pub use block::BlockValidator; pub use chainlock::ChainLockValidator; pub use filter::{FilterValidationInput, FilterValidator}; pub use header::BlockHeaderValidator; -pub use instantlock::{ - InstantLockStructureValidator, InstantLockValidator, InstantLockVerificationError, - VerifiedInstantLock, -}; +pub use instantlock::{InstantLockVerificationError, VerifiedInstantLock}; pub use masternode_list::MasternodeListValidator; use crate::error::ValidationResult; diff --git a/dash-spv/tests/instant_lock_evidence.rs b/dash-spv/tests/instant_lock_evidence.rs index e10b8b1b7..9a9906c67 100644 --- a/dash-spv/tests/instant_lock_evidence.rs +++ b/dash-spv/tests/instant_lock_evidence.rs @@ -2,79 +2,63 @@ use dash_spv::test_utils::{InstantLockFixture, MockNetworkManager}; use dash_spv::{ClientConfig, DashSpvClient, InstantLockVerificationError, VerifiedInstantLock}; -use dashcore::{InstantLock, Network}; -use dashcore::{OutPoint, ScriptBuf, Transaction, TxIn, TxOut, Txid}; +use dashcore::bls_sig_utils::BLSSignature; +use dashcore::{InstantLock, Network, OutPoint, Transaction, TxIn, Txid}; use key_wallet_manager::test_utils::MockWallet; use std::sync::Arc; use tempfile::TempDir; use tokio::sync::RwLock; -#[tokio::test] -async fn should_verify_instant_lock_after_cycle_arrives_without_wallet_arithmetic() { +type TestClient = DashSpvClient; + +/// A client built from `config`, storing into a directory that lives as long as it. +async fn client(config: ClientConfig) -> (TestClient, Arc>, TempDir) { let directory = TempDir::new().unwrap(); - let config = ClientConfig::mainnet().without_filters().with_storage_path(directory.path()); let wallet = Arc::new(RwLock::new(MockWallet::new())); + let config = config.without_filters().with_storage_path(directory.path()); let client = DashSpvClient::new(config, MockNetworkManager::new(), wallet.clone(), vec![]) .await .unwrap(); - let transaction = Transaction { - version: 1, - lock_time: 0, - input: vec![TxIn { - previous_output: OutPoint::new(Txid::from_byte_array([3; 32]), 0), - ..Default::default() - }], - output: vec![ - TxOut { - value: u64::MAX, - script_pubkey: ScriptBuf::new() - }; - 2 - ], - special_transaction_payload: None, - }; - let fixture = InstantLockFixture::new(&transaction).unwrap(); + (client, wallet, directory) +} + +fn spend() -> Transaction { + let mut transaction = Transaction::dummy_empty(); + transaction.input.push(TxIn { + previous_output: OutPoint::new(Txid::from_byte_array([3; 32]), 0), + ..Default::default() + }); + transaction +} + +fn with_wrong_signature(lock: &InstantLock) -> InstantLock { + InstantLock { + signature: BLSSignature::from([1; 96]), + ..lock.clone() + } +} + +#[tokio::test] +async fn should_verify_instant_lock_after_cycle_arrives_without_wallet_arithmetic() { + let (client, wallet, _directory) = client(ClientConfig::mainnet()).await; + let transaction = spend(); + let fixture = InstantLockFixture::new(Network::Mainnet, &transaction).unwrap(); let lock = fixture.instant_lock(); assert!(client.verify_instant_lock(lock).await.unwrap().is_none()); fixture.install(&client).await.unwrap(); let proof: VerifiedInstantLock = client.verify_instant_lock(lock).await.unwrap().unwrap(); assert!(proof.matches_transaction(&transaction)); assert_eq!(proof.instant_lock(), lock); - assert_eq!(proof.txid(), transaction.txid()); assert!(wallet.read().await.processed_instant_locks.lock().await.is_empty()); - - let mut changed_body = transaction.clone(); - changed_body.output[0].value -= 1; - assert!(!proof.matches_transaction(&changed_body)); - let mut wrong_txid = lock.clone(); - wrong_txid.txid = changed_body.txid(); - let mut wrong_input = lock.clone(); - wrong_input.inputs[0].vout += 1; - let mut wrong_signature = lock.clone(); - wrong_signature.signature = dashcore::bls_sig_utils::BLSSignature::from([1; 96]); - for invalid in [wrong_txid, wrong_input, wrong_signature] { - assert!(matches!( - client.verify_instant_lock(&invalid).await, - Err(InstantLockVerificationError::InvalidSignature(_)) - )); - } + assert!(matches!( + client.verify_instant_lock(&with_wrong_signature(lock)).await, + Err(InstantLockVerificationError::InvalidSignature(_)) + )); } #[tokio::test] async fn should_defer_instant_lock_when_masternodes_are_disabled() { - let directory = TempDir::new().unwrap(); - let config = ClientConfig::mainnet() - .without_filters() - .without_masternodes() - .with_storage_path(directory.path()); - let client = DashSpvClient::new( - config, - MockNetworkManager::new(), - Arc::new(RwLock::new(MockWallet::new())), - vec![], - ) - .await - .unwrap(); + let (client, _wallet, _directory) = client(ClientConfig::mainnet().without_masternodes()).await; assert!(client.verify_instant_lock(&InstantLock::dummy(0..1)).await.unwrap().is_none()); assert!(matches!( client.verify_instant_lock(&InstantLock::default()).await, @@ -84,30 +68,12 @@ async fn should_defer_instant_lock_when_masternodes_are_disabled() { #[tokio::test] async fn should_defer_instant_lock_until_selected_quorum_arrives() { - let directory = TempDir::new().unwrap(); - let config = ClientConfig::mainnet().without_filters().with_storage_path(directory.path()); - let client = DashSpvClient::new( - config, - MockNetworkManager::new(), - Arc::new(RwLock::new(MockWallet::new())), - vec![], - ) - .await - .unwrap(); - let transaction = Transaction { - version: 1, - lock_time: 0, - input: vec![TxIn { - previous_output: OutPoint::new(Txid::from_byte_array([3; 32]), 0), - ..Default::default() - }], - output: vec![], - special_transaction_payload: None, - }; - let fixture = InstantLockFixture::new(&transaction).unwrap(); + // Regtest's InstantSend quorum type has two active slots; exactly one signs this lock. + let (client, _wallet, _directory) = client(ClientConfig::regtest()).await; + let transaction = spend(); + let fixture = InstantLockFixture::new(Network::Regtest, &transaction).unwrap(); let lock = fixture.instant_lock(); let mut missing = 0; - // The test quorum type has two active slots; exactly one signs this lock. for index in 0..2 { fixture.clone().without_quorum(index).install(&client).await.unwrap(); match client.verify_instant_lock(lock).await { @@ -115,53 +81,34 @@ async fn should_defer_instant_lock_until_selected_quorum_arrives() { Ok(Some(proof)) => assert!(proof.matches_transaction(&transaction)), Err(error) => panic!("incomplete quorum data is unavailable, not invalid: {error}"), } + assert!( + client.verify_instant_lock(&with_wrong_signature(lock)).await.unwrap().is_none(), + "a partial cycle cannot refute a lock" + ); } assert_eq!(missing, 1); fixture.clone().without_quorum(0).without_quorum(1).install(&client).await.unwrap(); assert!(client.verify_instant_lock(lock).await.unwrap().is_none()); fixture.install(&client).await.unwrap(); - assert!(client - .verify_instant_lock(lock) - .await - .unwrap() - .unwrap() - .matches_transaction(&transaction)); + assert!(client.verify_instant_lock(lock).await.unwrap().is_some()); } #[tokio::test] async fn should_bind_instant_lock_evidence_to_the_verifying_network() { - let transaction = Transaction { - version: 1, - lock_time: 0, - input: vec![TxIn { - previous_output: OutPoint::new(Txid::from_byte_array([3; 32]), 0), - ..Default::default() - }], - output: vec![], - special_transaction_payload: None, - }; - let fixture = InstantLockFixture::new(&transaction).unwrap(); + let transaction = spend(); for network in [Network::Mainnet, Network::Testnet] { - let directory = TempDir::new().unwrap(); - let config = - ClientConfig::new(network).without_filters().with_storage_path(directory.path()); - let client = DashSpvClient::new( - config, - MockNetworkManager::new(), - Arc::new(RwLock::new(MockWallet::new())), - vec![], - ) - .await - .unwrap(); + let (client, _wallet, _directory) = client(ClientConfig::new(network)).await; + let fixture = InstantLockFixture::new(network, &transaction).unwrap(); fixture.install(&client).await.unwrap(); let proof = client.verify_instant_lock(fixture.instant_lock()).await.unwrap().unwrap(); - assert!(proof.matches_transaction(&transaction)); assert_eq!(proof.network(), network); - let other_network = if network == Network::Mainnet { - Network::Testnet - } else { - Network::Mainnet - }; - assert_ne!(proof.network(), other_network); } } + +#[tokio::test] +async fn should_not_verify_lock_of_another_instant_send_quorum_type() { + let (client, _wallet, _directory) = client(ClientConfig::mainnet()).await; + let fixture = InstantLockFixture::new(Network::Regtest, &spend()).unwrap(); + fixture.install(&client).await.unwrap(); + assert!(client.verify_instant_lock(fixture.instant_lock()).await.unwrap().is_none()); +} From 6770c57bbece5bcfc5301008588bef2506170b4f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:23:14 +0000 Subject: [PATCH 09/38] test(dash-spv): assert the mempool's InstantLock contract exactly `should_ignore_unverified_instant_lock` now checks the exact broadcast acceptance event, the removal of the broadcast and the lock handed to the wallet, and reuses the module's transaction and lock helpers. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sync/mempool/manager.rs | 60 ++++++++++------------------ 1 file changed, 21 insertions(+), 39 deletions(-) diff --git a/dash-spv/src/sync/mempool/manager.rs b/dash-spv/src/sync/mempool/manager.rs index b90a13816..92294c878 100644 --- a/dash-spv/src/sync/mempool/manager.rs +++ b/dash-spv/src/sync/mempool/manager.rs @@ -1368,26 +1368,13 @@ mod tests { async fn should_ignore_unverified_instant_lock(known: bool, uncertain: bool) { use crate::sync::SyncManager; let (mut manager, requests, _rx) = create_test_manager(); - let tx = dashcore::Transaction { - version: 1, - lock_time: 0, - input: vec![], - output: vec![], - special_transaction_payload: None, - }; + let tx = test_transaction(1); let txid = tx.txid(); assert!(manager.start_broadcast(&tx, &requests).await.is_empty()); if known { manager.transactions.insert( txid, - crate::types::UnconfirmedTransaction::new( - tx.clone(), - dashcore::Amount::from_sat(0), - false, - false, - Vec::new(), - 0, - ), + UnconfirmedTransaction::new(tx, Amount::from_sat(0), false, false, Vec::new(), 0), ); } let status = if uncertain { @@ -1396,40 +1383,35 @@ mod tests { BroadcastStatus::Pending }; manager.broadcasts.get_mut(&txid).unwrap().status = status; - let mut lock = dashcore::InstantLock::dummy(0..1); - lock.txid = txid; - let events = manager - .handle_sync_event( - &SyncEvent::InstantLockReceived { - instant_lock: lock.clone(), - validated: false, - }, - &requests, - ) - .await - .unwrap(); + let lock = dummy_instant_lock(txid); + let received = |validated| SyncEvent::InstantLockReceived { + instant_lock: lock.clone(), + validated, + }; + + let events = manager.handle_sync_event(&received(false), &requests).await.unwrap(); assert!(events.is_empty(), "unverified locks cannot accept broadcasts"); assert_eq!(manager.broadcasts.get(&txid).unwrap().status, status); assert!(manager.pending_is_locks.is_empty()); assert!(!manager.transactions.get(&txid).is_some_and(|tx| tx.is_instant_send)); assert!(manager.wallet.read().await.processed_instant_locks.lock().await.is_empty()); - let events = manager - .handle_sync_event( - &SyncEvent::InstantLockReceived { - instant_lock: lock.clone(), - validated: true, - }, - &requests, - ) - .await - .unwrap(); - assert_eq!(events.len(), 1, "later verification must still accept the broadcast"); + let events = manager.handle_sync_event(&received(true), &requests).await.unwrap(); + assert!(matches!( + events.as_slice(), + [SyncEvent::TransactionBroadcastResult { + txid: accepted, + result: BroadcastResult::Accepted { .. }, + }] if *accepted == txid + )); + assert!(!manager.broadcasts.contains_key(&txid)); + let processed = manager.wallet.read().await.processed_instant_locks.lock().await.clone(); if known { assert!(manager.transactions.get(&txid).unwrap().is_instant_send); - assert!(!manager.wallet.read().await.processed_instant_locks.lock().await.is_empty()); + assert_eq!(processed, vec![(txid, Some(lock))]); } else { assert_eq!(manager.pending_is_locks.get(&txid).unwrap().0, lock); + assert!(processed.is_empty()); } } From fc7c703bb2378d9357bb8da02ee2221784201986 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:23:14 +0000 Subject: [PATCH 10/38] test(key-wallet): authorize what the wallet signer produces Adds a round trip through `TransactionSigner::sign_tx` to the `verify_input_authorization` tests, and reads the P2PKH key hash with `Script::p2pkh_public_key_hash_bytes` instead of slicing the script. Co-Authored-By: Claude Opus 5.5 --- .../spend_authorization.rs | 33 ++++++++++++++++--- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/key-wallet/src/transaction_checking/spend_authorization.rs b/key-wallet/src/transaction_checking/spend_authorization.rs index d2daa0ecc..41ae93455 100644 --- a/key-wallet/src/transaction_checking/spend_authorization.rs +++ b/key-wallet/src/transaction_checking/spend_authorization.rs @@ -44,9 +44,9 @@ pub fn verify_input_authorization( { return Ok(false); } - if !prevout.script_pubkey.is_p2pkh() { + 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()) @@ -57,9 +57,7 @@ pub fn verify_input_authorization( return Ok(false); } let public_key_bytes = public_key.as_bytes(); - if hash160::Hash::hash(public_key_bytes).as_byte_array().as_slice() - != &prevout.script_pubkey.as_bytes()[3..23] - { + 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 { @@ -95,6 +93,9 @@ pub fn verify_input_authorization( #[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, }; @@ -159,6 +160,28 @@ mod tests { } } + #[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); From c90478da900ae5ed875ee53156af7b489c3d86e6 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:29:24 +0000 Subject: [PATCH 11/38] docs(dash-spv): document the InstantLockReceived validation contract State that an unverified lock is deferred rather than final, may repeat per txid, that refuted locks emit nothing, and that the mempool acts only on validated locks. Co-Authored-By: Claude Opus 5.5 --- dash-spv/ARCHITECTURE.md | 2 +- dash-spv/src/sync/events.rs | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/dash-spv/ARCHITECTURE.md b/dash-spv/ARCHITECTURE.md index 05ee3c2d1..efaf6d7bd 100644 --- a/dash-spv/ARCHITECTURE.md +++ b/dash-spv/ARCHITECTURE.md @@ -1174,7 +1174,7 @@ The `seen_txids` map provides a 180-second deduplication window to handle the ca |-------|--------| | `SyncComplete` | Activate mempool relay on all connected peers (transitions to `Synced`) | | `BlockProcessed` | Remove confirmed txids from mempool state; immediately rebuild bloom filter if new addresses | -| `InstantLockReceived` | Mark transaction as IS-locked, or store in pending_is_locks if TX not yet received | +| `InstantLockReceived` | Only `validated: true`: mark transaction as IS-locked, or store in pending_is_locks if TX not yet received; unverified locks are ignored | | `PeerConnected` | Activate on new peer immediately if already synced | | `PeerDisconnected` | Remove peer; redistribute its queued txids to a random activated peer | | `PeersUpdated` with no addresses | All peers lost: call `stop_sync()`, transition to `WaitingForConnections` | diff --git a/dash-spv/src/sync/events.rs b/dash-spv/src/sync/events.rs index 5a04b67d6..3ab84ce8f 100644 --- a/dash-spv/src/sync/events.rs +++ b/dash-spv/src/sync/events.rs @@ -154,12 +154,16 @@ pub enum SyncEvent { /// InstantSend lock received and processed. /// + /// `validated: false` means verification is deferred until quorum data + /// arrives: it is never final and may repeat for distinct locks of one txid. + /// Locks refuted by a complete, verified cycle emit no event. + /// /// Emitted by: `InstantSendManager` - /// Consumed by: External listeners, mempool state updates + /// Consumed by: External listeners, mempool state updates (validated locks only) InstantLockReceived { /// The complete InstantLock data instant_lock: InstantLock, - /// Whether the BLS signature was validated + /// Whether the BLS signature was verified against its signing quorum validated: bool, }, From 0d4a6a8ed55577989715c7394c7ac1df1ab23b40 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:32:18 +0000 Subject: [PATCH 12/38] fix(dash-spv): bind verified InstantLock evidence to the wallet network `VerifiedInstantLock::matches_transaction` now takes the receiving wallet's network and checks it together with the txid and ordered inputs, so consumers cannot accept cross-network evidence by forgetting a separate `network()` comparison. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/validation/instantlock.rs | 15 ++++++++------- dash-spv/tests/instant_lock_evidence.rs | 8 ++++++-- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/dash-spv/src/validation/instantlock.rs b/dash-spv/src/validation/instantlock.rs index 65337362f..0d6c9b4ce 100644 --- a/dash-spv/src/validation/instantlock.rs +++ b/dash-spv/src/validation/instantlock.rs @@ -48,12 +48,12 @@ impl VerifiedInstantLock { self.instant_lock.txid } - /// Binds the evidence to the complete transaction and its ordered inputs. + /// Binds the evidence to the wallet's network, the complete transaction and its ordered inputs. /// /// No wallet arithmetic or transaction consensus validation is performed. - /// Consumers must also match `network()` to the wallet receiving the evidence. - pub fn matches_transaction(&self, transaction: &Transaction) -> bool { - self.txid() == transaction.txid() + pub fn matches_transaction(&self, network: Network, transaction: &Transaction) -> bool { + self.network == network + && self.txid() == transaction.txid() && self .instant_lock .inputs @@ -305,13 +305,14 @@ mod tests { instant_lock: lock, network: Network::Mainnet, }; - assert!(verified.matches_transaction(&transaction)); + assert!(verified.matches_transaction(Network::Mainnet, &transaction)); + assert!(!verified.matches_transaction(Network::Testnet, &transaction)); let mut changed = transaction.clone(); changed.output[0].value -= 1; - assert!(!verified.matches_transaction(&changed)); + assert!(!verified.matches_transaction(Network::Mainnet, &changed)); let mut wrong_inputs = verified.clone(); wrong_inputs.instant_lock.inputs[0].vout += 1; - assert!(!wrong_inputs.matches_transaction(&transaction)); + assert!(!wrong_inputs.matches_transaction(Network::Mainnet, &transaction)); } #[test] diff --git a/dash-spv/tests/instant_lock_evidence.rs b/dash-spv/tests/instant_lock_evidence.rs index 9a9906c67..28fe002aa 100644 --- a/dash-spv/tests/instant_lock_evidence.rs +++ b/dash-spv/tests/instant_lock_evidence.rs @@ -47,7 +47,7 @@ async fn should_verify_instant_lock_after_cycle_arrives_without_wallet_arithmeti assert!(client.verify_instant_lock(lock).await.unwrap().is_none()); fixture.install(&client).await.unwrap(); let proof: VerifiedInstantLock = client.verify_instant_lock(lock).await.unwrap().unwrap(); - assert!(proof.matches_transaction(&transaction)); + assert!(proof.matches_transaction(Network::Mainnet, &transaction)); assert_eq!(proof.instant_lock(), lock); assert!(wallet.read().await.processed_instant_locks.lock().await.is_empty()); assert!(matches!( @@ -78,7 +78,7 @@ async fn should_defer_instant_lock_until_selected_quorum_arrives() { fixture.clone().without_quorum(index).install(&client).await.unwrap(); match client.verify_instant_lock(lock).await { Ok(None) => missing += 1, - Ok(Some(proof)) => assert!(proof.matches_transaction(&transaction)), + Ok(Some(proof)) => assert!(proof.matches_transaction(Network::Regtest, &transaction)), Err(error) => panic!("incomplete quorum data is unavailable, not invalid: {error}"), } assert!( @@ -102,6 +102,10 @@ async fn should_bind_instant_lock_evidence_to_the_verifying_network() { fixture.install(&client).await.unwrap(); let proof = client.verify_instant_lock(fixture.instant_lock()).await.unwrap().unwrap(); assert_eq!(proof.network(), network); + assert!(proof.matches_transaction(network, &transaction)); + for other in [Network::Mainnet, Network::Testnet].into_iter().filter(|n| *n != network) { + assert!(!proof.matches_transaction(other, &transaction)); + } } } From 66d3833955a98ce9ecca11e67698264537aa4fbf Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:01:25 +0000 Subject: [PATCH 13/38] fix(dash-spv): leave Syncing when a verified lock drains the pending queue A lock that verifies on arrival drops the other pending locks of its txid. When that empties the queue, the manager stayed in `Syncing` until the next masternode state update, since the tick only resolves the state for pending work it drained itself. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sync/instantsend/manager.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/dash-spv/src/sync/instantsend/manager.rs b/dash-spv/src/sync/instantsend/manager.rs index af436ee30..baae89de5 100644 --- a/dash-spv/src/sync/instantsend/manager.rs +++ b/dash-spv/src/sync/instantsend/manager.rs @@ -168,7 +168,11 @@ impl InstantSendManager { if validated { self.progress.add_valid(1); + let queued = self.pending_instantlocks.len(); self.pending_instantlocks.retain(|pending| pending.instant_lock.txid != txid); + if self.pending_instantlocks.len() < queued { + self.transition_synced_if_idle(); + } } else { self.queue_pending(PendingInstantLock { instant_lock: instantlock.clone(), @@ -600,6 +604,23 @@ mod tests { assert!(manager.process_instantlock(&other_cycle).await.unwrap().is_empty()); } + #[tokio::test] + async fn should_leave_syncing_when_a_direct_verification_drains_the_pending_queue() { + let mut manager = + InstantSendManager::new(Arc::new(RwLock::new(TestEngine::mainnet_fixture()))); + manager.set_state(SyncState::Syncing); + let genuine = mainnet_fixture_is_lock(); + let mut unknown_cycle = genuine.clone(); + unknown_cycle.cyclehash = CycleHash::from_byte_array([7; 32]); + manager.process_instantlock(&unknown_cycle).await.unwrap(); + assert_eq!(manager.pending_count(), 1); + + manager.process_instantlock(&genuine).await.unwrap(); + + assert_eq!(manager.pending_count(), 0); + assert_eq!(manager.state(), SyncState::Synced); + } + #[tokio::test] async fn test_instantsend_pending_queue() { let mut manager = create_test_manager(); From eeb42f9e4aafbf64159a7e5207520bd44af74001 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:21:06 +0000 Subject: [PATCH 14/38] test(dash-spv): cover refuted and superseded locks on the replay path Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sync/instantsend/manager.rs | 68 ++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/dash-spv/src/sync/instantsend/manager.rs b/dash-spv/src/sync/instantsend/manager.rs index baae89de5..7ac39699f 100644 --- a/dash-spv/src/sync/instantsend/manager.rs +++ b/dash-spv/src/sync/instantsend/manager.rs @@ -604,6 +604,74 @@ mod tests { assert!(manager.process_instantlock(&other_cycle).await.unwrap().is_empty()); } + /// A pending lock refuted once its cycle completes is dropped on replay without + /// an event, and the drained queue lets the manager leave `Syncing`. + #[tokio::test] + async fn should_drop_pending_lock_refuted_once_its_cycle_completes() { + let mut manager = InstantSendManager::new(Arc::new(RwLock::new(TestEngine::empty( + dashcore::Network::Mainnet, + )))); + manager.set_state(SyncState::Syncing); + let genuine = mainnet_fixture_is_lock(); + let mut forged = genuine.clone(); + forged.signature = BLSSignature::from([1; 96]); + let events = manager.process_instantlock(&forged).await.unwrap(); + assert!(matches!( + events.as_slice(), + [SyncEvent::InstantLockReceived { + validated: false, + .. + }] + )); + assert_eq!(manager.pending_count(), 1); + + *manager.engine.write().await = TestEngine::mainnet_fixture(); + let event = SyncEvent::MasternodeStateUpdated { + height: 1, + qr_info_result: None, + }; + let events = manager.handle_sync_event(&event, &no_op_network()).await.unwrap(); + + assert!(events.is_empty(), "a refuted lock emits no event: {events:?}"); + assert_eq!(manager.pending_count(), 0); + assert_eq!(manager.progress.invalid(), 1); + assert_eq!(manager.progress.valid(), 0); + assert_eq!(manager.state(), SyncState::Synced); + let events = manager.process_instantlock(&genuine).await.unwrap(); + assert!(matches!( + events.as_slice(), + [SyncEvent::InstantLockReceived { instant_lock, validated: true }] + if instant_lock == &genuine + )); + } + + /// A lock queued behind the one that verifies for its txid is superseded: + /// it emits nothing and leaves no pending entry. + #[tokio::test] + async fn should_supersede_locks_queued_after_the_verified_lock_of_a_txid() { + let mut manager = InstantSendManager::new(Arc::new(RwLock::new(TestEngine::empty( + dashcore::Network::Mainnet, + )))); + let genuine = mainnet_fixture_is_lock(); + let mut forged = genuine.clone(); + forged.signature = BLSSignature::from([1; 96]); + for lock in [&genuine, &forged] { + manager.process_instantlock(lock).await.unwrap(); + } + assert_eq!(manager.pending_count(), 2); + + *manager.engine.write().await = TestEngine::mainnet_fixture(); + let events = manager.validate_pending(Instant::now()).await.unwrap(); + + assert!(matches!( + events.as_slice(), + [SyncEvent::InstantLockReceived { instant_lock, validated: true }] + if instant_lock == &genuine + )); + assert_eq!(manager.pending_count(), 0); + assert!(manager.process_instantlock(&forged).await.unwrap().is_empty()); + } + #[tokio::test] async fn should_leave_syncing_when_a_direct_verification_drains_the_pending_queue() { let mut manager = From e5387dda659ed33c2b1191c7eb78d3fc3d43bec1 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:45:57 +0000 Subject: [PATCH 15/38] fix(dash-spv): sign `InstantLockFixture` with a random key The fixture signed with the constant secret `[1; 32]`, so a fixture cycle that reached a persisted engine would let anyone forge locks for it. Each fixture now draws its own secret from the thread CSPRNG. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/test_utils/instant_lock.rs | 7 ++++--- dash-spv/tests/instant_lock_evidence.rs | 13 +++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/dash-spv/src/test_utils/instant_lock.rs b/dash-spv/src/test_utils/instant_lock.rs index b39e811b7..bd10bb497 100644 --- a/dash-spv/src/test_utils/instant_lock.rs +++ b/dash-spv/src/test_utils/instant_lock.rs @@ -15,7 +15,7 @@ use crate::client::DashSpvClient; use crate::error::SpvError; use crate::network::NetworkManager; -/// Failure to build a deterministic signed test fixture. +/// Failure to build a signed test fixture. #[derive(Debug, thiserror::Error)] pub enum InstantLockFixtureError { /// The fixture key could not sign. @@ -26,7 +26,7 @@ pub enum InstantLockFixtureError { Encoding(#[from] std::io::Error), } -/// A lock signed by a constant, public test key, and a synthetic quorum cycle for it. +/// A lock signed by a random key of its own, and a synthetic quorum cycle for it. /// /// `install` makes every lock signed by that key verify on the client it is installed /// into, so use it only on throwaway test clients. It is never a network proof. @@ -43,7 +43,8 @@ impl InstantLockFixture { network: Network, transaction: &Transaction, ) -> Result { - let secret = BlsSkBytes::from_bytes([1; 32]); + let secret = + BlsSkBytes::from_bytes(rand::random()).as_scheme(BlsScheme::Modern).canonicalize()?; let key = secret.as_scheme(BlsScheme::Modern); let llmq_type = network.isd_llmq_type(); let quorum_hash = QuorumHash::from_byte_array([9; 32]); diff --git a/dash-spv/tests/instant_lock_evidence.rs b/dash-spv/tests/instant_lock_evidence.rs index 28fe002aa..26ba0fe56 100644 --- a/dash-spv/tests/instant_lock_evidence.rs +++ b/dash-spv/tests/instant_lock_evidence.rs @@ -116,3 +116,16 @@ async fn should_not_verify_lock_of_another_instant_send_quorum_type() { fixture.install(&client).await.unwrap(); assert!(client.verify_instant_lock(fixture.instant_lock()).await.unwrap().is_none()); } + +#[tokio::test] +async fn should_refute_a_lock_signed_by_another_fixture() { + let (client, _wallet, _directory) = client(ClientConfig::mainnet()).await; + let transaction = spend(); + let installed = InstantLockFixture::new(Network::Mainnet, &transaction).unwrap(); + let other = InstantLockFixture::new(Network::Mainnet, &transaction).unwrap(); + installed.install(&client).await.unwrap(); + assert!(matches!( + client.verify_instant_lock(other.instant_lock()).await, + Err(InstantLockVerificationError::InvalidSignature(_)) + )); +} From 5ac610e8835595ed156a704b872b2941d74d0035 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:46:06 +0000 Subject: [PATCH 16/38] refactor(dash-spv): let the engine own InstantLock cycle eligibility `VerifiedInstantLock::verify` re-derived which stored cycle may sign a lock from three engine internals. `MasternodeListEngine::instant_send_cycle` now owns that policy and `verify` only classifies the signature check over its result. A cycle counts as complete only when storage has stopped merging into it: every slot of the configured InstantSend type, all of that type. Mainnet, testnet and regtest behave as before. On a devnet whose cycle has another rotating type, a lock the cycle does not verify is deferred instead of refuted. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sml_engine.rs | 71 ++++++++++++++++++++++++-- dash-spv/src/validation/instantlock.rs | 13 ++--- 2 files changed, 70 insertions(+), 14 deletions(-) diff --git a/dash-spv/src/sml_engine.rs b/dash-spv/src/sml_engine.rs index 3fb6162d6..944542ccd 100644 --- a/dash-spv/src/sml_engine.rs +++ b/dash-spv/src/sml_engine.rs @@ -57,6 +57,15 @@ impl QRInfoFeedResult { } } +/// A stored cycle whose quorums may sign this network's InstantSend locks. +#[derive(Clone, Copy, Debug)] +pub(crate) struct InstantSendCycle<'a> { + /// The cycle's quorums, by quorum index. + pub(crate) quorums: &'a BTreeMap, + /// Whether no later QRInfo can replace the cycle's quorums, so it can refute a lock. + pub(crate) complete: bool, +} + /// Why the engine did not take a diff or a QRInfo. #[derive(Debug, thiserror::Error)] pub enum FeedError { @@ -427,6 +436,29 @@ impl MasternodeListEngine { self.rotated_quorums_per_cycle.get(cycle_hash) } + /// The cycle `cycle_hash` when every quorum of it is verified and of a type that + /// signs this network's InstantSend locks. + pub(crate) fn instant_send_cycle( + &self, + cycle_hash: &BlockHash, + ) -> Option> { + let quorums = self.rotated_quorums_per_cycle.get(cycle_hash)?; + if quorums.values().any(|quorum| { + quorum.verified != LLMQEntryVerificationStatus::Verified + || !self.signs_instant_locks(quorum.quorum_entry.llmq_type) + }) { + return None; + } + // Storage stops merging into a cycle only once it fills every slot of the configured type. + let isd_type = self.network.isd_llmq_type(); + let complete = self.is_cycle_fully_verified(cycle_hash) + && quorums.values().all(|quorum| quorum.quorum_entry.llmq_type == isd_type); + Some(InstantSendCycle { + quorums, + complete, + }) + } + #[cfg(feature = "test-utils")] pub(crate) fn install_test_instant_lock_cycle( &mut self, @@ -705,7 +737,7 @@ impl MasternodeListEngine { /// `true` when the stored cycle has a `Verified` quorum for every active /// slot. A partial cycle stays open so a later QRInfo can complete it. - pub(crate) fn is_cycle_fully_verified(&self, cycle_hash: &BlockHash) -> bool { + fn is_cycle_fully_verified(&self, cycle_hash: &BlockHash) -> bool { let expected = self.network.isd_llmq_type().active_quorum_count() as usize; self.rotated_quorums_per_cycle.get(cycle_hash).is_some_and(|existing| { existing.len() == expected @@ -905,7 +937,7 @@ impl MasternodeListEngine { /// Whether a quorum of `llmq_type` can sign this network's IS locks: the /// configured rotation type, or on a devnet without an override, any rotating type. - pub(crate) fn signs_instant_locks(&self, llmq_type: LLMQType) -> bool { + fn signs_instant_locks(&self, llmq_type: LLMQType) -> bool { if self.reads_served_rotation_type() { return llmq_type.is_rotating_quorum_type(); } @@ -1537,14 +1569,14 @@ pub(crate) mod test_support { #[cfg(test)] mod tests { - use super::test_support::{fixture_heights, quorum_entry, TestEngine}; + use super::test_support::{fixture_heights, mainnet_fixture_is_lock, quorum_entry, TestEngine}; use super::{build_cycle_quorum_map, qr_info_diffs, valid_coinbase_chain_lock}; use super::{FeedError, MasternodeListEngine, QRInfoFeedResult, WORK_DIFF_DEPTH}; use crate::error::{StorageError, StorageResult}; use crate::storage::{BlockHeaderStorage, BlockHeaderTip}; use crate::test_utils::MockHeaderStorage; use crate::types::HashedBlockHeader; - use crate::validation::MasternodeListValidator; + use crate::validation::{MasternodeListValidator, VerifiedInstantLock}; use bincode::{config, decode_from_slice, Decode}; use dashcore::bls_sig_utils::{BLSPublicKey, BLSSignature}; use dashcore::consensus::deserialize; @@ -3456,4 +3488,35 @@ mod tests { restored.coinbase_chain_locks.get(&tip_height) ); } + + /// On a devnet the signing cycle can be of another rotating type than the configured + /// one. Holding as many quorums as the configured type has slots does not complete + /// it, so a lock it does not verify is deferred, not refuted. + #[test] + fn should_defer_lock_on_a_partial_devnet_cycle_of_another_rotating_type() { + // Another test in this binary may set the process-wide override, which pins the type. + if devnet_isd_type_override().is_some() { + return; + } + let lock = mainnet_fixture_is_lock(); + let cycle = + TestEngine::mainnet_fixture().rotated_quorums_per_cycle[&lock.cyclehash].clone(); + let slots = Network::Devnet.isd_llmq_type().active_quorum_count() as usize; + assert!(slots < cycle.len(), "the mainnet cycle has more slots than a devnet one"); + // Index 23 signs the lock; the other kept slots only fill the count. + let mut partial = BTreeMap::from([(23, cycle[&23].clone())]); + for (index, quorum) in cycle { + if partial.len() == slots { + break; + } + partial.insert(index, quorum); + } + let mut engine = TestEngine::empty(Network::Devnet); + engine.rotated_quorums_per_cycle.insert(lock.cyclehash, partial); + + let mut forged = lock.clone(); + forged.signature = BLSSignature::from([1; 96]); + assert!(VerifiedInstantLock::verify(&forged, Some(&engine)).unwrap().is_none()); + assert!(VerifiedInstantLock::verify(&lock, Some(&engine)).unwrap().is_some()); + } } diff --git a/dash-spv/src/validation/instantlock.rs b/dash-spv/src/validation/instantlock.rs index 0d6c9b4ce..5ebe32eb1 100644 --- a/dash-spv/src/validation/instantlock.rs +++ b/dash-spv/src/validation/instantlock.rs @@ -1,7 +1,6 @@ use std::collections::BTreeMap; use dashcore::bls_sig_utils::BlsScheme; -use dashcore::sml::llmq_entry_verification::LLMQEntryVerificationStatus; use dashcore::sml::message_verification_error::MessageVerificationError; use dashcore::sml::quorum_entry::qualified_quorum_entry::QualifiedQuorumEntry; use dashcore::{InstantLock, Network, QuorumSigningRequestId, Transaction, Txid}; @@ -76,16 +75,10 @@ impl VerifiedInstantLock { let Some(engine) = engine else { return Ok(None); }; - let Some(quorums) = engine.rotated_quorums_of_cycle(&instant_lock.cyclehash) else { + let Some(cycle) = engine.instant_send_cycle(&instant_lock.cyclehash) else { return Ok(None); }; - if quorums.values().any(|quorum| { - quorum.verified != LLMQEntryVerificationStatus::Verified - || !engine.signs_instant_locks(quorum.quorum_entry.llmq_type) - }) { - return Ok(None); - } - match InstantLockValidator::new(quorums).validate_signature(instant_lock) { + match InstantLockValidator::new(cycle.quorums).validate_signature(instant_lock) { Ok(()) => Ok(Some(Self { instant_lock: instant_lock.clone(), network: engine.network(), @@ -95,7 +88,7 @@ impl VerifiedInstantLock { | MessageVerificationError::QuorumIndexNotFound(..), ) => Ok(None), // A later QRInfo can still replace the quorums of a partial cycle. - Err(_) if !engine.is_cycle_fully_verified(&instant_lock.cyclehash) => Ok(None), + Err(_) if !cycle.complete => Ok(None), Err(e) => Err(InstantLockVerificationError::InvalidSignature(signature_error(e))), } } From 357029fc4199c37391f4503a910b432ccca00f84 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:46:34 +0000 Subject: [PATCH 17/38] fix(dash-spv): bound InstantLock inputs and dedupe pending locks by hash A peer could send locks of up to ~111k inputs, and each new lock was compared input by input against every pending lock before verification. `InstantLockStructureValidator` now rejects locks with more than `MAX_BLOCK_SIZE / 41` inputs, the cap Dash Core applies in `InstantSendLock::MAX_INPUTS`: a transaction fits in a block and each input takes at least 41 bytes, so no valid lock is rejected. Pending locks are deduplicated by the hash of the serialized lock instead of a deep comparison. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sync/instantsend/manager.rs | 41 +++++++++++++++++------- dash-spv/src/validation/instantlock.rs | 15 +++++++++ 2 files changed, 44 insertions(+), 12 deletions(-) diff --git a/dash-spv/src/sync/instantsend/manager.rs b/dash-spv/src/sync/instantsend/manager.rs index 7ac39699f..bac3a111d 100644 --- a/dash-spv/src/sync/instantsend/manager.rs +++ b/dash-spv/src/sync/instantsend/manager.rs @@ -9,8 +9,11 @@ use std::time::{Duration, Instant, SystemTime}; use crate::sml_engine::MasternodeListEngine; use crate::storage::BlockHeaderStorage; +use dashcore::consensus::encode; use dashcore::ephemerealdata::instant_lock::InstantLock; +use dashcore::hash_types::InstantSendLockHash; use dashcore::Txid; +use dashcore_hashes::sha256d; use tokio::sync::RwLock; use crate::error::SyncResult; @@ -42,11 +45,18 @@ pub struct InstantLockEntry { pub validated: bool, } +/// The hash of the serialized lock, as its inventory announces it. +fn lock_hash(instant_lock: &InstantLock) -> InstantSendLockHash { + InstantSendLockHash::from_raw_hash(sha256d::Hash::hash(&encode::serialize(instant_lock))) +} + /// Pending InstantLock awaiting the quorum data required to verify it. #[derive(Debug, Clone)] pub(super) struct PendingInstantLock { /// The InstantLock data. instant_lock: InstantLock, + /// Hash of the serialized lock, which tells distinct locks of one txid apart. + hash: InstantSendLockHash, /// When the lock was first received, used to expire locks that never /// become verifiable. Uses a monotonic `Instant` so the elapsed-time TTL /// check is unaffected by wall-clock adjustments. @@ -54,6 +64,14 @@ pub(super) struct PendingInstantLock { } impl PendingInstantLock { + fn new(instant_lock: InstantLock, hash: InstantSendLockHash) -> Self { + Self { + instant_lock, + hash, + first_seen: Instant::now(), + } + } + /// Whether this pending lock has outlived [`PENDING_TTL`] as of `now`. /// /// Uses [`Instant::saturating_duration_since`], which clamps to zero @@ -141,10 +159,13 @@ impl InstantSendManager { // Only a verified lock settles its txid: an unverified one, possibly forged, // must not shadow the genuine lock for the same transaction. - if self.instantlocks.get(&txid).is_some_and(|entry| entry.validated) - || self.pending_instantlocks.iter().any(|pending| pending.instant_lock == *instantlock) - { - tracing::debug!("Already have InstantLock for txid {}", txid); + if self.instantlocks.get(&txid).is_some_and(|entry| entry.validated) { + tracing::debug!("Already have a verified InstantLock for txid {}", txid); + return Ok(vec![]); + } + let hash = lock_hash(instantlock); + if self.pending_instantlocks.iter().any(|pending| pending.hash == hash) { + tracing::debug!("The same InstantLock for txid {} is already pending", txid); return Ok(vec![]); } @@ -174,10 +195,7 @@ impl InstantSendManager { self.transition_synced_if_idle(); } } else { - self.queue_pending(PendingInstantLock { - instant_lock: instantlock.clone(), - first_seen: Instant::now(), - }); + self.queue_pending(PendingInstantLock::new(instantlock.clone(), hash)); } self.progress.update_pending(self.pending_instantlocks.len()); @@ -404,10 +422,9 @@ mod tests { /// driven by the `now` passed to `tick_at`/`expire_pending`, not by /// back-dating this field — see [`past_ttl`]. fn fresh_pending(txid: Txid) -> PendingInstantLock { - PendingInstantLock { - instant_lock: create_test_instantlock(txid), - first_seen: Instant::now(), - } + let instant_lock = create_test_instantlock(txid); + let hash = lock_hash(&instant_lock); + PendingInstantLock::new(instant_lock, hash) } /// An injected "now" far enough past a [`fresh_pending`] lock's `first_seen` diff --git a/dash-spv/src/validation/instantlock.rs b/dash-spv/src/validation/instantlock.rs index 5ebe32eb1..255a45839 100644 --- a/dash-spv/src/validation/instantlock.rs +++ b/dash-spv/src/validation/instantlock.rs @@ -1,6 +1,7 @@ use std::collections::BTreeMap; use dashcore::bls_sig_utils::BlsScheme; +use dashcore::constants::MAX_BLOCK_SIZE; use dashcore::sml::message_verification_error::MessageVerificationError; use dashcore::sml::quorum_entry::qualified_quorum_entry::QualifiedQuorumEntry; use dashcore::{InstantLock, Network, QuorumSigningRequestId, Transaction, Txid}; @@ -94,6 +95,10 @@ impl VerifiedInstantLock { } } +/// The most inputs a valid InstantLock can carry, as Dash Core caps them. +/// Its transaction fits in a block, and every input takes at least 41 bytes. +const MAX_INSTANT_LOCK_INPUTS: usize = MAX_BLOCK_SIZE as usize / 41; + /// Rejects malformed InstantLocks. Needs no quorum data, so it runs before a /// lock is looked up, queued or cached. /// @@ -120,6 +125,12 @@ impl Validator<&InstantLock> for InstantLockStructureValidator { )); } + if instant_lock.inputs.len() > MAX_INSTANT_LOCK_INPUTS { + return Err(ValidationError::InvalidInstantLock(format!( + "InstantLock has more than {MAX_INSTANT_LOCK_INPUTS} inputs" + ))); + } + if let Some(idx) = instant_lock.inputs.iter().position(|input| input.txid == dashcore::Txid::all_zeros()) { @@ -311,12 +322,16 @@ mod tests { #[test] fn a_well_formed_lock_passes_the_structure_check() { assert!(InstantLockStructureValidator.validate(&InstantLock::dummy(0..3)).is_ok()); + let mut largest = InstantLock::dummy(0..1); + largest.inputs = vec![largest.inputs[0]; MAX_INSTANT_LOCK_INPUTS]; + assert!(InstantLockStructureValidator.validate(&largest).is_ok()); } #[test_case(|lock| lock.inputs.clear(), "at least one input"; "no inputs")] #[test_case(|lock| lock.signature = dashcore::bls_sig_utils::BLSSignature::from([0; 96]), "signature cannot be zero"; "zero signature")] #[test_case(|lock| lock.txid = dashcore::Txid::all_zeros(), "transaction ID cannot be zero"; "null txid")] #[test_case(|lock| lock.inputs[1].txid = dashcore::Txid::all_zeros(), "input 1 has null transaction ID"; "null input txid")] + #[test_case(|lock| lock.inputs = vec![lock.inputs[0]; MAX_INSTANT_LOCK_INPUTS + 1], "more than 48780 inputs"; "too many inputs")] fn a_malformed_lock_fails_the_structure_check(malform: fn(&mut InstantLock), reason: &str) { let mut is_lock = InstantLock::dummy(0..3); malform(&mut is_lock); From 3f3d3302231e6873a473c2ab6639567f96f276d7 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:46:53 +0000 Subject: [PATCH 18/38] refactor(dash-spv)!: carry `VerifiedInstantLock` in `InstantLockReceived` The live InstantSend path discarded the `VerifiedInstantLock` it obtained and sent `validated: bool` to the mempool, whose gate was a literal `validated: true` pattern. A `{ .. }` match or a hand-built event could feed an unverified lock into acceptance. `SyncEvent::InstantLockReceived` now carries `instant_lock: VerifiedInstantLock` and is emitted only for verified locks. Locks awaiting quorum data are queued without an event; no in-repo consumer used that notification. `MempoolManager::process_instant_send` and its pending locks take only `VerifiedInstantLock`, which cannot be built outside the crate, so the mempool and wallet act on verified locks by type. The mempool event test moves next to its siblings in `sync_manager.rs`; its unverified-lock half is no longer expressible. Co-Authored-By: Claude Opus 5.5 --- dash-spv/ARCHITECTURE.md | 4 +- dash-spv/src/sync/events.rs | 24 ++-- dash-spv/src/sync/instantsend/manager.rs | 96 ++++++--------- dash-spv/src/sync/mempool/manager.rs | 109 +++++------------- dash-spv/src/sync/mempool/sync_manager.rs | 77 +++++++++++-- dash-spv/src/validation/instantlock.rs | 14 ++- dash-spv/tests/dashd_masternode/helpers.rs | 28 ++--- .../dashd_masternode/tests_instantsend.rs | 23 ++-- 8 files changed, 170 insertions(+), 205 deletions(-) diff --git a/dash-spv/ARCHITECTURE.md b/dash-spv/ARCHITECTURE.md index efaf6d7bd..6f8ff0ec5 100644 --- a/dash-spv/ARCHITECTURE.md +++ b/dash-spv/ARCHITECTURE.md @@ -1112,7 +1112,7 @@ sync// - Listens for InstantLock messages from network - Validates signatures -- Emits `InstantLockReceived` events +- Emits `InstantLockReceived` events carrying a `VerifiedInstantLock`; locks awaiting quorum data are queued without an event ##### `src/sync/mempool/` - Mempool Transaction Tracking @@ -1174,7 +1174,7 @@ The `seen_txids` map provides a 180-second deduplication window to handle the ca |-------|--------| | `SyncComplete` | Activate mempool relay on all connected peers (transitions to `Synced`) | | `BlockProcessed` | Remove confirmed txids from mempool state; immediately rebuild bloom filter if new addresses | -| `InstantLockReceived` | Only `validated: true`: mark transaction as IS-locked, or store in pending_is_locks if TX not yet received; unverified locks are ignored | +| `InstantLockReceived` | Mark transaction as IS-locked, or store in pending_is_locks if TX not yet received. The event carries only verified locks | | `PeerConnected` | Activate on new peer immediately if already synced | | `PeerDisconnected` | Remove peer; redistribute its queued txids to a random activated peer | | `PeersUpdated` with no addresses | All peers lost: call `stop_sync()`, transition to `WaitingForConnections` | diff --git a/dash-spv/src/sync/events.rs b/dash-spv/src/sync/events.rs index 3ab84ce8f..7467f3f44 100644 --- a/dash-spv/src/sync/events.rs +++ b/dash-spv/src/sync/events.rs @@ -1,8 +1,8 @@ use crate::sml_engine::QRInfoFeedResult; use crate::sync::mempool::BroadcastResult; use crate::sync::ManagerIdentifier; +use crate::validation::VerifiedInstantLock; use dashcore::ephemerealdata::chain_lock::ChainLock; -use dashcore::ephemerealdata::instant_lock::InstantLock; use dashcore::{BlockHash, ScriptBuf, Txid}; use key_wallet_manager::{FilterMatchKey, WalletId}; use std::collections::{BTreeMap, BTreeSet}; @@ -152,19 +152,16 @@ pub enum SyncEvent { validated: bool, }, - /// InstantSend lock received and processed. + /// InstantSend lock verified against its signing quorum. /// - /// `validated: false` means verification is deferred until quorum data - /// arrives: it is never final and may repeat for distinct locks of one txid. - /// Locks refuted by a complete, verified cycle emit no event. + /// A lock awaiting quorum data emits this event once it verifies. Malformed + /// locks and locks a complete, verified cycle refutes emit no event. /// /// Emitted by: `InstantSendManager` - /// Consumed by: External listeners, mempool state updates (validated locks only) + /// Consumed by: External listeners, mempool state updates InstantLockReceived { - /// The complete InstantLock data - instant_lock: InstantLock, - /// Whether the BLS signature was verified against its signing quorum - validated: bool, + /// The verified lock + instant_lock: VerifiedInstantLock, }, /// The network-level outcome of a self-broadcast transaction was @@ -277,12 +274,7 @@ impl fmt::Display for SyncEvent { ), SyncEvent::InstantLockReceived { instant_lock, - validated, - } => write!( - f, - "InstantLockReceived(txid={}, validated={})", - instant_lock.txid, validated - ), + } => write!(f, "InstantLockReceived(txid={})", instant_lock.txid()), SyncEvent::TransactionBroadcastResult { txid, result, diff --git a/dash-spv/src/sync/instantsend/manager.rs b/dash-spv/src/sync/instantsend/manager.rs index bac3a111d..c18437979 100644 --- a/dash-spv/src/sync/instantsend/manager.rs +++ b/dash-spv/src/sync/instantsend/manager.rs @@ -115,7 +115,7 @@ impl PendingInstantLock { /// - Subscribes to ISLock messages from the network /// - Validates InstantLocks when masternode engine is available /// - Queues InstantLocks for later validation when engine not ready -/// - Emits InstantLockReceived events +/// - Emits InstantLockReceived events for verified locks pub struct InstantSendManager { /// Current progress of the manager. pub(super) progress: InstantSendProgress, @@ -174,11 +174,11 @@ impl InstantSendManager { let engine = self.engine.read().await; let result = VerifiedInstantLock::verify(instantlock, Some(&*engine)); drop(engine); - let validated = match result { - Ok(Some(_)) => true, + let verified = match result { + Ok(Some(verified)) => Some(verified), Ok(None) => { tracing::debug!("InstantLock for txid {} awaits quorum data", txid); - false + None } Err(e) => { tracing::warn!("Rejected InstantLock for txid {}: {}", txid, e); @@ -187,7 +187,7 @@ impl InstantSendManager { } }; - if validated { + if verified.is_some() { self.progress.add_valid(1); let queued = self.pending_instantlocks.len(); self.pending_instantlocks.retain(|pending| pending.instant_lock.txid != txid); @@ -202,14 +202,16 @@ impl InstantSendManager { // Store in cache let entry = InstantLockEntry { received_at: SystemTime::now(), - validated, + validated: verified.is_some(), }; self.store_instantlock(txid, entry); - Ok(vec![SyncEvent::InstantLockReceived { - instant_lock: instantlock.clone(), - validated, - }]) + Ok(verified + .map(|instant_lock| SyncEvent::InstantLockReceived { + instant_lock, + }) + .into_iter() + .collect()) } /// Queue an InstantLock for later validation. @@ -249,7 +251,7 @@ impl InstantSendManager { /// Re-validate every pending InstantLock against the current engine state. /// /// Called both when a `MasternodeStateUpdated` event arrives and from `tick` - /// once the engine has advanced. Locks that verify are emitted as validated + /// once the engine has advanced. Locks that verify are emitted as /// `InstantLockReceived` events; locks that still can't be verified are /// re-queued until they either become verifiable or exceed [`PENDING_TTL`]. /// @@ -284,15 +286,14 @@ impl InstantSendManager { Some(&*self.engine.read().await), ); match result { - Ok(Some(_)) => { + Ok(Some(instant_lock)) => { self.progress.add_valid(1); validated_txids.insert(txid); if let Some(entry) = self.instantlocks.get_mut(&txid) { entry.validated = true; } events.push(SyncEvent::InstantLockReceived { - instant_lock: pending_lock.instant_lock, - validated: true, + instant_lock, }); } Ok(None) => self.queue_pending(pending_lock), @@ -498,13 +499,13 @@ mod tests { let islock1 = create_test_instantlock(txid); let islock2 = create_test_instantlock(txid); - // First should process - let events1 = manager.process_instantlock(&islock1).await.unwrap(); - assert_eq!(events1.len(), 1); + // First is queued until quorum data arrives + assert!(manager.process_instantlock(&islock1).await.unwrap().is_empty()); + assert_eq!(manager.pending_count(), 1); // Second should be ignored as duplicate - let events2 = manager.process_instantlock(&islock2).await.unwrap(); - assert_eq!(events2.len(), 0); + assert!(manager.process_instantlock(&islock2).await.unwrap().is_empty()); + assert_eq!(manager.pending_count(), 1); } #[test_case(|lock| lock.txid = Txid::all_zeros(); "null txid")] @@ -526,8 +527,7 @@ mod tests { assert_eq!(manager.progress.invalid(), 1); // Not cached, so the well-formed lock for the transaction still gets in. - let events = manager.process_instantlock(&create_test_instantlock(txid)).await.unwrap(); - assert_eq!(events.len(), 1); + manager.process_instantlock(&create_test_instantlock(txid)).await.unwrap(); assert_eq!(manager.pending_count(), 1); } @@ -542,20 +542,14 @@ mod tests { forged.cyclehash = CycleHash::from_byte_array([7; 32]); let events = manager.process_instantlock(&forged).await.unwrap(); - assert!(matches!( - events.as_slice(), - [SyncEvent::InstantLockReceived { - validated: false, - .. - }] - )); + assert!(events.is_empty(), "a lock awaiting quorum data emits no event"); let events = manager.process_instantlock(&genuine).await.unwrap(); assert!( matches!( events.as_slice(), - [SyncEvent::InstantLockReceived { instant_lock, validated: true }] - if instant_lock == &genuine + [SyncEvent::InstantLockReceived { instant_lock }] + if instant_lock.instant_lock() == &genuine ), "genuine lock was shadowed by the forged one: {events:?}" ); @@ -579,13 +573,7 @@ mod tests { assert_eq!(manager.progress.invalid(), 1); let events = manager.process_instantlock(&genuine).await.unwrap(); - assert!(matches!( - events.as_slice(), - [SyncEvent::InstantLockReceived { - validated: true, - .. - }] - )); + assert!(matches!(events.as_slice(), [SyncEvent::InstantLockReceived { .. }])); } /// Once one lock for a txid verifies, its other pending locks never emit. @@ -599,13 +587,7 @@ mod tests { other_cycle.cyclehash = CycleHash::from_byte_array([7; 32]); for lock in [&other_cycle, &genuine] { let events = manager.process_instantlock(lock).await.unwrap(); - assert!(matches!( - events.as_slice(), - [SyncEvent::InstantLockReceived { - validated: false, - .. - }] - )); + assert!(events.is_empty(), "a lock awaiting quorum data emits no event"); } assert_eq!(manager.pending_count(), 2); @@ -613,8 +595,8 @@ mod tests { let events = manager.validate_pending(Instant::now()).await.unwrap(); assert!(matches!( events.as_slice(), - [SyncEvent::InstantLockReceived { instant_lock, validated: true }] - if instant_lock == &genuine + [SyncEvent::InstantLockReceived { instant_lock }] + if instant_lock.instant_lock() == &genuine )); assert_eq!(manager.pending_count(), 0); assert!(manager.validate_pending(Instant::now()).await.unwrap().is_empty()); @@ -633,13 +615,7 @@ mod tests { let mut forged = genuine.clone(); forged.signature = BLSSignature::from([1; 96]); let events = manager.process_instantlock(&forged).await.unwrap(); - assert!(matches!( - events.as_slice(), - [SyncEvent::InstantLockReceived { - validated: false, - .. - }] - )); + assert!(events.is_empty(), "a lock awaiting quorum data emits no event"); assert_eq!(manager.pending_count(), 1); *manager.engine.write().await = TestEngine::mainnet_fixture(); @@ -657,8 +633,8 @@ mod tests { let events = manager.process_instantlock(&genuine).await.unwrap(); assert!(matches!( events.as_slice(), - [SyncEvent::InstantLockReceived { instant_lock, validated: true }] - if instant_lock == &genuine + [SyncEvent::InstantLockReceived { instant_lock }] + if instant_lock.instant_lock() == &genuine )); } @@ -682,8 +658,8 @@ mod tests { assert!(matches!( events.as_slice(), - [SyncEvent::InstantLockReceived { instant_lock, validated: true }] - if instant_lock == &genuine + [SyncEvent::InstantLockReceived { instant_lock }] + if instant_lock.instant_lock() == &genuine )); assert_eq!(manager.pending_count(), 0); assert!(manager.process_instantlock(&forged).await.unwrap().is_empty()); @@ -909,8 +885,7 @@ mod tests { // First announcement: the empty engine can't verify it, so it is queued // and cached as an unvalidated entry. - let events = manager.process_instantlock(&create_test_instantlock(txid)).await.unwrap(); - assert_eq!(events.len(), 1); + manager.process_instantlock(&create_test_instantlock(txid)).await.unwrap(); assert_eq!(manager.pending_count(), 1); assert!(manager.instantlocks.contains_key(&txid)); @@ -920,8 +895,7 @@ mod tests { assert!(!manager.instantlocks.contains_key(&txid)); // Re-announcement of the same txid is processed fresh, not deduped away. - let events = manager.process_instantlock(&create_test_instantlock(txid)).await.unwrap(); - assert_eq!(events.len(), 1); + manager.process_instantlock(&create_test_instantlock(txid)).await.unwrap(); assert_eq!(manager.pending_count(), 1); } diff --git a/dash-spv/src/sync/mempool/manager.rs b/dash-spv/src/sync/mempool/manager.rs index 92294c878..68ec37c54 100644 --- a/dash-spv/src/sync/mempool/manager.rs +++ b/dash-spv/src/sync/mempool/manager.rs @@ -10,7 +10,6 @@ use std::net::SocketAddr; use std::sync::Arc; use std::time::{Duration, Instant}; -use dashcore::ephemerealdata::instant_lock::InstantLock; use dashcore::network::message::NetworkMessage; use dashcore::network::message_blockdata::Inventory; use dashcore::{Amount, Transaction, Txid}; @@ -26,6 +25,7 @@ use crate::network::NetworkManager; use crate::sync::mempool::MempoolProgress; use crate::sync::SyncEvent; use crate::types::UnconfirmedTransaction; +use crate::validation::VerifiedInstantLock; use key_wallet_manager::WalletInterface; /// Timeout for pruning expired mempool transactions (24 hours). @@ -66,7 +66,7 @@ pub(crate) struct MempoolManager { /// Connected peers and their activation state. pub(super) peers: HashMap>>, /// IS locks that arrived before their corresponding transaction, with insertion time. - pending_is_locks: HashMap, + pub(super) pending_is_locks: HashMap, /// Txids already downloaded, with download timestamp. /// Prevents duplicate downloads when multiple peers announce the same transactions. /// Entries expire after `SEEN_TXID_EXPIRY`. @@ -400,7 +400,8 @@ impl MempoolManager { self.progress.add_received(1); // Check for a pre-arrived IS lock before wallet processing consumes it - let pending_lock = self.pending_is_locks.remove(&txid).map(|(lock, _)| lock); + let pending_lock = + self.pending_is_locks.remove(&txid).map(|(lock, _)| lock.instant_lock().clone()); let is_locked = pending_lock.is_some(); let result = { @@ -605,9 +606,9 @@ impl MempoolManager { /// broadcast for the txid is promoted to accepted and dropped from tracking. pub(super) async fn process_instant_send( &mut self, - instant_lock: InstantLock, + instant_lock: VerifiedInstantLock, ) -> Vec { - let txid = instant_lock.txid; + let txid = instant_lock.txid(); let mut events = Vec::new(); if let Some(state) = self.broadcasts.remove(&txid) { if matches!(state.status, BroadcastStatus::Pending | BroadcastStatus::Uncertain) { @@ -639,7 +640,9 @@ impl MempoolManager { if let Some(lock) = instant_lock_opt { let mut wallet = self.wallet.write().await; if let Some(tx) = self.transactions.get(&txid) { - wallet.process_mempool_instant_send_lock(&tx.transaction, lock).await; + wallet + .process_mempool_instant_send_lock(&tx.transaction, lock.instant_lock().clone()) + .await; } } events @@ -852,7 +855,7 @@ impl fmt::Debug for MempoolManager { mod tests { use super::*; use dashcore::network::message::NetworkMessage; - use dashcore::{Address, BlockHash, Network, ScriptBuf, Transaction}; + use dashcore::{Address, BlockHash, InstantLock, Network, ScriptBuf, Transaction}; use key_wallet::transaction_checking::TransactionContext; use key_wallet_manager::test_utils::MockWallet; @@ -866,6 +869,10 @@ mod tests { } } + fn verified_lock(txid: Txid) -> VerifiedInstantLock { + VerifiedInstantLock::assume_verified(dummy_instant_lock(txid)) + } + fn rich_instant_lock(txid: Txid) -> InstantLock { InstantLock { txid, @@ -1333,7 +1340,7 @@ mod tests { UnconfirmedTransaction::new(tx, Amount::from_sat(0), false, false, Vec::new(), 0), ); - let events = manager.process_instant_send(dummy_instant_lock(txid)).await; + let events = manager.process_instant_send(verified_lock(txid)).await; // Verify IS flag, broadcast promotion, and tracking cleanup assert!(manager.transactions.get(&txid).unwrap().is_instant_send); @@ -1360,67 +1367,12 @@ mod tests { assert_eq!(locks[0], (txid, Some(dummy_instant_lock(txid)))); } - #[test_case::test_case(true, false; "known pending")] - #[test_case::test_case(true, true; "known uncertain")] - #[test_case::test_case(false, false; "early pending")] - #[test_case::test_case(false, true; "early uncertain")] - #[tokio::test] - async fn should_ignore_unverified_instant_lock(known: bool, uncertain: bool) { - use crate::sync::SyncManager; - let (mut manager, requests, _rx) = create_test_manager(); - let tx = test_transaction(1); - let txid = tx.txid(); - assert!(manager.start_broadcast(&tx, &requests).await.is_empty()); - if known { - manager.transactions.insert( - txid, - UnconfirmedTransaction::new(tx, Amount::from_sat(0), false, false, Vec::new(), 0), - ); - } - let status = if uncertain { - BroadcastStatus::Uncertain - } else { - BroadcastStatus::Pending - }; - manager.broadcasts.get_mut(&txid).unwrap().status = status; - let lock = dummy_instant_lock(txid); - let received = |validated| SyncEvent::InstantLockReceived { - instant_lock: lock.clone(), - validated, - }; - - let events = manager.handle_sync_event(&received(false), &requests).await.unwrap(); - assert!(events.is_empty(), "unverified locks cannot accept broadcasts"); - assert_eq!(manager.broadcasts.get(&txid).unwrap().status, status); - assert!(manager.pending_is_locks.is_empty()); - assert!(!manager.transactions.get(&txid).is_some_and(|tx| tx.is_instant_send)); - assert!(manager.wallet.read().await.processed_instant_locks.lock().await.is_empty()); - - let events = manager.handle_sync_event(&received(true), &requests).await.unwrap(); - assert!(matches!( - events.as_slice(), - [SyncEvent::TransactionBroadcastResult { - txid: accepted, - result: BroadcastResult::Accepted { .. }, - }] if *accepted == txid - )); - assert!(!manager.broadcasts.contains_key(&txid)); - let processed = manager.wallet.read().await.processed_instant_locks.lock().await.clone(); - if known { - assert!(manager.transactions.get(&txid).unwrap().is_instant_send); - assert_eq!(processed, vec![(txid, Some(lock))]); - } else { - assert_eq!(manager.pending_is_locks.get(&txid).unwrap().0, lock); - assert!(processed.is_empty()); - } - } - #[tokio::test] async fn test_mark_instant_send_stores_pending_for_unknown() { let (mut manager, _requests, _rx) = create_test_manager(); let unknown_txid = Txid::from_byte_array([0xbb; 32]); - manager.process_instant_send(dummy_instant_lock(unknown_txid)).await; + manager.process_instant_send(verified_lock(unknown_txid)).await; // No immediate wallet notification let wallet = manager.wallet.read().await; @@ -1532,7 +1484,7 @@ mod tests { .peers .insert(test_socket_address(1), Some(VecDeque::from([Txid::from_byte_array([2; 32])]))); let txid3 = Txid::from_byte_array([3; 32]); - manager.pending_is_locks.insert(txid3, (dummy_instant_lock(txid3), Instant::now())); + manager.pending_is_locks.insert(txid3, (verified_lock(txid3), Instant::now())); manager.clear_pending(); @@ -1581,7 +1533,9 @@ mod tests { let txid = tx.txid(); // IS lock arrives before the transaction (with a distinct cyclehash) - manager.process_instant_send(rich_instant_lock(txid)).await; + manager + .process_instant_send(VerifiedInstantLock::assume_verified(rich_instant_lock(txid))) + .await; assert!(manager.pending_is_locks.contains_key(&txid)); // Transaction arrives @@ -1619,7 +1573,7 @@ mod tests { let txid = tx.txid(); // IS lock arrives before the transaction - manager.process_instant_send(dummy_instant_lock(txid)).await; + manager.process_instant_send(verified_lock(txid)).await; assert!(manager.pending_is_locks.contains_key(&txid)); // Transaction arrives but wallet says it's not relevant @@ -1641,13 +1595,13 @@ mod tests { let mut bytes = [0u8; 32]; bytes[0..8].copy_from_slice(&(i as u64).to_le_bytes()); let txid = Txid::from_byte_array(bytes); - manager.pending_is_locks.insert(txid, (dummy_instant_lock(txid), Instant::now())); + manager.pending_is_locks.insert(txid, (verified_lock(txid), Instant::now())); } assert_eq!(manager.pending_is_locks.len(), MAX_PENDING_IS_LOCKS); // Next IS lock should be dropped let overflow_txid = Txid::from_byte_array([0xff; 32]); - manager.process_instant_send(dummy_instant_lock(overflow_txid)).await; + manager.process_instant_send(verified_lock(overflow_txid)).await; assert!(!manager.pending_is_locks.contains_key(&overflow_txid)); assert_eq!(manager.pending_is_locks.len(), MAX_PENDING_IS_LOCKS); } @@ -1675,10 +1629,10 @@ mod tests { // Also store a pending IS lock for this txid and an unrelated one let unrelated_txid = Txid::from_byte_array([0xdd; 32]); - manager.pending_is_locks.insert(txid, (dummy_instant_lock(txid), Instant::now())); + manager.pending_is_locks.insert(txid, (verified_lock(txid), Instant::now())); manager .pending_is_locks - .insert(unrelated_txid, (dummy_instant_lock(unrelated_txid), Instant::now())); + .insert(unrelated_txid, (verified_lock(unrelated_txid), Instant::now())); manager.prune_expired(test_timeout); @@ -1704,17 +1658,12 @@ mod tests { let stale_txid = Txid::from_byte_array([0xaa; 32]); manager.pending_is_locks.insert( stale_txid, - ( - dummy_instant_lock(stale_txid), - Instant::now() - test_timeout - Duration::from_secs(1), - ), + (verified_lock(stale_txid), Instant::now() - test_timeout - Duration::from_secs(1)), ); // Insert a fresh pending IS lock let fresh_txid = Txid::from_byte_array([0xbb; 32]); - manager - .pending_is_locks - .insert(fresh_txid, (dummy_instant_lock(fresh_txid), Instant::now())); + manager.pending_is_locks.insert(fresh_txid, (verified_lock(fresh_txid), Instant::now())); manager.prune_expired(test_timeout); @@ -2016,7 +1965,7 @@ mod tests { // The same signed transaction reached the network by another route first (a BIP70 // merchant broadcasting the bytes it was just paid with), so its InstantSend lock // arrives before this node dispatches its own copy. - manager.process_instant_send(dummy_instant_lock(txid)).await; + manager.process_instant_send(verified_lock(txid)).await; assert!(manager.pending_is_locks.contains_key(&txid)); let events = manager.start_broadcast(&tx, &requests).await; @@ -2118,7 +2067,7 @@ mod tests { let tx = test_transaction(43); let txid = tx.txid(); - manager.process_instant_send(dummy_instant_lock(txid)).await; + manager.process_instant_send(verified_lock(txid)).await; let local_addr = SocketAddr::from(([0, 0, 0, 0], 0)); let events = manager.handle_tx(tx, local_addr, &requests).await.unwrap(); diff --git a/dash-spv/src/sync/mempool/sync_manager.rs b/dash-spv/src/sync/mempool/sync_manager.rs index d9207ba01..45a77d22b 100644 --- a/dash-spv/src/sync/mempool/sync_manager.rs +++ b/dash-spv/src/sync/mempool/sync_manager.rs @@ -131,7 +131,6 @@ impl SyncManager for MempoolManager { } SyncEvent::InstantLockReceived { instant_lock, - validated: true, } => Ok(self.process_instant_send(instant_lock.clone()).await), _ => Ok(vec![]), } @@ -185,8 +184,12 @@ impl SyncManager for MempoolManager { mod tests { use super::*; use crate::client::config::MempoolStrategy; + use crate::sync::mempool::broadcast::{BroadcastResult, BroadcastStatus}; use crate::sync::BroadcastConfig; use crate::test_utils::{test_socket_address, MockNetworkManager}; + use crate::types::UnconfirmedTransaction; + use crate::validation::VerifiedInstantLock; + use dashcore::{Amount, InstantLock}; use key_wallet_manager::test_utils::MockWallet; use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; @@ -427,8 +430,7 @@ mod tests { is_lock.txid = txid; let event = SyncEvent::InstantLockReceived { - instant_lock: is_lock, - validated: true, + instant_lock: VerifiedInstantLock::assume_verified(is_lock), }; let events = manager.handle_sync_event(&event, &network).await.unwrap(); assert!(events.is_empty()); @@ -497,8 +499,7 @@ mod tests { ..InstantLock::default() }; let event = SyncEvent::InstantLockReceived { - instant_lock: lock, - validated: true, + instant_lock: VerifiedInstantLock::assume_verified(lock), }; manager.handle_sync_event(&event, &network).await.unwrap(); let mut corrections = Vec::new(); @@ -577,11 +578,10 @@ mod tests { } while rx.try_recv().is_ok() {} let event = SyncEvent::InstantLockReceived { - instant_lock: InstantLock { + instant_lock: VerifiedInstantLock::assume_verified(InstantLock { txid: tx.txid(), ..InstantLock::default() - }, - validated: true, + }), }; manager.handle_sync_event(&event, &network).await.unwrap(); let mut locks = 0; @@ -622,11 +622,10 @@ mod tests { .unwrap(); while rx.try_recv().is_ok() {} let event = SyncEvent::InstantLockReceived { - instant_lock: InstantLock { + instant_lock: VerifiedInstantLock::assume_verified(InstantLock { txid: outgoing.txid(), ..InstantLock::default() - }, - validated: true, + }), }; manager.handle_sync_event(&event, &network).await.unwrap(); assert!( @@ -642,6 +641,62 @@ mod tests { )); } + #[test_case::test_case(true, false; "known pending")] + #[test_case::test_case(true, true; "known uncertain")] + #[test_case::test_case(false, false; "early pending")] + #[test_case::test_case(false, true; "early uncertain")] + #[tokio::test] + async fn should_accept_broadcast_on_verified_instant_lock(known: bool, uncertain: bool) { + let (mut manager, network) = create_test_manager(); + let tx = dashcore::Transaction { + version: 1, + lock_time: 0, + input: vec![], + output: vec![], + special_transaction_payload: None, + }; + let txid = tx.txid(); + assert!(manager.start_broadcast(&tx, &network).await.is_empty()); + if known { + manager.transactions.insert( + txid, + UnconfirmedTransaction::new(tx, Amount::from_sat(0), false, false, Vec::new(), 0), + ); + } + let status = if uncertain { + BroadcastStatus::Uncertain + } else { + BroadcastStatus::Pending + }; + manager.broadcasts.get_mut(&txid).unwrap().status = status; + let lock = InstantLock { + txid, + ..InstantLock::default() + }; + let event = SyncEvent::InstantLockReceived { + instant_lock: VerifiedInstantLock::assume_verified(lock.clone()), + }; + + let events = manager.handle_sync_event(&event, &network).await.unwrap(); + + assert!(matches!( + events.as_slice(), + [SyncEvent::TransactionBroadcastResult { + txid: accepted, + result: BroadcastResult::Accepted { .. }, + }] if *accepted == txid + )); + assert!(!manager.broadcasts.contains_key(&txid)); + let processed = manager.wallet.read().await.processed_instant_locks.lock().await.clone(); + if known { + assert!(manager.transactions.get(&txid).unwrap().is_instant_send); + assert_eq!(processed, vec![(txid, Some(lock))]); + } else { + assert_eq!(manager.pending_is_locks.get(&txid).unwrap().0.instant_lock(), &lock); + assert!(processed.is_empty()); + } + } + #[tokio::test] async fn test_peer_disconnect_removes_from_peers() { let (mut manager, network) = create_test_manager(); diff --git a/dash-spv/src/validation/instantlock.rs b/dash-spv/src/validation/instantlock.rs index 255a45839..62898d1f2 100644 --- a/dash-spv/src/validation/instantlock.rs +++ b/dash-spv/src/validation/instantlock.rs @@ -14,13 +14,25 @@ use crate::validation::Validator; /// An InstantLock authenticated against the client's synchronized quorum state. /// /// This evidence is process-local: persisted locks must be verified again on load. -/// Obtain it with `DashSpvClient::verify_instant_lock`; a stored context is not proof. +/// Obtain it with `DashSpvClient::verify_instant_lock` or from `SyncEvent::InstantLockReceived`; +/// a stored context is not proof. #[derive(Debug, Clone)] pub struct VerifiedInstantLock { instant_lock: InstantLock, network: Network, } +#[cfg(test)] +impl VerifiedInstantLock { + /// Evidence for `instant_lock` without authenticating it, for unit tests of its consumers. + pub(crate) fn assume_verified(instant_lock: InstantLock) -> Self { + Self { + instant_lock, + network: Network::Testnet, + } + } +} + /// A stored or received InstantLock failed authentication. #[derive(Debug, thiserror::Error)] pub enum InstantLockVerificationError { diff --git a/dash-spv/tests/dashd_masternode/helpers.rs b/dash-spv/tests/dashd_masternode/helpers.rs index 6bb76061c..c28020cd8 100644 --- a/dash-spv/tests/dashd_masternode/helpers.rs +++ b/dash-spv/tests/dashd_masternode/helpers.rs @@ -280,14 +280,12 @@ pub(super) async fn wait_for_mn_state_with_stored_cycle_above( } } -/// Wait for an `InstantLockReceived` sync event for `txid` with the desired validation state. +/// Wait for the verified `InstantLockReceived` sync event for `txid`. /// -/// Returns the received `InstantLock`. Ignores events for unrelated txids and events -/// whose `validated` flag does not match `want_validated`. +/// Returns the verified `InstantLock`. Ignores events for unrelated txids. pub(super) async fn wait_for_instant_lock_received( event_receiver: &mut broadcast::Receiver, txid: Txid, - want_validated: bool, timeout_secs: u64, ) -> InstantLock { let timeout = time::sleep(Duration::from_secs(timeout_secs)); @@ -296,26 +294,18 @@ pub(super) async fn wait_for_instant_lock_received( loop { tokio::select! { _ = &mut timeout => { - panic!( - "Timeout waiting for InstantLockReceived(txid={}, validated={})", - txid, want_validated - ); + panic!("Timeout waiting for InstantLockReceived(txid={})", txid); } result = event_receiver.recv() => { match result { - Ok(SyncEvent::InstantLockReceived { instant_lock, validated }) - if instant_lock.txid == txid && validated == want_validated => - { - tracing::info!( - "InstantLockReceived(txid={}, validated={})", - txid, validated - ); - return instant_lock; + Ok(SyncEvent::InstantLockReceived { instant_lock }) if instant_lock.txid() == txid => { + tracing::info!("InstantLockReceived(txid={})", txid); + return instant_lock.instant_lock().clone(); } - Ok(SyncEvent::InstantLockReceived { instant_lock, validated }) => { + Ok(SyncEvent::InstantLockReceived { instant_lock }) => { tracing::debug!( - "Ignoring InstantLockReceived(txid={}, validated={}) — waiting for txid={} validated={}", - instant_lock.txid, validated, txid, want_validated + "Ignoring InstantLockReceived(txid={}) — waiting for txid={}", + instant_lock.txid(), txid ); continue; } diff --git a/dash-spv/tests/dashd_masternode/tests_instantsend.rs b/dash-spv/tests/dashd_masternode/tests_instantsend.rs index 74559c003..912bdde17 100644 --- a/dash-spv/tests/dashd_masternode/tests_instantsend.rs +++ b/dash-spv/tests/dashd_masternode/tests_instantsend.rs @@ -31,7 +31,7 @@ use super::setup::{ /// up). The sends are sequential rather than concurrent because regtest's /// 4-MN quorum has trouble keeping multiple concurrent IS signing sessions /// alive past the session timeout. For each transaction the test asserts: -/// 1. `SyncEvent::InstantLockReceived { validated: true }` fires. +/// 1. `SyncEvent::InstantLockReceived` fires for the verified lock. /// 2. A wallet event reports `TransactionContext::InstantSend(_)` for the txid. /// Then it mines blocks until a ChainLock is produced and asserts each tx /// transitions to `TransactionContext::InChainLockedBlock(_)`. @@ -80,7 +80,6 @@ async fn test_instantsend_full_lifecycle() { let lock = wait_for_instant_lock_received( &mut client_handle.sync_event_receiver, txid, - true, SYNC_TIMEOUT, ) .await; @@ -181,7 +180,6 @@ async fn test_instantsend_across_quorum_rotation() { let _ = wait_for_instant_lock_received( &mut client_handle.sync_event_receiver, pre_txid, - true, SYNC_TIMEOUT, ) .await; @@ -215,7 +213,6 @@ async fn test_instantsend_across_quorum_rotation() { let _ = wait_for_instant_lock_received( &mut client_handle.sync_event_receiver, post_txid, - true, SYNC_TIMEOUT, ) .await; @@ -239,7 +236,7 @@ async fn test_instantsend_across_quorum_rotation() { /// path where an islock is held until the matching mempool entry arrives. /// /// Regardless of exact ordering, the test asserts the end-to-end outcome: a -/// validated `InstantLockReceived` event plus a wallet event reporting the +/// verified `InstantLockReceived` event plus a wallet event reporting the /// transaction in an `InstantSend` context. #[tokio::test] async fn test_instantsend_islock_arrives_before_tx() { @@ -288,18 +285,14 @@ async fn test_instantsend_islock_arrives_before_tx() { // rotated_quorums_per_cycle so the pending islock can be validated. wait_for_masternode_sync(&mut client_handle.progress_receiver, SYNC_TIMEOUT).await; - // The isdlock may have arrived before MN sync (validated=false, queued as - // pending). MasternodeStateUpdated triggers validate_pending which re-emits - // with validated=true. Bump mocktime again to ensure the scheduler fires. + // The isdlock may have arrived before MN sync and been queued as pending. + // MasternodeStateUpdated triggers validate_pending, which emits it once it + // verifies. Bump mocktime again to ensure the scheduler fires. ctx.mn_ctx.bump_mocktime(30); - let lock = wait_for_instant_lock_received( - &mut client_handle.sync_event_receiver, - txid, - true, - SYNC_TIMEOUT, - ) - .await; + let lock = + wait_for_instant_lock_received(&mut client_handle.sync_event_receiver, txid, SYNC_TIMEOUT) + .await; assert_eq!(lock.txid, txid); // And the wallet must observe it with an InstantSend context regardless of From 9bf93c1a7fc5f1f25345232a3f861da8e9fd7ae3 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:47:03 +0000 Subject: [PATCH 19/38] refactor(dash-spv): drop the superseded `InstantLockValidator` impl `impl Validator<&InstantLock> for InstantLockValidator` was only reached by a test since `VerifiedInstantLock::verify` became the single entry point. Its doc now points there, and the disconnect comments describe the current deduplication. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sync/instantsend/manager.rs | 4 +--- dash-spv/src/sync/instantsend/sync_manager.rs | 6 ++---- dash-spv/src/validation/instantlock.rs | 18 ++++-------------- 3 files changed, 7 insertions(+), 21 deletions(-) diff --git a/dash-spv/src/sync/instantsend/manager.rs b/dash-spv/src/sync/instantsend/manager.rs index c18437979..4d70dc98f 100644 --- a/dash-spv/src/sync/instantsend/manager.rs +++ b/dash-spv/src/sync/instantsend/manager.rs @@ -874,9 +874,7 @@ mod tests { } /// A lock re-announced with the same txid after a disconnect must be - /// processed fresh, not silently dropped as a duplicate. `on_disconnect` has - /// to evict the unvalidated cache entry that `process_instantlock` dedupes - /// against, otherwise the re-announced lock is never re-queued/re-validated. + /// processed fresh, not dropped as a duplicate of the cleared pending queue. #[tokio::test] async fn test_reannounce_after_disconnect_is_not_duplicate() { let mut manager = create_test_manager(); diff --git a/dash-spv/src/sync/instantsend/sync_manager.rs b/dash-spv/src/sync/instantsend/sync_manager.rs index 527cbb9da..b5cea2989 100644 --- a/dash-spv/src/sync/instantsend/sync_manager.rs +++ b/dash-spv/src/sync/instantsend/sync_manager.rs @@ -30,10 +30,8 @@ impl SyncManager for InstantSendManager { } fn on_disconnect(&mut self) { - // Clear the queue *and* drop unvalidated cache entries. Leaving the - // latter behind would make `process_instantlock` treat a lock - // re-announced after reconnect as a duplicate, so it would never be - // re-queued or re-validated. + // Clear the queue so a lock re-announced after reconnect is processed + // fresh, and drop unvalidated cache entries because they are not final. self.clear_unvalidated_on_disconnect(); // Nothing is queued anymore, so the height at which we last validated is // meaningless; reset it so re-validation runs again after reconnect. diff --git a/dash-spv/src/validation/instantlock.rs b/dash-spv/src/validation/instantlock.rs index 62898d1f2..74095ba05 100644 --- a/dash-spv/src/validation/instantlock.rs +++ b/dash-spv/src/validation/instantlock.rs @@ -155,24 +155,14 @@ impl Validator<&InstantLock> for InstantLockStructureValidator { } } -/// Verifies an InstantLock's signature against the rotated quorums of its -/// cycle. It does not check the lock's structure: run -/// [`InstantLockStructureValidator`] first. Never accept InstantLocks from the -/// network without both. -/// -/// A lock whose signature does not verify, or whose quorum is not in the -/// cycle, fails with [`ValidationError::InvalidSignature`]. +/// Verifies an InstantLock's signature against the rotated quorums of its cycle. +/// It does not check the lock's structure or the cycle's eligibility: use +/// [`VerifiedInstantLock::verify`], which does both. pub struct InstantLockValidator<'a> { /// The rotated quorums of the lock's cycle, by quorum index. cycle_quorums: &'a BTreeMap, } -impl Validator<&InstantLock> for InstantLockValidator<'_> { - fn validate(&self, instant_lock: &InstantLock) -> ValidationResult<()> { - self.validate_signature(instant_lock).map_err(signature_error) - } -} - fn signature_error(error: MessageVerificationError) -> ValidationError { ValidationError::InvalidSignature(format!( "InstantLock BLS signature verification failed: {error}" @@ -384,7 +374,7 @@ mod tests { sign_id.as_byte_array().to_lower_hex_string(), "6fcbf58004b118d865a448bf89d9299c64d4ecedd754dabec655090224de91cd" ); - validator.validate(&lock).expect("expected to verify is lock"); + validator.validate_signature(&lock).expect("expected to verify is lock"); // Without its quorum index in the cycle, the lock cannot be resolved. let mut quorums = engine.rotated_quorums_of_cycle(&lock.cyclehash).unwrap().clone(); From ae2218de9321c23b67e6ee136ab4a92d669a02de Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:56:48 +0000 Subject: [PATCH 20/38] test(dash-spv): drop an InstantLock above the input bound before queueing it Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sync/instantsend/manager.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/dash-spv/src/sync/instantsend/manager.rs b/dash-spv/src/sync/instantsend/manager.rs index 4d70dc98f..a591baf64 100644 --- a/dash-spv/src/sync/instantsend/manager.rs +++ b/dash-spv/src/sync/instantsend/manager.rs @@ -512,6 +512,7 @@ mod tests { #[test_case(|lock| lock.signature = BLSSignature::from([0; 96]); "zero signature")] #[test_case(|lock| lock.inputs.clear(); "no inputs")] #[test_case(|lock| lock.inputs[0].txid = Txid::all_zeros(); "null input txid")] + #[test_case(|lock| lock.inputs = vec![lock.inputs[0]; dashcore::constants::MAX_BLOCK_SIZE as usize / 41 + 1]; "too many inputs")] #[tokio::test] async fn a_malformed_lock_of_an_unknown_cycle_is_dropped(malform: fn(&mut InstantLock)) { let mut manager = create_test_manager(); From 38823cd2244e92cda8f2a0e67ca477ddf3c73c45 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:10:36 +0000 Subject: [PATCH 21/38] test(dash-spv): check devnet cycle completeness without the global override The devnet test returned early whenever another test in the same binary had set the process-wide devnet override, so under `cargo test` it rarely asserted anything. The completeness rule now lives in a pure function taking the InstantSend type explicitly, and the test drives it directly. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sml_engine.rs | 102 ++++++++++++++++++++----------------- 1 file changed, 56 insertions(+), 46 deletions(-) diff --git a/dash-spv/src/sml_engine.rs b/dash-spv/src/sml_engine.rs index 944542ccd..c36d8fc3a 100644 --- a/dash-spv/src/sml_engine.rs +++ b/dash-spv/src/sml_engine.rs @@ -66,6 +66,39 @@ pub(crate) struct InstantSendCycle<'a> { pub(crate) complete: bool, } +/// `true` when the cycle holds a `Verified` quorum for every active slot of `isd_type`. +fn fills_every_slot(quorums: &BTreeMap, isd_type: LLMQType) -> bool { + quorums.len() == isd_type.active_quorum_count() as usize + && quorums.values().all(|quorum| quorum.verified == LLMQEntryVerificationStatus::Verified) +} + +/// Whether a stored cycle is complete, or `None` when one of its quorums is unverified or +/// cannot sign IS locks: of type `isd_type`, or any rotating type when `reads_served_type`. +/// Storage stops merging into a cycle only once it fills every slot of `isd_type`. +fn instant_send_cycle_completeness( + quorums: &BTreeMap, + isd_type: LLMQType, + reads_served_type: bool, +) -> Option { + let signs = |llmq_type: LLMQType| { + if reads_served_type { + llmq_type.is_rotating_quorum_type() + } else { + llmq_type == isd_type + } + }; + if quorums.values().any(|quorum| { + quorum.verified != LLMQEntryVerificationStatus::Verified + || !signs(quorum.quorum_entry.llmq_type) + }) { + return None; + } + Some( + fills_every_slot(quorums, isd_type) + && quorums.values().all(|quorum| quorum.quorum_entry.llmq_type == isd_type), + ) +} + /// Why the engine did not take a diff or a QRInfo. #[derive(Debug, thiserror::Error)] pub enum FeedError { @@ -443,16 +476,11 @@ impl MasternodeListEngine { cycle_hash: &BlockHash, ) -> Option> { let quorums = self.rotated_quorums_per_cycle.get(cycle_hash)?; - if quorums.values().any(|quorum| { - quorum.verified != LLMQEntryVerificationStatus::Verified - || !self.signs_instant_locks(quorum.quorum_entry.llmq_type) - }) { - return None; - } - // Storage stops merging into a cycle only once it fills every slot of the configured type. - let isd_type = self.network.isd_llmq_type(); - let complete = self.is_cycle_fully_verified(cycle_hash) - && quorums.values().all(|quorum| quorum.quorum_entry.llmq_type == isd_type); + let complete = instant_send_cycle_completeness( + quorums, + self.network.isd_llmq_type(), + self.reads_served_rotation_type(), + )?; Some(InstantSendCycle { quorums, complete, @@ -738,11 +766,10 @@ impl MasternodeListEngine { /// `true` when the stored cycle has a `Verified` quorum for every active /// slot. A partial cycle stays open so a later QRInfo can complete it. fn is_cycle_fully_verified(&self, cycle_hash: &BlockHash) -> bool { - let expected = self.network.isd_llmq_type().active_quorum_count() as usize; - self.rotated_quorums_per_cycle.get(cycle_hash).is_some_and(|existing| { - existing.len() == expected - && existing.values().all(|q| q.verified == LLMQEntryVerificationStatus::Verified) - }) + let isd_type = self.network.isd_llmq_type(); + self.rotated_quorums_per_cycle + .get(cycle_hash) + .is_some_and(|existing| fills_every_slot(existing, isd_type)) } /// Merges the active set into its stored cycle when every quorum of it is @@ -935,15 +962,6 @@ impl MasternodeListEngine { .unwrap_or(configured) } - /// Whether a quorum of `llmq_type` can sign this network's IS locks: the - /// configured rotation type, or on a devnet without an override, any rotating type. - fn signs_instant_locks(&self, llmq_type: LLMQType) -> bool { - if self.reads_served_rotation_type() { - return llmq_type.is_rotating_quorum_type(); - } - llmq_type == self.network.isd_llmq_type() - } - fn reads_served_rotation_type(&self) -> bool { self.network == Network::Devnet && devnet_isd_type_override().is_none() } @@ -1570,13 +1588,16 @@ pub(crate) mod test_support { #[cfg(test)] mod tests { use super::test_support::{fixture_heights, mainnet_fixture_is_lock, quorum_entry, TestEngine}; - use super::{build_cycle_quorum_map, qr_info_diffs, valid_coinbase_chain_lock}; + use super::{ + build_cycle_quorum_map, instant_send_cycle_completeness, qr_info_diffs, + valid_coinbase_chain_lock, + }; use super::{FeedError, MasternodeListEngine, QRInfoFeedResult, WORK_DIFF_DEPTH}; use crate::error::{StorageError, StorageResult}; use crate::storage::{BlockHeaderStorage, BlockHeaderTip}; use crate::test_utils::MockHeaderStorage; use crate::types::HashedBlockHeader; - use crate::validation::{MasternodeListValidator, VerifiedInstantLock}; + use crate::validation::MasternodeListValidator; use bincode::{config, decode_from_slice, Decode}; use dashcore::bls_sig_utils::{BLSPublicKey, BLSSignature}; use dashcore::consensus::deserialize; @@ -3493,30 +3514,19 @@ mod tests { /// one. Holding as many quorums as the configured type has slots does not complete /// it, so a lock it does not verify is deferred, not refuted. #[test] - fn should_defer_lock_on_a_partial_devnet_cycle_of_another_rotating_type() { - // Another test in this binary may set the process-wide override, which pins the type. - if devnet_isd_type_override().is_some() { - return; - } + fn should_not_complete_a_devnet_cycle_of_another_rotating_type() { let lock = mainnet_fixture_is_lock(); let cycle = TestEngine::mainnet_fixture().rotated_quorums_per_cycle[&lock.cyclehash].clone(); - let slots = Network::Devnet.isd_llmq_type().active_quorum_count() as usize; + let served = LLMQType::Llmqtype60_75; + let configured = LLMQType::LlmqtypeDevnetDIP0024; + let slots = configured.active_quorum_count() as usize; assert!(slots < cycle.len(), "the mainnet cycle has more slots than a devnet one"); - // Index 23 signs the lock; the other kept slots only fill the count. - let mut partial = BTreeMap::from([(23, cycle[&23].clone())]); - for (index, quorum) in cycle { - if partial.len() == slots { - break; - } - partial.insert(index, quorum); - } - let mut engine = TestEngine::empty(Network::Devnet); - engine.rotated_quorums_per_cycle.insert(lock.cyclehash, partial); + let partial: BTreeMap<_, _> = cycle.clone().into_iter().take(slots).collect(); - let mut forged = lock.clone(); - forged.signature = BLSSignature::from([1; 96]); - assert!(VerifiedInstantLock::verify(&forged, Some(&engine)).unwrap().is_none()); - assert!(VerifiedInstantLock::verify(&lock, Some(&engine)).unwrap().is_some()); + assert_eq!(instant_send_cycle_completeness(&partial, configured, true), Some(false)); + assert_eq!(instant_send_cycle_completeness(&partial, configured, false), None); + assert_eq!(instant_send_cycle_completeness(&cycle, served, false), Some(true)); + assert_eq!(instant_send_cycle_completeness(&partial, served, false), Some(false)); } } From 8b1e686126cc70be9e5febf789609216ad4a9fdd Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:10:36 +0000 Subject: [PATCH 22/38] fix(dash-spv): reject a malformed InstantLock before hashing it The pending-queue dedupe hashed every incoming lock first, so an oversized lock was serialized in full before the input bound dropped it. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sync/instantsend/manager.rs | 8 +++++++- dash-spv/src/validation/mod.rs | 1 + 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/dash-spv/src/sync/instantsend/manager.rs b/dash-spv/src/sync/instantsend/manager.rs index a591baf64..76255b572 100644 --- a/dash-spv/src/sync/instantsend/manager.rs +++ b/dash-spv/src/sync/instantsend/manager.rs @@ -18,7 +18,7 @@ use tokio::sync::RwLock; use crate::error::SyncResult; use crate::sync::{InstantSendProgress, SyncEvent, SyncState}; -use crate::validation::VerifiedInstantLock; +use crate::validation::{InstantLockStructureValidator, Validator, VerifiedInstantLock}; /// Maximum number of pending InstantLocks awaiting validation. const MAX_PENDING_INSTANTLOCKS: usize = 500; @@ -163,6 +163,12 @@ impl InstantSendManager { tracing::debug!("Already have a verified InstantLock for txid {}", txid); return Ok(vec![]); } + // Checked before hashing, so an oversized lock is dropped without serializing it. + if let Err(e) = InstantLockStructureValidator.validate(instantlock) { + tracing::warn!("Malformed InstantLock for txid {}: {}", txid, e); + self.progress.add_invalid(1); + return Ok(vec![]); + } let hash = lock_hash(instantlock); if self.pending_instantlocks.iter().any(|pending| pending.hash == hash) { tracing::debug!("The same InstantLock for txid {} is already pending", txid); diff --git a/dash-spv/src/validation/mod.rs b/dash-spv/src/validation/mod.rs index 803873ef1..9a1b245fc 100644 --- a/dash-spv/src/validation/mod.rs +++ b/dash-spv/src/validation/mod.rs @@ -11,6 +11,7 @@ pub use block::BlockValidator; pub use chainlock::ChainLockValidator; pub use filter::{FilterValidationInput, FilterValidator}; pub use header::BlockHeaderValidator; +pub(crate) use instantlock::InstantLockStructureValidator; pub use instantlock::{InstantLockVerificationError, VerifiedInstantLock}; pub use masternode_list::MasternodeListValidator; From 18c8d78b5b7c628ed0626754d4257cd271cf2788 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:09:47 +0000 Subject: [PATCH 23/38] refactor(dash-spv): drop the unused `rotated_quorums_of_cycle` query The InstantSend path reads cycles through `instant_send_cycle`, which left the raw query to tests only and failed the release clippy build. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sml_engine.rs | 8 -------- dash-spv/src/validation/instantlock.rs | 4 ++-- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/dash-spv/src/sml_engine.rs b/dash-spv/src/sml_engine.rs index c36d8fc3a..76f7d9371 100644 --- a/dash-spv/src/sml_engine.rs +++ b/dash-spv/src/sml_engine.rs @@ -461,14 +461,6 @@ impl MasternodeListEngine { self.masternode_lists.last_key_value().map(|(_, list)| list) } - /// The rotated quorums of the cycle `cycle_hash`, by quorum index. - pub fn rotated_quorums_of_cycle( - &self, - cycle_hash: &BlockHash, - ) -> Option<&BTreeMap> { - self.rotated_quorums_per_cycle.get(cycle_hash) - } - /// The cycle `cycle_hash` when every quorum of it is verified and of a type that /// signs this network's InstantSend locks. pub(crate) fn instant_send_cycle( diff --git a/dash-spv/src/validation/instantlock.rs b/dash-spv/src/validation/instantlock.rs index 74095ba05..b5bc99ace 100644 --- a/dash-spv/src/validation/instantlock.rs +++ b/dash-spv/src/validation/instantlock.rs @@ -349,7 +349,7 @@ mod tests { let engine = TestEngine::mainnet_fixture(); let lock = mainnet_fixture_is_lock(); let validator = - InstantLockValidator::new(engine.rotated_quorums_of_cycle(&lock.cyclehash).unwrap()); + InstantLockValidator::new(&engine.rotated_quorums_per_cycle()[&lock.cyclehash]); let request_id = lock.request_id().expect("expected to make request id"); assert_eq!( @@ -377,7 +377,7 @@ mod tests { validator.validate_signature(&lock).expect("expected to verify is lock"); // Without its quorum index in the cycle, the lock cannot be resolved. - let mut quorums = engine.rotated_quorums_of_cycle(&lock.cyclehash).unwrap().clone(); + let mut quorums = engine.rotated_quorums_per_cycle()[&lock.cyclehash].clone(); quorums.remove(&23); match InstantLockValidator::new(&quorums).signing_quorum(&lock) { Err(MessageVerificationError::QuorumIndexNotFound(23, hash)) => { From 6f206d482d38def57b866f9dae1a6e98f84d25a9 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:22:49 +0000 Subject: [PATCH 24/38] test(dash-spv): import test types instead of writing full paths Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sync/mempool/sync_manager.rs | 9 +++++---- dash-spv/src/validation/instantlock.rs | 24 +++++++++++------------ 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/dash-spv/src/sync/mempool/sync_manager.rs b/dash-spv/src/sync/mempool/sync_manager.rs index 45a77d22b..9e6a1aad9 100644 --- a/dash-spv/src/sync/mempool/sync_manager.rs +++ b/dash-spv/src/sync/mempool/sync_manager.rs @@ -193,6 +193,7 @@ mod tests { use key_wallet_manager::test_utils::MockWallet; use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; + use test_case::test_case; use tokio::sync::RwLock; fn create_test_manager() -> (MempoolManager, Arc) { @@ -641,10 +642,10 @@ mod tests { )); } - #[test_case::test_case(true, false; "known pending")] - #[test_case::test_case(true, true; "known uncertain")] - #[test_case::test_case(false, false; "early pending")] - #[test_case::test_case(false, true; "early uncertain")] + #[test_case(true, false; "known pending")] + #[test_case(true, true; "known uncertain")] + #[test_case(false, false; "early pending")] + #[test_case(false, true; "early uncertain")] #[tokio::test] async fn should_accept_broadcast_on_verified_instant_lock(known: bool, uncertain: bool) { let (mut manager, network) = create_test_manager(); diff --git a/dash-spv/src/validation/instantlock.rs b/dash-spv/src/validation/instantlock.rs index b5bc99ace..a35363841 100644 --- a/dash-spv/src/validation/instantlock.rs +++ b/dash-spv/src/validation/instantlock.rs @@ -239,8 +239,10 @@ impl<'a> InstantLockValidator<'a> { mod tests { use super::*; use crate::sml_engine::test_support::{mainnet_fixture_is_lock, TestEngine}; + use crate::test_utils::MockHeaderStorage; + use dashcore::bls_sig_utils::BLSSignature; use dashcore::sml::llmq_type::LLMQType; - use dashcore::QuorumHash; + use dashcore::{BlockHash, OutPoint, QuorumHash, ScriptBuf, TxIn, TxOut}; use hex_conservative::DisplayHex; use test_case::test_case; @@ -248,19 +250,17 @@ mod tests { fn should_authenticate_stored_lock_only_with_available_cycle() { let engine = TestEngine::mainnet_fixture(); let lock = mainnet_fixture_is_lock(); - assert!(VerifiedInstantLock::verify::(&lock, None,) - .unwrap() - .is_none()); - let empty = TestEngine::empty(dashcore::Network::Mainnet); + assert!(VerifiedInstantLock::verify::(&lock, None,).unwrap().is_none()); + let empty = TestEngine::empty(Network::Mainnet); assert!(VerifiedInstantLock::verify(&lock, Some(&empty)).unwrap().is_none()); let verified = VerifiedInstantLock::verify(&lock, Some(&engine)).unwrap().unwrap(); assert_eq!(verified.txid(), lock.txid); assert_eq!(verified.instant_lock(), &lock); let mut unknown_cycle = lock.clone(); - unknown_cycle.cyclehash = dashcore::BlockHash::all_zeros(); + unknown_cycle.cyclehash = BlockHash::all_zeros(); assert!(VerifiedInstantLock::verify(&unknown_cycle, Some(&engine)).unwrap().is_none()); let mut invalid = lock.clone(); - invalid.txid = dashcore::Txid::from_byte_array([7; 32]); + invalid.txid = Txid::from_byte_array([7; 32]); assert!(matches!( VerifiedInstantLock::verify(&invalid, Some(&engine)), Err(InstantLockVerificationError::InvalidSignature(_)) @@ -272,7 +272,7 @@ mod tests { Err(InstantLockVerificationError::InvalidSignature(_)) )); let mut changed_signature = lock.clone(); - changed_signature.signature = dashcore::bls_sig_utils::BLSSignature::from([1; 96]); + changed_signature.signature = BLSSignature::from([1; 96]); assert!(matches!( VerifiedInstantLock::verify(&changed_signature, Some(&engine)), Err(InstantLockVerificationError::InvalidSignature(_)) @@ -290,14 +290,14 @@ mod tests { let transaction = Transaction { version: 1, lock_time: 0, - input: vec![dashcore::TxIn { - previous_output: dashcore::OutPoint::new(Txid::from_byte_array([3; 32]), 0), + input: vec![TxIn { + previous_output: OutPoint::new(Txid::from_byte_array([3; 32]), 0), ..Default::default() }], output: vec![ - dashcore::TxOut { + TxOut { value: u64::MAX, - script_pubkey: dashcore::ScriptBuf::new(), + script_pubkey: ScriptBuf::new(), }; 2 ], From 20bccb136f3c37cc6d22f5d7a036e2ea488f3c98 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 10 Nov 2026 16:28:47 +0000 Subject: [PATCH 25/38] test(key-wallet): bind each input to its own funding output Covers `verify_input_authorization` on a two-input transaction signed by two owners: each input verifies only against its own prevout, a change to one input revokes the other input's SIGHASH_ALL authorization, and a signature does not follow its input to another position. The existing tests only exercised input 0 of single-input transactions. Co-Authored-By: Claude Fable 5.2 --- .../spend_authorization.rs | 75 ++++++++++++++++++- 1 file changed, 73 insertions(+), 2 deletions(-) diff --git a/key-wallet/src/transaction_checking/spend_authorization.rs b/key-wallet/src/transaction_checking/spend_authorization.rs index 41ae93455..cac69b190 100644 --- a/key-wallet/src/transaction_checking/spend_authorization.rs +++ b/key-wallet/src/transaction_checking/spend_authorization.rs @@ -140,18 +140,89 @@ mod tests { 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(0, &prevout.script_pubkey, u32::from(mode)) + .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[0].script_sig = Builder::new() + 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] { From 94fb8b518259c5bec8d6b139fb0090e80fd8c2e2 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 10 Nov 2026 16:28:47 +0000 Subject: [PATCH 26/38] test(dash-spv): reproduce unverified locks evicting a verified one Fails on this branch. `InstantSendManager` still caches an entry for every lock awaiting quorum data, although only verified entries deduplicate. `MAX_CACHE_SIZE` such locks evict the oldest verified entry, so the next announcement of that lock is verified and emitted as `InstantLockReceived` a second time. Co-Authored-By: Claude Fable 5.2 --- dash-spv/src/sync/instantsend/manager.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/dash-spv/src/sync/instantsend/manager.rs b/dash-spv/src/sync/instantsend/manager.rs index 76255b572..6584b4d7e 100644 --- a/dash-spv/src/sync/instantsend/manager.rs +++ b/dash-spv/src/sync/instantsend/manager.rs @@ -689,6 +689,29 @@ mod tests { assert_eq!(manager.state(), SyncState::Synced); } + /// Locks awaiting quorum data settle nothing, so they must not push a verified + /// lock out of the cache: its next announcement would be verified and emitted again. + #[tokio::test] + async fn should_keep_a_verified_lock_settled_while_unverified_locks_fill_the_cache() { + let mut manager = + InstantSendManager::new(Arc::new(RwLock::new(TestEngine::mainnet_fixture()))); + let genuine = mainnet_fixture_is_lock(); + let events = manager.process_instantlock(&genuine).await.unwrap(); + assert!(matches!(events.as_slice(), [SyncEvent::InstantLockReceived { .. }])); + + for i in 0..MAX_CACHE_SIZE { + let mut txid = [0xee; 32]; + txid[0..4].copy_from_slice(&(i as u32).to_le_bytes()); + let mut unverifiable = create_test_instantlock(Txid::from_byte_array(txid)); + unverifiable.cyclehash = CycleHash::from_byte_array([7; 32]); + assert!(manager.process_instantlock(&unverifiable).await.unwrap().is_empty()); + } + + let events = manager.process_instantlock(&genuine).await.unwrap(); + assert!(events.is_empty(), "the verified lock was emitted a second time: {events:?}"); + assert_eq!(manager.progress.valid(), 1); + } + #[tokio::test] async fn test_instantsend_pending_queue() { let mut manager = create_test_manager(); From 1e960df2a0f47576a5776c4d9fc543a16fbb39a2 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:38:59 +0000 Subject: [PATCH 27/38] fix(dash-spv): cache only verified InstantLock txids Only a verified entry settles a txid, yet `InstantSendManager` still cached an entry for every lock awaiting quorum data. `MAX_CACHE_SIZE` such locks evicted the oldest verified entry, so the next announcement of that lock was verified again and emitted as a second `InstantLockReceived`. `validate_pending` also lost the verified txid when its unverified entry had been evicted. The cache now holds only verified txids, recorded both on direct verification and when a pending lock verifies. Disconnect clears just the pending queue. The manager tests import `Network` and `MAX_BLOCK_SIZE` instead of writing full paths. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sync/instantsend/manager.rs | 118 +++++++----------- dash-spv/src/sync/instantsend/sync_manager.rs | 5 +- 2 files changed, 48 insertions(+), 75 deletions(-) diff --git a/dash-spv/src/sync/instantsend/manager.rs b/dash-spv/src/sync/instantsend/manager.rs index 6584b4d7e..7509e0483 100644 --- a/dash-spv/src/sync/instantsend/manager.rs +++ b/dash-spv/src/sync/instantsend/manager.rs @@ -23,10 +23,10 @@ use crate::validation::{InstantLockStructureValidator, Validator, VerifiedInstan /// Maximum number of pending InstantLocks awaiting validation. const MAX_PENDING_INSTANTLOCKS: usize = 500; -/// Maximum number of InstantLocks to cache. +/// Maximum number of verified txids to cache. const MAX_CACHE_SIZE: usize = 5000; -/// TTL for cached InstantLocks (1 hour). +/// TTL for cached verified txids (1 hour). const CACHE_TTL: Duration = Duration::from_secs(3600); /// How long a pending InstantLock is retained while awaiting the quorum data @@ -36,15 +36,6 @@ const CACHE_TTL: Duration = Duration::from_secs(3600); /// would overrun long before an hour elapsed during a fresh sync. const PENDING_TTL: Duration = Duration::from_secs(3600); -/// Entry in the InstantLock cache. -#[derive(Debug, Clone)] -pub struct InstantLockEntry { - /// When the InstantLock was received. - pub received_at: SystemTime, - /// Whether the BLS signature was validated. - pub validated: bool, -} - /// The hash of the serialized lock, as its inventory announces it. fn lock_hash(instant_lock: &InstantLock) -> InstantSendLockHash { InstantSendLockHash::from_raw_hash(sha256d::Hash::hash(&encode::serialize(instant_lock))) @@ -121,8 +112,9 @@ pub struct InstantSendManager { pub(super) progress: InstantSendProgress, /// Shared Masternode list engine. engine: Arc>>, - /// InstantLocks indexed by txid. - instantlocks: HashMap, + /// When each txid's lock verified. Only verified locks are cached, so locks that + /// wait for quorum data cannot evict them. + verified_txids: HashMap, /// Pending InstantLocks awaiting the quorum data required to verify them. pub(super) pending_instantlocks: Vec, /// Highest masternode-list height at which every pending InstantLock has @@ -142,7 +134,7 @@ impl InstantSendManager { Self { progress: InstantSendProgress::default(), engine, - instantlocks: HashMap::new(), + verified_txids: HashMap::new(), pending_instantlocks: Vec::new(), last_validated_engine_height: None, } @@ -159,7 +151,7 @@ impl InstantSendManager { // Only a verified lock settles its txid: an unverified one, possibly forged, // must not shadow the genuine lock for the same transaction. - if self.instantlocks.get(&txid).is_some_and(|entry| entry.validated) { + if self.verified_txids.contains_key(&txid) { tracing::debug!("Already have a verified InstantLock for txid {}", txid); return Ok(vec![]); } @@ -204,13 +196,9 @@ impl InstantSendManager { self.queue_pending(PendingInstantLock::new(instantlock.clone(), hash)); } self.progress.update_pending(self.pending_instantlocks.len()); - - // Store in cache - let entry = InstantLockEntry { - received_at: SystemTime::now(), - validated: verified.is_some(), - }; - self.store_instantlock(txid, entry); + if verified.is_some() { + self.store_verified(txid); + } Ok(verified .map(|instant_lock| SyncEvent::InstantLockReceived { @@ -235,16 +223,18 @@ impl InstantSendManager { self.pending_instantlocks.push(pending); } - /// Store an InstantLock in the cache. - fn store_instantlock(&mut self, txid: Txid, entry: InstantLockEntry) { - self.instantlocks.insert(txid, entry); + /// Records that `txid`'s lock verified, evicting the oldest record past [`MAX_CACHE_SIZE`]. + fn store_verified(&mut self, txid: Txid) { + self.verified_txids.insert(txid, SystemTime::now()); - // Enforce cache limit by removing oldest - if self.instantlocks.len() > MAX_CACHE_SIZE { - let oldest = - self.instantlocks.iter().min_by_key(|(_, e)| e.received_at).map(|(k, _)| *k); - if let Some(key) = oldest { - self.instantlocks.remove(&key); + if self.verified_txids.len() > MAX_CACHE_SIZE { + let oldest = self + .verified_txids + .iter() + .min_by_key(|(_, verified_at)| **verified_at) + .map(|(txid, _)| *txid); + if let Some(txid) = oldest { + self.verified_txids.remove(&txid); } } } @@ -295,9 +285,7 @@ impl InstantSendManager { Ok(Some(instant_lock)) => { self.progress.add_valid(1); validated_txids.insert(txid); - if let Some(entry) = self.instantlocks.get_mut(&txid) { - entry.validated = true; - } + self.store_verified(txid); events.push(SyncEvent::InstantLockReceived { instant_lock, }); @@ -325,19 +313,17 @@ impl InstantSendManager { /// Prune old entries from the cache. pub(super) fn prune_old_entries(&mut self) { let now = SystemTime::now(); - self.instantlocks.retain(|_, entry| { - now.duration_since(entry.received_at).map(|d| d < CACHE_TTL).unwrap_or(true) + self.verified_txids.retain(|_, verified_at| { + now.duration_since(*verified_at).map(|d| d < CACHE_TTL).unwrap_or(true) }); } - /// Drop cached InstantLock entries that were never BLS-validated, and clear - /// the queued locks that fed them. + /// Drop the locks still waiting for quorum data. /// /// Called on disconnect, so a lock re-announced after reconnect is processed - /// fresh. Validated entries are kept — their locks are already final. - pub(super) fn clear_unvalidated_on_disconnect(&mut self) { + /// fresh. Verified txids are kept, since their locks are already final. + pub(super) fn clear_pending_on_disconnect(&mut self) { self.pending_instantlocks.clear(); - self.instantlocks.retain(|_, entry| entry.validated); self.progress.update_pending(0); } @@ -391,7 +377,7 @@ impl std::fmt::Debug for InstantSendManager { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("InstantSendManager") .field("progress", &self.progress) - .field("cached", &self.instantlocks.len()) + .field("cached", &self.verified_txids.len()) .field("pending", &self.pending_instantlocks.len()) .finish() } @@ -404,9 +390,10 @@ mod tests { use crate::sync::{ManagerIdentifier, SyncManager, SyncManagerProgress, SyncState}; use crate::test_utils::MockHeaderStorage; use dashcore::bls_sig_utils::BLSSignature; + use dashcore::constants::MAX_BLOCK_SIZE; use dashcore::hash_types::CycleHash; use dashcore::sml::masternode_list::MasternodeList; - use dashcore::{BlockHash, OutPoint}; + use dashcore::{BlockHash, Network, OutPoint}; use test_case::test_case; /// Insert an empty masternode list at `height` so the shared engine reports a @@ -518,7 +505,7 @@ mod tests { #[test_case(|lock| lock.signature = BLSSignature::from([0; 96]); "zero signature")] #[test_case(|lock| lock.inputs.clear(); "no inputs")] #[test_case(|lock| lock.inputs[0].txid = Txid::all_zeros(); "null input txid")] - #[test_case(|lock| lock.inputs = vec![lock.inputs[0]; dashcore::constants::MAX_BLOCK_SIZE as usize / 41 + 1]; "too many inputs")] + #[test_case(|lock| lock.inputs = vec![lock.inputs[0]; MAX_BLOCK_SIZE as usize / 41 + 1]; "too many inputs")] #[tokio::test] async fn a_malformed_lock_of_an_unknown_cycle_is_dropped(malform: fn(&mut InstantLock)) { let mut manager = create_test_manager(); @@ -530,7 +517,7 @@ mod tests { assert!(events.is_empty(), "no InstantLockReceived for a malformed lock"); assert_eq!(manager.pending_count(), 0, "a malformed lock is not kept pending"); - assert!(manager.instantlocks.is_empty(), "a malformed lock is not cached"); + assert!(manager.verified_txids.is_empty(), "a malformed lock is not cached"); assert_eq!(manager.progress.invalid(), 1); // Not cached, so the well-formed lock for the transaction still gets in. @@ -576,7 +563,7 @@ mod tests { assert!(manager.process_instantlock(&forged).await.unwrap().is_empty()); assert_eq!(manager.pending_count(), 0); - assert!(manager.instantlocks.is_empty(), "a rejected lock is not cached"); + assert!(manager.verified_txids.is_empty(), "a rejected lock is not cached"); assert_eq!(manager.progress.invalid(), 1); let events = manager.process_instantlock(&genuine).await.unwrap(); @@ -586,9 +573,8 @@ mod tests { /// Once one lock for a txid verifies, its other pending locks never emit. #[tokio::test] async fn should_drop_other_pending_locks_of_a_txid_once_one_verifies() { - let mut manager = InstantSendManager::new(Arc::new(RwLock::new(TestEngine::empty( - dashcore::Network::Mainnet, - )))); + let mut manager = + InstantSendManager::new(Arc::new(RwLock::new(TestEngine::empty(Network::Mainnet)))); let genuine = mainnet_fixture_is_lock(); let mut other_cycle = genuine.clone(); other_cycle.cyclehash = CycleHash::from_byte_array([7; 32]); @@ -614,9 +600,8 @@ mod tests { /// an event, and the drained queue lets the manager leave `Syncing`. #[tokio::test] async fn should_drop_pending_lock_refuted_once_its_cycle_completes() { - let mut manager = InstantSendManager::new(Arc::new(RwLock::new(TestEngine::empty( - dashcore::Network::Mainnet, - )))); + let mut manager = + InstantSendManager::new(Arc::new(RwLock::new(TestEngine::empty(Network::Mainnet)))); manager.set_state(SyncState::Syncing); let genuine = mainnet_fixture_is_lock(); let mut forged = genuine.clone(); @@ -649,9 +634,8 @@ mod tests { /// it emits nothing and leaves no pending entry. #[tokio::test] async fn should_supersede_locks_queued_after_the_verified_lock_of_a_txid() { - let mut manager = InstantSendManager::new(Arc::new(RwLock::new(TestEngine::empty( - dashcore::Network::Mainnet, - )))); + let mut manager = + InstantSendManager::new(Arc::new(RwLock::new(TestEngine::empty(Network::Mainnet)))); let genuine = mainnet_fixture_is_lock(); let mut forged = genuine.clone(); forged.signature = BLSSignature::from([1; 96]); @@ -752,29 +736,22 @@ mod tests { let islock = create_test_instantlock(txid); let _ = manager.process_instantlock(&islock).await.unwrap(); - // Should be retrievable by txid - assert!(manager.instantlocks.contains_key(&txid)); - - // Unknown txid - let unknown = Txid::from_byte_array([2u8; 32]); - assert!(!manager.instantlocks.contains_key(&unknown)); + // A lock awaiting quorum data is queued, not recorded as verified. + assert_eq!(manager.pending_count(), 1); + assert!(!manager.verified_txids.contains_key(&txid)); } #[tokio::test] async fn test_instantsend_cache_limit() { let mut manager = create_test_manager(); - // Add more than MAX_CACHE_SIZE instantlocks for i in 0..MAX_CACHE_SIZE + 10 { let mut bytes = [0u8; 32]; bytes[0..4].copy_from_slice(&(i as u32).to_le_bytes()); - let txid = Txid::from_byte_array(bytes); - let islock = create_test_instantlock(txid); - let _ = manager.process_instantlock(&islock).await.unwrap(); + manager.store_verified(Txid::from_byte_array(bytes)); } - // Should be capped at MAX_CACHE_SIZE - assert!(manager.instantlocks.len() <= MAX_CACHE_SIZE); + assert_eq!(manager.verified_txids.len(), MAX_CACHE_SIZE); } /// A queued InstantLock must be re-validated by `tick` as soon as the @@ -911,16 +888,13 @@ mod tests { let txid = Txid::from_byte_array([5u8; 32]); - // First announcement: the empty engine can't verify it, so it is queued - // and cached as an unvalidated entry. + // First announcement: the empty engine can't verify it, so it is queued. manager.process_instantlock(&create_test_instantlock(txid)).await.unwrap(); assert_eq!(manager.pending_count(), 1); - assert!(manager.instantlocks.contains_key(&txid)); - // Disconnect must clear the queue AND the unvalidated cache entry. + // Disconnect must clear the queue. manager.on_disconnect(); assert_eq!(manager.pending_count(), 0); - assert!(!manager.instantlocks.contains_key(&txid)); // Re-announcement of the same txid is processed fresh, not deduped away. manager.process_instantlock(&create_test_instantlock(txid)).await.unwrap(); diff --git a/dash-spv/src/sync/instantsend/sync_manager.rs b/dash-spv/src/sync/instantsend/sync_manager.rs index b5cea2989..3239a5ae3 100644 --- a/dash-spv/src/sync/instantsend/sync_manager.rs +++ b/dash-spv/src/sync/instantsend/sync_manager.rs @@ -30,9 +30,8 @@ impl SyncManager for InstantSendManager { } fn on_disconnect(&mut self) { - // Clear the queue so a lock re-announced after reconnect is processed - // fresh, and drop unvalidated cache entries because they are not final. - self.clear_unvalidated_on_disconnect(); + // Clear the queue so a lock re-announced after reconnect is processed fresh. + self.clear_pending_on_disconnect(); // Nothing is queued anymore, so the height at which we last validated is // meaningless; reset it so re-validation runs again after reconnect. self.last_validated_engine_height = None; From 8137008f59197b29d8431196ce7546c4945886a6 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:39:08 +0000 Subject: [PATCH 28/38] refactor(dash-spv): import types and narrow `InstantLockValidator` Replaces full paths with imports in the code this branch adds, and makes `InstantLockValidator` private, since only `VerifiedInstantLock::verify` uses it. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/client/queries.rs | 3 ++- dash-spv/src/sync/mempool/sync_manager.rs | 10 +++++----- dash-spv/src/test_utils/instant_lock.rs | 3 ++- dash-spv/src/validation/instantlock.rs | 4 ++-- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/dash-spv/src/client/queries.rs b/dash-spv/src/client/queries.rs index d1dfc4b9a..660271e3c 100644 --- a/dash-spv/src/client/queries.rs +++ b/dash-spv/src/client/queries.rs @@ -17,6 +17,7 @@ use dashcore::sml::quorum_entry::qualified_quorum_entry::QualifiedQuorumEntry; use dashcore::transaction::special_transaction::coinbase::CoinbasePayload; use dashcore::{InstantLock, QuorumHash}; use key_wallet_manager::WalletInterface; +use std::result; use std::sync::Arc; use tokio::sync::RwLock; @@ -54,7 +55,7 @@ impl DashSpvClient { pub async fn verify_instant_lock( &self, instant_lock: &InstantLock, - ) -> std::result::Result, InstantLockVerificationError> { + ) -> result::Result, InstantLockVerificationError> { let Some(engine) = &self.masternode_engine else { return VerifiedInstantLock::verify::(instant_lock, None); }; diff --git a/dash-spv/src/sync/mempool/sync_manager.rs b/dash-spv/src/sync/mempool/sync_manager.rs index 9e6a1aad9..2de84d6d0 100644 --- a/dash-spv/src/sync/mempool/sync_manager.rs +++ b/dash-spv/src/sync/mempool/sync_manager.rs @@ -189,7 +189,7 @@ mod tests { use crate::test_utils::{test_socket_address, MockNetworkManager}; use crate::types::UnconfirmedTransaction; use crate::validation::VerifiedInstantLock; - use dashcore::{Amount, InstantLock}; + use dashcore::{Amount, InstantLock, Transaction}; use key_wallet_manager::test_utils::MockWallet; use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; @@ -358,7 +358,7 @@ mod tests { // Add transactions to mempool let mut txids = Vec::new(); for i in 0..2u32 { - let tx = dashcore::Transaction { + let tx = Transaction { version: 1, lock_time: i, input: vec![], @@ -406,7 +406,7 @@ mod tests { manager.handle_sync_event(&sync, &network).await.unwrap(); // Add a transaction to mempool - let tx = dashcore::Transaction { + let tx = Transaction { version: 1, lock_time: 0, input: vec![], @@ -649,7 +649,7 @@ mod tests { #[tokio::test] async fn should_accept_broadcast_on_verified_instant_lock(known: bool, uncertain: bool) { let (mut manager, network) = create_test_manager(); - let tx = dashcore::Transaction { + let tx = Transaction { version: 1, lock_time: 0, input: vec![], @@ -1064,7 +1064,7 @@ mod tests { network_mock.clear_sent().await; // handle_tx with a relevant transaction should NOT eagerly rebuild - let tx = dashcore::Transaction { + let tx = Transaction { version: 1, lock_time: 0, input: vec![], diff --git a/dash-spv/src/test_utils/instant_lock.rs b/dash-spv/src/test_utils/instant_lock.rs index bd10bb497..d05c75838 100644 --- a/dash-spv/src/test_utils/instant_lock.rs +++ b/dash-spv/src/test_utils/instant_lock.rs @@ -1,6 +1,7 @@ //! Signed fixtures for consumers testing authenticated InstantSend replay. use std::collections::BTreeMap; +use std::io; use dashcore::bls_sig_utils::{BLSPublicKey, BLSSignature, BlsError, BlsScheme, BlsSkBytes}; use dashcore::hash_types::QuorumVVecHash; @@ -23,7 +24,7 @@ pub enum InstantLockFixtureError { Key(#[from] BlsError), /// The lock signing digest could not be encoded. #[error("cannot encode fixture signing digest: {0}")] - Encoding(#[from] std::io::Error), + Encoding(#[from] io::Error), } /// A lock signed by a random key of its own, and a synthetic quorum cycle for it. diff --git a/dash-spv/src/validation/instantlock.rs b/dash-spv/src/validation/instantlock.rs index a35363841..0ecfc9df7 100644 --- a/dash-spv/src/validation/instantlock.rs +++ b/dash-spv/src/validation/instantlock.rs @@ -158,7 +158,7 @@ impl Validator<&InstantLock> for InstantLockStructureValidator { /// Verifies an InstantLock's signature against the rotated quorums of its cycle. /// It does not check the lock's structure or the cycle's eligibility: use /// [`VerifiedInstantLock::verify`], which does both. -pub struct InstantLockValidator<'a> { +struct InstantLockValidator<'a> { /// The rotated quorums of the lock's cycle, by quorum index. cycle_quorums: &'a BTreeMap, } @@ -170,7 +170,7 @@ fn signature_error(error: MessageVerificationError) -> ValidationError { } impl<'a> InstantLockValidator<'a> { - pub fn new(cycle_quorums: &'a BTreeMap) -> Self { + fn new(cycle_quorums: &'a BTreeMap) -> Self { Self { cycle_quorums, } From a1828879cd25f42936ff7669cd9596a682a92d28 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 16 Nov 2026 06:37:16 +0000 Subject: [PATCH 29/38] test(dash-spv): adapt tests merged from `dev` to verified locks The restart test added on `dev` still passed the removed `validated` flag to `wait_for_instant_lock_received` and called the removed `rotated_quorums_of_cycle`. It now checks the stored cycle through `rotated_quorums_per_cycle`. The `sml_engine` test imports drop `qr_info_diffs`, which `dev` moved into the tests module, and the no longer used `WORK_DIFF_DEPTH`. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sml_engine.rs | 5 ++--- dash-spv/tests/dashd_masternode/tests_sync.rs | 12 ++++-------- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/dash-spv/src/sml_engine.rs b/dash-spv/src/sml_engine.rs index 4b56ea326..b273e27b0 100644 --- a/dash-spv/src/sml_engine.rs +++ b/dash-spv/src/sml_engine.rs @@ -1467,10 +1467,9 @@ pub(crate) mod test_support { mod tests { use super::test_support::{fixture_heights, mainnet_fixture_is_lock, quorum_entry, TestEngine}; use super::{ - build_cycle_quorum_map, instant_send_cycle_completeness, qr_info_diffs, - valid_coinbase_chain_lock, + build_cycle_quorum_map, instant_send_cycle_completeness, valid_coinbase_chain_lock, }; - use super::{FeedError, MasternodeListEngine, QRInfoFeedResult, WORK_DIFF_DEPTH}; + use super::{FeedError, MasternodeListEngine, QRInfoFeedResult}; use crate::error::{StorageError, StorageResult}; use crate::storage::{BlockHeaderStorage, BlockHeaderTip}; use crate::test_utils::MockHeaderStorage; diff --git a/dash-spv/tests/dashd_masternode/tests_sync.rs b/dash-spv/tests/dashd_masternode/tests_sync.rs index a05367c19..27b88394a 100644 --- a/dash-spv/tests/dashd_masternode/tests_sync.rs +++ b/dash-spv/tests/dashd_masternode/tests_sync.rs @@ -204,17 +204,13 @@ async fn test_masternode_list_sync_with_restart() { wait_for_masternode_sync(&mut client_handle.progress_receiver, SYNC_TIMEOUT).await; let second_height = second_mn_progress.current_height(); - let lock = wait_for_instant_lock_received( - &mut client_handle.sync_event_receiver, - txid, - true, - SYNC_TIMEOUT, - ) - .await; + let lock = + wait_for_instant_lock_received(&mut client_handle.sync_event_receiver, txid, SYNC_TIMEOUT) + .await; { let engine = client_handle.engine.read().await; assert!( - engine.rotated_quorums_of_cycle(&lock.cyclehash).is_some(), + engine.rotated_quorums_per_cycle().contains_key(&lock.cyclehash), "the lock is accepted against a stored cycle" ); assert_all_rotated_quorums_verified(&engine); From 514b9fc634cb199b41d689b664321c1e74131e12 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:06:09 +0000 Subject: [PATCH 30/38] refactor: hash InstantLocks with `InstantLock::hash` `dash-spv` computed the inventory hash of an InstantLock in two places: the `ISLock` arm of the network reply matcher and the InstantSend manager's dedupe. Both now call the new `InstantLock::hash` in `dashcore`. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/network/costs.rs | 4 +--- dash-spv/src/sync/instantsend/manager.rs | 11 ++--------- dash/src/ephemerealdata/instant_lock.rs | 10 +++++++++- 3 files changed, 12 insertions(+), 13 deletions(-) diff --git a/dash-spv/src/network/costs.rs b/dash-spv/src/network/costs.rs index 19b26ecae..94f04920e 100644 --- a/dash-spv/src/network/costs.rs +++ b/dash-spv/src/network/costs.rs @@ -90,9 +90,7 @@ impl Reply { NetworkMessage::CFHeaders(m) => Reply::CfHeaders(m.stop_hash), NetworkMessage::Block(block) => Reply::Block(block.block_hash()), NetworkMessage::Tx(tx) => Reply::Tx(tx.txid()), - NetworkMessage::ISLock(lock) => Reply::InstantLock(InstantSendLockHash::from_raw_hash( - sha256d::Hash::hash(&encode::serialize(lock)), - )), + NetworkMessage::ISLock(lock) => Reply::InstantLock(lock.hash()), NetworkMessage::CLSig(lock) => Reply::ChainLock(ChainLockHash::from_raw_hash( sha256d::Hash::hash(&encode::serialize(lock)), )), diff --git a/dash-spv/src/sync/instantsend/manager.rs b/dash-spv/src/sync/instantsend/manager.rs index 7509e0483..0db7ec870 100644 --- a/dash-spv/src/sync/instantsend/manager.rs +++ b/dash-spv/src/sync/instantsend/manager.rs @@ -9,11 +9,9 @@ use std::time::{Duration, Instant, SystemTime}; use crate::sml_engine::MasternodeListEngine; use crate::storage::BlockHeaderStorage; -use dashcore::consensus::encode; use dashcore::ephemerealdata::instant_lock::InstantLock; use dashcore::hash_types::InstantSendLockHash; use dashcore::Txid; -use dashcore_hashes::sha256d; use tokio::sync::RwLock; use crate::error::SyncResult; @@ -36,11 +34,6 @@ const CACHE_TTL: Duration = Duration::from_secs(3600); /// would overrun long before an hour elapsed during a fresh sync. const PENDING_TTL: Duration = Duration::from_secs(3600); -/// The hash of the serialized lock, as its inventory announces it. -fn lock_hash(instant_lock: &InstantLock) -> InstantSendLockHash { - InstantSendLockHash::from_raw_hash(sha256d::Hash::hash(&encode::serialize(instant_lock))) -} - /// Pending InstantLock awaiting the quorum data required to verify it. #[derive(Debug, Clone)] pub(super) struct PendingInstantLock { @@ -161,7 +154,7 @@ impl InstantSendManager { self.progress.add_invalid(1); return Ok(vec![]); } - let hash = lock_hash(instantlock); + let hash = instantlock.hash(); if self.pending_instantlocks.iter().any(|pending| pending.hash == hash) { tracing::debug!("The same InstantLock for txid {} is already pending", txid); return Ok(vec![]); @@ -417,7 +410,7 @@ mod tests { /// back-dating this field — see [`past_ttl`]. fn fresh_pending(txid: Txid) -> PendingInstantLock { let instant_lock = create_test_instantlock(txid); - let hash = lock_hash(&instant_lock); + let hash = instant_lock.hash(); PendingInstantLock::new(instant_lock, hash) } diff --git a/dash/src/ephemerealdata/instant_lock.rs b/dash/src/ephemerealdata/instant_lock.rs index 6ea96abf8..941d034f4 100644 --- a/dash/src/ephemerealdata/instant_lock.rs +++ b/dash/src/ephemerealdata/instant_lock.rs @@ -11,7 +11,10 @@ pub use std::vec::Vec; use crate::bls_sig_utils::BLSSignature; use crate::consensus::Encodable; -use crate::hash_types::{CycleHash, QuorumSigningRequestId, QuorumSigningSignId}; +use crate::consensus::encode::serialize; +use crate::hash_types::{ + CycleHash, InstantSendLockHash, QuorumSigningRequestId, QuorumSigningSignId, +}; use crate::internal_macros::impl_consensus_encoding; use crate::sml::llmq_type::LLMQType; use crate::{OutPoint, QuorumHash, Txid, VarInt, io}; @@ -52,6 +55,11 @@ impl Default for InstantLock { } impl InstantLock { + /// Returns the hash peers use to announce and request this lock. + pub fn hash(&self) -> InstantSendLockHash { + InstantSendLockHash::from_raw_hash(sha256d::Hash::hash(&serialize(self))) + } + /// Returns quorum signing request ID pub fn request_id(&self) -> Result { let mut engine = sha256d::Hash::engine(); From 2b7cbd890089a2a832701de72756946609a95fb5 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 31/38] refactor(key-wallet): move spend authorization to its own PR `verify_input_authorization` shares no code with the InstantLock changes and nothing in the workspace calls it yet. It moves to its own `feat(key-wallet)` PR, together with the `thiserror` dependency it needs. 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 deletions(-) delete mode 100644 key-wallet/src/transaction_checking/spend_authorization.rs diff --git a/key-wallet/Cargo.toml b/key-wallet/Cargo.toml index c9140f522..4ce1d3615 100644 --- a/key-wallet/Cargo.toml +++ b/key-wallet/Cargo.toml @@ -72,7 +72,6 @@ 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 cd08380da..0ccb2048d 100644 --- a/key-wallet/src/transaction_checking/mod.rs +++ b/key-wallet/src/transaction_checking/mod.rs @@ -17,6 +17,3 @@ 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 deleted file mode 100644 index cac69b190..000000000 --- a/key-wallet/src/transaction_checking/spend_authorization.rs +++ /dev/null @@ -1,403 +0,0 @@ -//! 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 f1237a68096b97ad0eb66b16e91cf2921eac0039 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:39:55 +0000 Subject: [PATCH 32/38] test(dash-spv): reach the uncertain broadcast state by its timeout `should_accept_broadcast_on_verified_instant_lock` set the broadcast status by hand, a state the test never reached through the manager. The test moves next to `process_instant_send` in the mempool manager tests and reaches `Uncertain` through `expire_broadcasts_at` at the acceptance timeout. The known pending case is dropped: `test_mark_instant_send_emits_status_change` already covers it. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sync/mempool/manager.rs | 42 ++++++++++++++++ dash-spv/src/sync/mempool/sync_manager.rs | 61 +---------------------- 2 files changed, 43 insertions(+), 60 deletions(-) diff --git a/dash-spv/src/sync/mempool/manager.rs b/dash-spv/src/sync/mempool/manager.rs index cf48923e1..d7f17a043 100644 --- a/dash-spv/src/sync/mempool/manager.rs +++ b/dash-spv/src/sync/mempool/manager.rs @@ -862,6 +862,7 @@ mod tests { use crate::sync::SyncState; use crate::test_utils::{test_socket_address, MockNetworkManager}; + use test_case::test_case; fn dummy_instant_lock(txid: Txid) -> InstantLock { InstantLock { @@ -1988,6 +1989,47 @@ mod tests { ); } + #[test_case(true, true; "known uncertain")] + #[test_case(false, false; "early pending")] + #[test_case(false, true; "early uncertain")] + #[tokio::test] + async fn should_accept_broadcast_on_instant_lock(known: bool, uncertain: bool) { + let (mut manager, requests, _rx) = create_test_manager(); + let tx = test_transaction(42); + let txid = tx.txid(); + assert!(manager.start_broadcast(&tx, &requests).await.is_empty()); + if known { + manager.transactions.insert( + txid, + UnconfirmedTransaction::new(tx, Amount::from_sat(0), false, false, Vec::new(), 0), + ); + } + if uncertain { + let deadline = Instant::now() + BroadcastConfig::default().acceptance_timeout; + assert_eq!(manager.expire_broadcasts_at(deadline).len(), 1); + } + let lock = dummy_instant_lock(txid); + + let events = manager.process_instant_send(verified_lock(txid)).await; + + assert!(matches!( + events.as_slice(), + [SyncEvent::TransactionBroadcastResult { + txid: accepted, + result: BroadcastResult::Accepted { .. }, + }] if *accepted == txid + )); + assert!(!manager.broadcasts.contains_key(&txid)); + let processed = manager.wallet.read().await.processed_instant_locks.lock().await.clone(); + if known { + assert!(manager.transactions[&txid].is_instant_send); + assert_eq!(processed, vec![(txid, Some(lock))]); + } else { + assert_eq!(manager.pending_is_locks[&txid].0.instant_lock(), &lock); + assert!(processed.is_empty()); + } + } + #[tokio::test] async fn test_broadcast_seeds_acceptance_from_peer_relay() { let (mut manager, requests, _rx) = create_test_manager(); diff --git a/dash-spv/src/sync/mempool/sync_manager.rs b/dash-spv/src/sync/mempool/sync_manager.rs index 152e91f72..1e66c0a63 100644 --- a/dash-spv/src/sync/mempool/sync_manager.rs +++ b/dash-spv/src/sync/mempool/sync_manager.rs @@ -180,16 +180,13 @@ impl SyncManager for MempoolManager { #[cfg(test)] mod tests { use super::*; - use crate::sync::mempool::broadcast::{BroadcastResult, BroadcastStatus}; use crate::sync::BroadcastConfig; use crate::test_utils::{test_socket_address, MockNetworkManager}; - use crate::types::UnconfirmedTransaction; use crate::validation::VerifiedInstantLock; - use dashcore::{Amount, InstantLock, Transaction}; + use dashcore::Transaction; use key_wallet_manager::test_utils::MockWallet; use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; - use test_case::test_case; use tokio::sync::RwLock; fn create_test_manager() -> (MempoolManager, Arc) { @@ -638,62 +635,6 @@ mod tests { )); } - #[test_case(true, false; "known pending")] - #[test_case(true, true; "known uncertain")] - #[test_case(false, false; "early pending")] - #[test_case(false, true; "early uncertain")] - #[tokio::test] - async fn should_accept_broadcast_on_verified_instant_lock(known: bool, uncertain: bool) { - let (mut manager, network) = create_test_manager(); - let tx = Transaction { - version: 1, - lock_time: 0, - input: vec![], - output: vec![], - special_transaction_payload: None, - }; - let txid = tx.txid(); - assert!(manager.start_broadcast(&tx, &network).await.is_empty()); - if known { - manager.transactions.insert( - txid, - UnconfirmedTransaction::new(tx, Amount::from_sat(0), false, false, Vec::new(), 0), - ); - } - let status = if uncertain { - BroadcastStatus::Uncertain - } else { - BroadcastStatus::Pending - }; - manager.broadcasts.get_mut(&txid).unwrap().status = status; - let lock = InstantLock { - txid, - ..InstantLock::default() - }; - let event = SyncEvent::InstantLockReceived { - instant_lock: VerifiedInstantLock::assume_verified(lock.clone()), - }; - - let events = manager.handle_sync_event(&event, &network).await.unwrap(); - - assert!(matches!( - events.as_slice(), - [SyncEvent::TransactionBroadcastResult { - txid: accepted, - result: BroadcastResult::Accepted { .. }, - }] if *accepted == txid - )); - assert!(!manager.broadcasts.contains_key(&txid)); - let processed = manager.wallet.read().await.processed_instant_locks.lock().await.clone(); - if known { - assert!(manager.transactions.get(&txid).unwrap().is_instant_send); - assert_eq!(processed, vec![(txid, Some(lock))]); - } else { - assert_eq!(manager.pending_is_locks.get(&txid).unwrap().0.instant_lock(), &lock); - assert!(processed.is_empty()); - } - } - #[tokio::test] async fn test_peer_disconnect_removes_from_peers() { let (mut manager, network) = create_test_manager(); From 3ccc21a1c1829b4e86e75fc33056dbbe1f0548b2 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:41:15 +0000 Subject: [PATCH 33/38] fix(dash-spv): reject InstantLocks that repeat an input Dash Core's `InstantSendLock::TriviallyValid` drops a lock whose inputs are not unique. `InstantLockStructureValidator` accepted one, so a lock with a repeated input and an unknown cycle waited in the pending queue until it expired. The validator now rejects it right after the input count check. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/validation/instantlock.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/dash-spv/src/validation/instantlock.rs b/dash-spv/src/validation/instantlock.rs index 0ecfc9df7..0896e5ae2 100644 --- a/dash-spv/src/validation/instantlock.rs +++ b/dash-spv/src/validation/instantlock.rs @@ -1,4 +1,4 @@ -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashSet}; use dashcore::bls_sig_utils::BlsScheme; use dashcore::constants::MAX_BLOCK_SIZE; @@ -143,6 +143,13 @@ impl Validator<&InstantLock> for InstantLockStructureValidator { ))); } + let mut seen = HashSet::with_capacity(instant_lock.inputs.len()); + if let Some(idx) = instant_lock.inputs.iter().position(|input| !seen.insert(input)) { + return Err(ValidationError::InvalidInstantLock(format!( + "InstantLock input {idx} repeats an earlier input" + ))); + } + if let Some(idx) = instant_lock.inputs.iter().position(|input| input.txid == dashcore::Txid::all_zeros()) { @@ -325,7 +332,9 @@ mod tests { fn a_well_formed_lock_passes_the_structure_check() { assert!(InstantLockStructureValidator.validate(&InstantLock::dummy(0..3)).is_ok()); let mut largest = InstantLock::dummy(0..1); - largest.inputs = vec![largest.inputs[0]; MAX_INSTANT_LOCK_INPUTS]; + let txid = largest.inputs[0].txid; + largest.inputs = + (0..MAX_INSTANT_LOCK_INPUTS as u32).map(|vout| OutPoint::new(txid, vout)).collect(); assert!(InstantLockStructureValidator.validate(&largest).is_ok()); } @@ -334,6 +343,7 @@ mod tests { #[test_case(|lock| lock.txid = dashcore::Txid::all_zeros(), "transaction ID cannot be zero"; "null txid")] #[test_case(|lock| lock.inputs[1].txid = dashcore::Txid::all_zeros(), "input 1 has null transaction ID"; "null input txid")] #[test_case(|lock| lock.inputs = vec![lock.inputs[0]; MAX_INSTANT_LOCK_INPUTS + 1], "more than 48780 inputs"; "too many inputs")] + #[test_case(|lock| lock.inputs[2] = lock.inputs[0], "input 2 repeats an earlier input"; "repeated input")] fn a_malformed_lock_fails_the_structure_check(malform: fn(&mut InstantLock), reason: &str) { let mut is_lock = InstantLock::dummy(0..3); malform(&mut is_lock); From 358abcc4ea73be2c7921a5b92faf061cca5a05d3 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:35:34 +0000 Subject: [PATCH 34/38] feat(dashcore): list the inputs an InstantLock of a transaction carries `InstantLock::lock_inputs` derives them as Dash Core's `GetLockInputs` does. An asset unlock (Platform withdrawal) spends no inputs, so its lock carries one synthetic outpoint: the hash of the `plwdtx` prefix and the withdrawal index, at output 0. Every other transaction's lock carries its prevouts. `Transaction::dummy_asset_unlock` builds a withdrawal for tests. Co-Authored-By: Claude Opus 5.5 --- dash/src/ephemerealdata/instant_lock.rs | 41 ++++++++++++++++++++++++- dash/src/test_utils/transaction.rs | 34 +++++++++++++++++++- 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/dash/src/ephemerealdata/instant_lock.rs b/dash/src/ephemerealdata/instant_lock.rs index 941d034f4..0b0eb2f9c 100644 --- a/dash/src/ephemerealdata/instant_lock.rs +++ b/dash/src/ephemerealdata/instant_lock.rs @@ -17,9 +17,11 @@ use crate::hash_types::{ }; use crate::internal_macros::impl_consensus_encoding; use crate::sml::llmq_type::LLMQType; -use crate::{OutPoint, QuorumHash, Txid, VarInt, io}; +use crate::transaction::special_transaction::TransactionPayload; +use crate::{OutPoint, QuorumHash, Transaction, Txid, VarInt, io}; const IS_LOCK_REQUEST_ID_PREFIX: &str = "islock"; +const ASSET_UNLOCK_REQUEST_ID_PREFIX: &str = "plwdtx"; #[derive(Clone, Eq, PartialEq)] #[cfg_attr(feature = "bincode", derive(Encode, Decode))] @@ -55,6 +57,23 @@ impl Default for InstantLock { } impl InstantLock { + /// Returns the outpoints a lock of `transaction` lists, as Dash Core's `GetLockInputs` + /// derives them. An asset unlock spends no inputs, so its lock lists one outpoint + /// derived from the withdrawal index. + pub fn lock_inputs(transaction: &Transaction) -> Vec { + let Some(TransactionPayload::AssetUnlockPayloadType(payload)) = + &transaction.special_transaction_payload + else { + return transaction.input.iter().map(|input| input.previous_output).collect(); + }; + let mut engine = sha256d::Hash::engine(); + // The compact size of a length below 0xfd is that one byte. + engine.input(&[ASSET_UNLOCK_REQUEST_ID_PREFIX.len() as u8]); + engine.input(ASSET_UNLOCK_REQUEST_ID_PREFIX.as_bytes()); + engine.input(&payload.base.index.to_le_bytes()); + vec![OutPoint::new(Txid::from_raw_hash(engine.finalize()), 0)] + } + /// Returns the hash peers use to announce and request this lock. pub fn hash(&self) -> InstantSendLockHash { InstantSendLockHash::from_raw_hash(sha256d::Hash::hash(&serialize(self))) @@ -118,6 +137,26 @@ mod tests { use super::*; use crate::consensus::{deserialize, serialize}; use crate::internal_macros::hex; + use crate::{Address, Network}; + + #[test] + fn should_list_the_inputs_dash_core_locks() { + let address = Address::dummy(Network::Testnet, 0); + let transaction = Transaction::dummy(&address, 0..2, &[1]); + let prevouts: Vec = + transaction.input.iter().map(|input| input.previous_output).collect(); + assert_eq!(InstantLock::lock_inputs(&transaction), prevouts); + + // sha256d of the compact-size string "plwdtx" followed by index 7 as a u64. + let withdrawal_txid = Txid::from_slice(&hex!( + "938752a81b996801646ce07e4647fa3f536fabbc7d308b0a7647b75732a0ae58" + )) + .unwrap(); + assert_eq!( + InstantLock::lock_inputs(&Transaction::dummy_asset_unlock(&address, 7, 1)), + vec![OutPoint::new(withdrawal_txid, 0)] + ); + } #[test] pub fn should_decode_vec() { diff --git a/dash/src/test_utils/transaction.rs b/dash/src/test_utils/transaction.rs index dc370e22c..e60df3b98 100644 --- a/dash/src/test_utils/transaction.rs +++ b/dash/src/test_utils/transaction.rs @@ -6,12 +6,17 @@ use crate::hash_types::{ InputsHash, MerkleRootAssetUnlocks, MerkleRootMasternodeList, MerkleRootQuorums, }; use crate::sml::masternode_list_entry::MasternodeNetInfo; +use crate::transaction::special_transaction::asset_unlock::qualified_asset_unlock::AssetUnlockPayload; +use crate::transaction::special_transaction::asset_unlock::request_info::AssetUnlockRequestInfo; +use crate::transaction::special_transaction::asset_unlock::unqualified_asset_unlock::AssetUnlockBasePayload; use crate::transaction::special_transaction::coinbase::CoinbasePayload; use crate::transaction::special_transaction::provider_registration::{ ProviderMasternodeType, ProviderRegistrationPayload, }; use crate::transaction::special_transaction::{TransactionPayload, TransactionType}; -use crate::{Address, OutPoint, PubkeyHash, ScriptBuf, Transaction, TxIn, TxOut, Txid, Witness}; +use crate::{ + Address, OutPoint, PubkeyHash, QuorumHash, ScriptBuf, Transaction, TxIn, TxOut, Txid, Witness, +}; /// A special transaction type no Dash Core version assigns pub const UNASSIGNED_SPECIAL_TX_TYPE: u16 = 0xffff; @@ -28,6 +33,33 @@ impl Transaction { } } + /// Creates an asset unlock (Platform withdrawal) paying `value` to `address`. + pub fn dummy_asset_unlock(address: &Address, index: u64, value: u64) -> Transaction { + Transaction { + version: 3, + lock_time: 0, + input: Vec::new(), + output: vec![TxOut { + value, + script_pubkey: address.script_pubkey(), + }], + special_transaction_payload: Some(TransactionPayload::AssetUnlockPayloadType( + AssetUnlockPayload { + base: AssetUnlockBasePayload { + version: 1, + index, + fee: 0, + }, + request_info: AssetUnlockRequestInfo { + request_height: 0, + quorum_hash: QuorumHash::all_zeros(), + }, + quorum_sig: BLSSignature::from([0; 96]), + }, + )), + } + } + pub fn dummy( address: &Address, inputs_ids_range: Range, From 18f5471ca9e45272b16a9d31cba504e70144bf88 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:36:29 +0000 Subject: [PATCH 35/38] fix(dash-spv): bind a withdrawal's lock to its synthetic input `VerifiedInstantLock::matches_transaction` compared the lock's inputs with the transaction's prevouts. Dash Core locks an asset unlock, which has no inputs, with one synthetic outpoint derived from its withdrawal index, so a genuine lock of a Platform withdrawal never matched. The check and `InstantLockFixture::new` now take the expected inputs from `InstantLock::lock_inputs`. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/test_utils/instant_lock.rs | 4 ++-- dash-spv/src/validation/instantlock.rs | 25 ++++++++++++++++--------- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/dash-spv/src/test_utils/instant_lock.rs b/dash-spv/src/test_utils/instant_lock.rs index d05c75838..b8f5fda31 100644 --- a/dash-spv/src/test_utils/instant_lock.rs +++ b/dash-spv/src/test_utils/instant_lock.rs @@ -38,7 +38,7 @@ pub struct InstantLockFixture { } impl InstantLockFixture { - /// Signs the transaction's ID and ordered inputs with a quorum of `network`'s + /// Signs the transaction's ID and the inputs its lock carries with a quorum of `network`'s /// InstantSend quorum type. pub fn new( network: Network, @@ -51,7 +51,7 @@ impl InstantLockFixture { let quorum_hash = QuorumHash::from_byte_array([9; 32]); let mut instant_lock = InstantLock { version: 1, - inputs: transaction.input.iter().map(|input| input.previous_output).collect(), + inputs: InstantLock::lock_inputs(transaction), txid: transaction.txid(), cyclehash: BlockHash::from_byte_array([8; 32]), signature: BLSSignature::from([0; 96]), diff --git a/dash-spv/src/validation/instantlock.rs b/dash-spv/src/validation/instantlock.rs index 0896e5ae2..b0ce18f27 100644 --- a/dash-spv/src/validation/instantlock.rs +++ b/dash-spv/src/validation/instantlock.rs @@ -60,18 +60,14 @@ impl VerifiedInstantLock { self.instant_lock.txid } - /// Binds the evidence to the wallet's network, the complete transaction and its ordered inputs. + /// Binds the evidence to the wallet's network, the complete transaction and the ordered + /// inputs its lock carries, see [`InstantLock::lock_inputs`]. /// /// No wallet arithmetic or transaction consensus validation is performed. pub fn matches_transaction(&self, network: Network, transaction: &Transaction) -> bool { self.network == network && self.txid() == transaction.txid() - && self - .instant_lock - .inputs - .iter() - .copied() - .eq(transaction.input.iter().map(|input| input.previous_output)) + && self.instant_lock.inputs == InstantLock::lock_inputs(transaction) } /// Authenticates a lock, or returns `None` while the engine lacks the quorum data to decide. @@ -249,7 +245,7 @@ mod tests { use crate::test_utils::MockHeaderStorage; use dashcore::bls_sig_utils::BLSSignature; use dashcore::sml::llmq_type::LLMQType; - use dashcore::{BlockHash, OutPoint, QuorumHash, ScriptBuf, TxIn, TxOut}; + use dashcore::{Address, BlockHash, OutPoint, QuorumHash, ScriptBuf, TxIn, TxOut}; use hex_conservative::DisplayHex; use test_case::test_case; @@ -313,7 +309,7 @@ mod tests { // This unit tests binding only; authentication is exercised with the signed fixture. let mut lock = mainnet_fixture_is_lock(); lock.txid = transaction.txid(); - lock.inputs = transaction.input.iter().map(|input| input.previous_output).collect(); + lock.inputs = InstantLock::lock_inputs(&transaction); let verified = VerifiedInstantLock { instant_lock: lock, network: Network::Mainnet, @@ -326,6 +322,17 @@ mod tests { let mut wrong_inputs = verified.clone(); wrong_inputs.instant_lock.inputs[0].vout += 1; assert!(!wrong_inputs.matches_transaction(Network::Mainnet, &transaction)); + + let address = Address::dummy(Network::Mainnet, 0); + let withdrawal = Transaction::dummy_asset_unlock(&address, 7, 1); + let mut lock = mainnet_fixture_is_lock(); + lock.txid = withdrawal.txid(); + lock.inputs = InstantLock::lock_inputs(&withdrawal); + let verified = VerifiedInstantLock { + instant_lock: lock, + network: Network::Mainnet, + }; + assert!(verified.matches_transaction(Network::Mainnet, &withdrawal)); } #[test] From bd7021c3cea1bc43665aa1a8b3c259bbadfadc57 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:38:01 +0000 Subject: [PATCH 36/38] fix(dash-spv): keep a foreign-type cycle open for merging `is_cycle_fully_verified` closed a stored cycle once it held as many verified quorums as the configured InstantSend type has slots, whatever their type. On an unconfigured devnet a cycle of a rotating type with more slots could close early, so a later full QRInfo of the configured type was never merged and locks selecting a missing index failed with `QuorumIndexNotFound`. `fills_every_slot` now also requires the configured type, which `instant_send_cycle_completeness` already did. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sml_engine.rs | 53 ++++++++++++++++++++++++++++++++------ 1 file changed, 45 insertions(+), 8 deletions(-) diff --git a/dash-spv/src/sml_engine.rs b/dash-spv/src/sml_engine.rs index b273e27b0..511fe72b1 100644 --- a/dash-spv/src/sml_engine.rs +++ b/dash-spv/src/sml_engine.rs @@ -65,10 +65,13 @@ pub(crate) struct InstantSendCycle<'a> { pub(crate) complete: bool, } -/// `true` when the cycle holds a `Verified` quorum for every active slot of `isd_type`. +/// `true` when the cycle holds a `Verified` quorum of `isd_type` for every active slot. fn fills_every_slot(quorums: &BTreeMap, isd_type: LLMQType) -> bool { quorums.len() == isd_type.active_quorum_count() as usize - && quorums.values().all(|quorum| quorum.verified == LLMQEntryVerificationStatus::Verified) + && quorums.values().all(|quorum| { + quorum.verified == LLMQEntryVerificationStatus::Verified + && quorum.quorum_entry.llmq_type == isd_type + }) } /// Whether a stored cycle is complete, or `None` when one of its quorums is unverified or @@ -92,10 +95,7 @@ fn instant_send_cycle_completeness( }) { return None; } - Some( - fills_every_slot(quorums, isd_type) - && quorums.values().all(|quorum| quorum.quorum_entry.llmq_type == isd_type), - ) + Some(fills_every_slot(quorums, isd_type)) } /// Why the engine did not take a diff or a QRInfo. @@ -763,8 +763,9 @@ impl MasternodeListEngine { Ok(()) } - /// `true` when the stored cycle has a `Verified` quorum for every active - /// slot. A partial cycle stays open so a later QRInfo can complete it. + /// `true` when the stored cycle has a `Verified` quorum of the configured type for + /// every active slot. A partial or foreign-type cycle stays open so a later QRInfo + /// can complete it. fn is_cycle_fully_verified(&self, cycle_hash: &BlockHash) -> bool { let isd_type = self.network.isd_llmq_type(); self.rotated_quorums_per_cycle @@ -2631,6 +2632,42 @@ mod tests { ); } + /// A stored cycle of another rotating type does not close the storage gate, so + /// the configured type's full set still merges into it. + #[tokio::test] + async fn store_cycle_if_fully_verified_merges_over_a_foreign_type() { + let (mut engine, qr_info) = load_qrinfo_2240504_fixture().await; + engine.feed_qr_info(qr_info).await.expect("first feed should succeed"); + let cycle_key = *engine + .rotated_quorums_per_cycle + .keys() + .next() + .expect("first feed must store at least one rotation cycle"); + let original_cycle = engine.rotated_quorums_per_cycle[&cycle_key].clone(); + let rotation_quorum_type = + original_cycle.values().next().expect("cycle non-empty").quorum_entry.llmq_type; + let foreign = original_cycle + .iter() + .map(|(index, quorum)| { + let mut quorum = quorum.clone(); + quorum.quorum_entry.llmq_type = LLMQType::LlmqtypeTestDIP0024; + (*index, quorum) + }) + .collect(); + engine.rotated_quorums_per_cycle.insert(cycle_key, foreign); + + engine + .store_cycle_if_fully_verified( + cycle_key, + original_cycle.values().cloned().collect(), + rotation_quorum_type, + ) + .await + .expect("gate must not error"); + + assert_eq!(engine.rotated_quorums_per_cycle[&cycle_key], original_cycle); + } + /// The storage gate must short-circuit with `Ok(None)` (and not write) /// when any input entry is not `Verified` or the target cycle is already /// fully `Verified`, and it only ever merges into a stored cycle. From b75d212814d19ef69435b8aca8e3b90473fd87ca Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:43:35 +0000 Subject: [PATCH 37/38] refactor(dashcore): serialize the withdrawal request as Core does `InstantLock::lock_inputs` wrote the prefix's compact-size length as a hand-cast byte. It now serializes the `(prefix, index)` pair with the consensus encoder, the same way Dash Core's `SerializeHash(std::make_pair(...))` does, so the length prefix comes from `VarInt` and needs no comment. The derived outpoint is unchanged. Co-Authored-By: Claude Opus 5.5 --- dash/src/ephemerealdata/instant_lock.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/dash/src/ephemerealdata/instant_lock.rs b/dash/src/ephemerealdata/instant_lock.rs index 0b0eb2f9c..1f2189c59 100644 --- a/dash/src/ephemerealdata/instant_lock.rs +++ b/dash/src/ephemerealdata/instant_lock.rs @@ -66,12 +66,9 @@ impl InstantLock { else { return transaction.input.iter().map(|input| input.previous_output).collect(); }; - let mut engine = sha256d::Hash::engine(); - // The compact size of a length below 0xfd is that one byte. - engine.input(&[ASSET_UNLOCK_REQUEST_ID_PREFIX.len() as u8]); - engine.input(ASSET_UNLOCK_REQUEST_ID_PREFIX.as_bytes()); - engine.input(&payload.base.index.to_le_bytes()); - vec![OutPoint::new(Txid::from_raw_hash(engine.finalize()), 0)] + let request = (ASSET_UNLOCK_REQUEST_ID_PREFIX.to_string(), payload.base.index); + let txid = Txid::from_raw_hash(sha256d::Hash::hash(&serialize(&request))); + vec![OutPoint::new(txid, 0)] } /// Returns the hash peers use to announce and request this lock. From 1818275a6d1ae595735df2451acb71500cec2cfb Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:45:08 +0000 Subject: [PATCH 38/38] test(dash-spv): check a foreign-type cycle without hand-set state `store_cycle_if_fully_verified_merges_over_a_foreign_type` wrote a cycle of another rotating type into a mainnet engine's private map, a state no mainnet feed reaches. The devnet test that already covers a cycle of another rotating type now asserts that `fills_every_slot` keeps such a cycle open, which is the case a devnet engine reaches. The assertion fails without the type check in `fills_every_slot`. Co-Authored-By: Claude Opus 5.5 --- dash-spv/src/sml_engine.rs | 42 ++++---------------------------------- 1 file changed, 4 insertions(+), 38 deletions(-) diff --git a/dash-spv/src/sml_engine.rs b/dash-spv/src/sml_engine.rs index 511fe72b1..808ccff95 100644 --- a/dash-spv/src/sml_engine.rs +++ b/dash-spv/src/sml_engine.rs @@ -1468,7 +1468,8 @@ pub(crate) mod test_support { mod tests { use super::test_support::{fixture_heights, mainnet_fixture_is_lock, quorum_entry, TestEngine}; use super::{ - build_cycle_quorum_map, instant_send_cycle_completeness, valid_coinbase_chain_lock, + build_cycle_quorum_map, fills_every_slot, instant_send_cycle_completeness, + valid_coinbase_chain_lock, }; use super::{FeedError, MasternodeListEngine, QRInfoFeedResult}; use crate::error::{StorageError, StorageResult}; @@ -2632,42 +2633,6 @@ mod tests { ); } - /// A stored cycle of another rotating type does not close the storage gate, so - /// the configured type's full set still merges into it. - #[tokio::test] - async fn store_cycle_if_fully_verified_merges_over_a_foreign_type() { - let (mut engine, qr_info) = load_qrinfo_2240504_fixture().await; - engine.feed_qr_info(qr_info).await.expect("first feed should succeed"); - let cycle_key = *engine - .rotated_quorums_per_cycle - .keys() - .next() - .expect("first feed must store at least one rotation cycle"); - let original_cycle = engine.rotated_quorums_per_cycle[&cycle_key].clone(); - let rotation_quorum_type = - original_cycle.values().next().expect("cycle non-empty").quorum_entry.llmq_type; - let foreign = original_cycle - .iter() - .map(|(index, quorum)| { - let mut quorum = quorum.clone(); - quorum.quorum_entry.llmq_type = LLMQType::LlmqtypeTestDIP0024; - (*index, quorum) - }) - .collect(); - engine.rotated_quorums_per_cycle.insert(cycle_key, foreign); - - engine - .store_cycle_if_fully_verified( - cycle_key, - original_cycle.values().cloned().collect(), - rotation_quorum_type, - ) - .await - .expect("gate must not error"); - - assert_eq!(engine.rotated_quorums_per_cycle[&cycle_key], original_cycle); - } - /// The storage gate must short-circuit with `Ok(None)` (and not write) /// when any input entry is not `Verified` or the target cycle is already /// fully `Verified`, and it only ever merges into a stored cycle. @@ -3422,7 +3387,7 @@ mod tests { /// On a devnet the signing cycle can be of another rotating type than the configured /// one. Holding as many quorums as the configured type has slots does not complete - /// it, so a lock it does not verify is deferred, not refuted. + /// it, so a lock it does not verify is deferred and a later QRInfo still merges in. #[test] fn should_not_complete_a_devnet_cycle_of_another_rotating_type() { let lock = mainnet_fixture_is_lock(); @@ -3434,6 +3399,7 @@ mod tests { assert!(slots < cycle.len(), "the mainnet cycle has more slots than a devnet one"); let partial: BTreeMap<_, _> = cycle.clone().into_iter().take(slots).collect(); + assert!(!fills_every_slot(&partial, configured)); assert_eq!(instant_send_cycle_completeness(&partial, configured, true), Some(false)); assert_eq!(instant_send_cycle_completeness(&partial, configured, false), None); assert_eq!(instant_send_cycle_completeness(&cycle, served, false), Some(true));