Skip to content

dash-spv: verified InstantSend lock never reaches the wallet after the tx expires from the mempool manager #1357

Open

Description

@lklimek

TL;DR: If a wallet's unconfirmed payment drops out of the SPV client's mempool tracking before its InstantSend lock is verified, the lock never reaches the wallet, so the payment stays "unconfirmed" instead of "InstantSend-locked".

User story

As a wallet developer building on dash-spv, I want every verified InstantSend lock for a transaction my wallet still holds as unconfirmed to be applied to that transaction, to show users instant, final payments and let them spend those funds right away.

Scenario

Base flow

  1. The wallet receives an incoming payment while it is still unconfirmed (it sits in the network's mempool).
  2. The SPV client stops tracking that payment in its own mempool view, for example because the entry reached the mempool expiry age.
  3. Later, the InstantSend lock for that payment arrives and is verified (for example because the lock had to wait for the masternode quorum data needed to check its signature).

Actual behavior

The verified lock is parked in an internal "lock waiting for its transaction" list and is never passed to the wallet. The wallet keeps showing the payment as a plain unconfirmed transaction, with no InstantSend status and no TransactionInstantLocked event, until a block confirms it.

Expected behavior

The wallet receives the lock and marks the payment as InstantSend-locked, the same as when the lock arrives while the client still tracks the transaction.

Detailed discussion

Root cause (at 66d3833, PR #1336 head plus one local commit)

  • MempoolManager::handle_sync_event acts only on SyncEvent::InstantLockReceived { validated: true } (dash-spv/src/sync/mempool/sync_manager.rs:132-135) and calls process_instant_send.
  • MempoolManager::process_instant_send (dash-spv/src/sync/mempool/manager.rs:606-646) notifies the wallet (process_mempool_instant_send_lock) only when the txid is present in self.transactions. Otherwise it inserts the lock into pending_is_locks (lines 627-628), which is drained only by handle_tx (line 403) when the transaction is downloaded again, and pruned after MEMPOOL_TX_EXPIRY (24 h).
  • Two paths remove a txid from self.transactions:
    • prune_expired (manager.rs:649-681), run from tick with MEMPOOL_TX_EXPIRY = 24 h (sync_manager.rs:151). It does not notify the wallet, and WalletInterface has no API to drop an unconfirmed record, so the wallet still holds the transaction as TransactionContext::Mempool. This is the case the test below reproduces.
    • remove_confirmed (manager.rs:572-597) on SyncEvent::BlockProcessed (sync_manager.rs:122-128). The block already confirms the transaction, so the user-facing impact is smaller. The wallet does accept late locks for mined records (key-wallet-manager/src/process_block.rs:490-498, pinned by test_late_instant_send_lock_after_block_confirmation_emits_event), so is_instantlocked on those UTXOs is also never set on this path.
  • self.transactions is in memory only. After a restart it is empty until peers re-announce the transaction in response to the mempool request. A peer re-announcement drains pending_is_locks through handle_tx, so a restart alone recovers as long as a peer still has the transaction.

Relation to PR #1336

The gap exists on dev: there handle_sync_event handles every InstantLockReceived (validated or not) with the same process_instant_send, so a lock that genuinely arrives after expiry is lost the same way. PR #1336 makes the mempool manager wait for verification. A lock that arrives before the client has the signing quorum is queued in InstantSendManager (dash-spv/src/sync/instantsend/manager.rs:177) and re-validated in validate_pending (line 242) for up to PENDING_TTL = 1 h (line 34). This widens the window: the transaction can expire from the mempool manager while its lock waits for verification.

Reproduction

Test sync::mempool::sync_manager::tests::should_lock_wallet_tx_after_mempool_expiry (on branch test/late-islock-after-mempool-prune, marked #[ignore] so CI stays green). It uses a real WalletManager and confirms that the wallet still holds the transaction as Mempool after the prune. Then it delivers a validated lock through handle_sync_event. It fails on the first contract assertion: the record never becomes InstantSend.

#[tokio::test]
async fn should_lock_wallet_tx_after_mempool_expiry() {
    let ctx = TestWalletContext::new_random();
    let tx = Transaction::dummy(&ctx.receive_address, 0..1, &[100_000]);
    let txid = tx.txid();
    let mut wallet = WalletManager::new(dashcore::Network::Testnet);
    let wallet_id = wallet.insert_wallet(ctx.wallet, ctx.managed_wallet).unwrap();
    let wallet = Arc::new(RwLock::new(wallet));
    let network: Arc<dyn NetworkManager> = Arc::new(MockNetworkManager::new());
    let mut manager = MempoolManager::new(
        wallet.clone(),
        MempoolStrategy::FetchAll,
        1000,
        0,
        BroadcastConfig::default(),
    );
    let peer = test_socket_address(1);
    manager.handle_message(peer, NetworkMessage::Tx(tx.into()).into(), &network).await.unwrap();

    // The lock is verified only after the mempool entry expired.
    tokio::time::sleep(Duration::from_millis(1)).await;
    manager.prune_expired(Duration::ZERO);
    let context = |wallet: &WalletManager| {
        wallet
            .get_wallet_info(&wallet_id)
            .unwrap()
            .first_bip44_managed_account()
            .unwrap()
            .transactions()[&txid]
            .context
            .clone()
    };
    assert_eq!(context(&*wallet.read().await), TransactionContext::Mempool);

    let mut rx = wallet.read().await.subscribe_events();
    let event = SyncEvent::InstantLockReceived {
        instant_lock: InstantLock {
            txid,
            ..InstantLock::default()
        },
        validated: true,
    };
    manager.handle_sync_event(&event, &network).await.unwrap();

    assert!(
        matches!(context(&*wallet.read().await), TransactionContext::InstantSend(_)),
        "a verified lock must reach the wallet's unconfirmed record"
    );
    assert!(matches!(
        rx.try_recv(),
        Ok(WalletEvent::TransactionInstantLocked { txid: locked, .. }) if locked == txid
    ));
}

Run (remove the #[ignore] or pass --ignored):

cargo test -p dash-spv --features test-utils --lib -- --ignored should_lock_wallet_tx_after_mempool_expiry

Result at 66d3833:

thread '...should_lock_wallet_tx_after_mempool_expiry' panicked at dash-spv/src/sync/mempool/sync_manager.rs:<line>:
a verified lock must reach the wallet's unconfirmed record

Possible fix directions (none chosen)

  • Forward a verified lock to the wallet even when the mempool manager no longer tracks the txid, for example through the lock-only WalletInterface::process_instant_send_lock. The wallet then decides whether the lock matches a record it holds. The cost is one wallet call per unknown lock.
  • Keep a bounded set of txids (or full transactions) that were pruned while the wallet still considered them relevant, and apply a later lock against it.
  • Have prune_expired skip, or extend, entries that the wallet still holds as unconfirmed, so the mempool view does not diverge from the wallet.
  • Let the wallet drain parked locks: expose pending_is_locks to the wallet layer, or re-check them against the wallet's unconfirmed records on each tick.

Prior work

Attribution

🤖 Co-authored by Claudius the Magnificent AI Agent

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions