Skip to content

key-wallet: no-change asset locks keep the source account in Mempool after finality re-delivery #1303

Closed

Description

@lklimek

TL;DR: A transfer that spends its full Core input can remain pending in the paying account after the network has finalized it, while the same wallet correctly marks the transfer final in its asset-lock account.

User story

As a wallet user, I want an accepted transfer from Core to Platform to finish once the network confirms it, even when I spend the whole selected coin and receive no Core change.

Scenario

Base flow

Receive a confirmed coin. Spend it on a transfer to Platform, with no change returning to the Core account. The wallet first sees the pending transaction, then receives its InstantSend lock or its containing block.

Actual behavior

The paying account still reports the transfer as pending. Another account in the same wallet has already received its finality update. A consumer looking at the paying account can continue waiting despite that update.

Expected behavior

Every account already holding the transaction learns its delivered finality. The funding account must not depend on receiving a change output to observe that update.

Detailed discussion

Confirmed with native key-wallet Cargo tests at both:

  • current dev: 2900e46efe1bcaad18d2ab0b41aa1d4ef5d43a73;
  • the observed weekly build's rust-dashcore pin: aca020263990a86a15cc1d97ae2cbf965d488db5.

The fixture creates a deterministic watch-only wallet with BIP44 account 0 and AssetLockAddressTopUp. No seeds, private keys, database, GUI, platform-wallet, network access, transaction broadcast, or funds are used. Its non-coinbase funding parent is explicitly delivered and checked as ChainLocked before the asset lock spends it.

The actual public entry point is WalletTransactionChecker::check_core_transaction with state and balance updates enabled:

  1. Deliver the funding parent as InChainLockedBlock.
  2. Deliver a type-8 asset lock as Mempool. Its credit output belongs to AssetLockAddressTopUp; its input belongs to BIP44. Both accounts record it, and BIP44 consumes the input UTXO.
  3. In separate tests, re-deliver it as InstantSend, InBlock, or InChainLockedBlock.
  4. Assert the correct source-account context/finalized state and its emitted updated record. Repeat all three cases with owned Core change as controls.

All three no-change cases fail. All three owned-change controls pass. The same result holds on current dev with keep-finalized-transactions enabled, excluding record pruning as the cause.

Re-delivery No-change BIP44 No-change credit-key account With owned Core change
InstantSend Mempool InstantSend Both InstantSend
Mined Mempool InBlock Both InBlock
ChainLocked block Mempool, not finalized Finalized Both finalized

On each failing delivery, updated_records contains only AssetLockAddressTopUp.

Root cause

The wallet checker computes fresh relevance from output matches and the remaining live input UTXOs. After the mempool delivery consumed the source UTXO, the no-change source no longer matches. The owned credit output still makes the keys account relevant.

The stored-context fallback runs only when the whole transaction is irrelevant (and only for a mined context). It therefore does not repair the missing source account here. The InstantSend re-delivery loop and the mined path process only affected_accounts.

Reproduce

Save the test below as key-wallet/tests/asset_lock_source_finality.rs at either revision, then run:

cargo test -p key-wallet --test asset_lock_source_finality -- --nocapture
cargo test -p key-wallet --test asset_lock_source_finality --features keep-finalized-transactions -- --nocapture

The second command was run on current dev. Each executed target reports:

test_case_1_no_change_instant_send ... FAILED
test_case_2_no_change_mined ... FAILED
test_case_3_no_change_chain_locked ... FAILED
test_case_4_owned_change_instant_send ... ok
test_case_5_owned_change_mined ... ok
test_case_6_owned_change_chain_locked ... ok
test result: FAILED. 3 passed; 3 failed; 0 ignored; 0 measured; 0 filtered out

The no-change InstantSend/mined assertions show left: Mempool; the ChainLocked case fails source account must observe the delivered ChainLock. These are normal failing contract tests, with no should_panic, ignored tests, or production fix. Targeted all-features clippy and cargo fmt --all pass.

Complete offline native reproduction (same file on both revisions)
//! Re-delivery must promote every account's record of the same asset lock.
//! Synthetic, unsigned transactions exercise post-verification wallet state only.

use dashcore::blockdata::transaction::special_transaction::{
    asset_lock::AssetLockPayload, TransactionPayload,
};
use dashcore::ephemerealdata::instant_lock::InstantLock;
use dashcore::hashes::Hash;
use dashcore::{
    Address, BlockHash, Network, OutPoint, ScriptBuf, Transaction, TxIn, TxOut, Witness,
};
use key_wallet::account::{AccountCollection, StandardAccountType};
use key_wallet::bip32::{ChildNumber, ExtendedPubKey};
use key_wallet::managed_account::{
    managed_account_trait::ManagedAccountTrait, managed_account_type::ManagedAccountType,
};
use key_wallet::transaction_checking::wallet_checker::WalletTransactionChecker;
use key_wallet::transaction_checking::{BlockInfo, TransactionContext};
use key_wallet::wallet::{ManagedWalletInfo, Wallet};
use key_wallet::{Account, AccountType, KeySource};
use test_case::test_case;

#[derive(Clone, Copy, Debug)]
enum Delivery {
    InstantSend,
    Mined,
    ChainLocked,
}

#[test_case(false, Delivery::InstantSend; "no_change_instant_send")]
#[test_case(false, Delivery::Mined; "no_change_mined")]
#[test_case(false, Delivery::ChainLocked; "no_change_chain_locked")]
#[test_case(true, Delivery::InstantSend; "owned_change_instant_send")]
#[test_case(true, Delivery::Mined; "owned_change_mined")]
#[test_case(true, Delivery::ChainLocked; "owned_change_chain_locked")]
#[tokio::test]
async fn asset_lock_source_observes_redelivered_context(with_change: bool, delivery: Delivery) {
    // Public-only fixture: deterministic addresses, no seed or private key material.
    let public_key = dashcore::ecdsa::EcdsaPublicKey::from_bytes(&[2; 33]).unwrap();
    let funds_xpub = ExtendedPubKey {
        network: Network::Testnet,
        depth: 0,
        parent_fingerprint: Default::default(),
        child_number: ChildNumber::from_normal_idx(0).unwrap(),
        public_key,
        chain_code: [1; 32].into(),
    };
    let keys_xpub = ExtendedPubKey {
        chain_code: [2; 32].into(),
        ..funds_xpub
    };
    let source_type = AccountType::Standard {
        index: 0,
        standard_account_type: StandardAccountType::BIP44Account,
    };
    let mut accounts = AccountCollection::new();
    accounts
        .standard_bip44_accounts
        .insert(0, Account::from_xpub(None, source_type, funds_xpub, Network::Testnet).unwrap());
    accounts.asset_lock_address_topup = Some(
        Account::from_xpub(None, AccountType::AssetLockAddressTopUp, keys_xpub, Network::Testnet)
            .unwrap(),
    );
    let mut wallet = Wallet::from_xpub(funds_xpub, accounts, false).unwrap();
    let mut info = ManagedWalletInfo::from_wallet_with_name(&wallet, "Finality fixture".into(), 0);
    let receive = info
        .first_bip44_managed_account_mut()
        .unwrap()
        .next_receive_address(Some(&funds_xpub), true)
        .unwrap();
    let credit_address: Address = {
        let account = info.accounts.asset_lock_address_topup.as_mut().unwrap();
        let ManagedAccountType::AssetLockAddressTopUp {
            addresses,
        } = account.managed_account_type_mut()
        else {
            panic!("wrong type")
        };
        addresses.next_unused(&KeySource::Public(keys_xpub), true).unwrap()
    };
    let funding = Transaction {
        version: 2,
        lock_time: 0,
        input: vec![TxIn {
            previous_output: OutPoint::new(dashcore::Txid::from_byte_array([3; 32]), 0),
            script_sig: ScriptBuf::new(),
            sequence: u32::MAX,
            witness: Witness::new(),
        }],
        output: vec![TxOut {
            value: 200_000,
            script_pubkey: receive.script_pubkey(),
        }],
        special_transaction_payload: None,
    };
    let block = |height| BlockInfo::new(height, BlockHash::all_zeros(), 1_790_000_000);
    let funded = info
        .check_core_transaction(
            &funding,
            TransactionContext::InChainLockedBlock(block(1)),
            &mut wallet,
            true,
            true,
        )
        .await;
    assert!(funded.is_relevant);
    assert!(info.first_bip44_managed_account().unwrap().transaction_is_finalized(&funding.txid()));
    let funding_outpoint = OutPoint::new(funding.txid(), 0);
    assert!(info.first_bip44_managed_account().unwrap().utxos.contains_key(&funding_outpoint));
    let change = info
        .first_bip44_managed_account_mut()
        .unwrap()
        .next_change_address(Some(&funds_xpub), true)
        .unwrap();
    let lock_amount = if with_change {
        190_000
    } else {
        199_000
    };
    let mut outputs = vec![TxOut {
        value: lock_amount,
        script_pubkey: ScriptBuf::new_op_return(&[]),
    }];
    if with_change {
        outputs.push(TxOut {
            value: 9_000,
            script_pubkey: change.script_pubkey(),
        });
    }
    let lock = Transaction {
        version: 3,
        lock_time: 0,
        input: vec![TxIn {
            previous_output: OutPoint::new(funding.txid(), 0),
            script_sig: ScriptBuf::new(),
            sequence: u32::MAX,
            witness: Witness::new(),
        }],
        output: outputs,
        special_transaction_payload: Some(TransactionPayload::AssetLockPayloadType(
            AssetLockPayload {
                version: 1,
                credit_outputs: vec![TxOut {
                    value: lock_amount,
                    script_pubkey: credit_address.script_pubkey(),
                }],
            },
        )),
    };
    let txid = lock.txid();
    let first = info
        .check_core_transaction(&lock, TransactionContext::Mempool, &mut wallet, true, true)
        .await;
    assert!(first.is_relevant);
    assert_eq!(
        first.new_records.len(),
        2,
        "funds and credit-key accounts must both record the first sighting"
    );
    assert!(!info.first_bip44_managed_account().unwrap().utxos.contains_key(&funding_outpoint));
    for account in info.accounts.all_accounts() {
        assert!(matches!(
            account.transactions().get(&txid).unwrap().context,
            TransactionContext::Mempool
        ));
    }

    // InstantLock signatures are deliberately not verified here: this is the
    // state-delivery boundary after the network layer has verified finality.
    let context = match delivery {
        Delivery::InstantSend => TransactionContext::InstantSend(InstantLock {
            txid,
            inputs: vec![funding_outpoint],
            ..Default::default()
        }),
        Delivery::Mined => TransactionContext::InBlock(block(2)),
        Delivery::ChainLocked => TransactionContext::InChainLockedBlock(block(2)),
    };
    let result = info.check_core_transaction(&lock, context.clone(), &mut wallet, true, true).await;
    let source = info.first_bip44_managed_account().unwrap();
    let keys = info.accounts.asset_lock_address_topup.as_ref().unwrap();
    println!("change={with_change} delivery={delivery:?} source={:?} source_finalized={} keys={:?} keys_finalized={} updated_accounts={:?}",
        source.transactions().get(&txid).map(|r| r.context.to_string()), source.transaction_is_finalized(&txid),
        keys.transactions().get(&txid).map(|r| r.context.to_string()), keys.transaction_is_finalized(&txid),
        result.updated_records.iter().map(|r| r.account_type).collect::<Vec<_>>());
    assert!(result.is_relevant);
    // Check the credit account first to distinguish missed delivery from a
    // promotion that reached only one of the two records.
    if context.is_chain_locked() {
        assert!(keys.transaction_is_finalized(&txid));
        assert!(
            source.transaction_is_finalized(&txid),
            "source account must observe the delivered ChainLock"
        );
    } else {
        assert_eq!(keys.transactions().get(&txid).unwrap().context, context);
        assert_eq!(
            source.transactions().get(&txid).unwrap().context,
            context,
            "source and credit accounts must observe the same delivered context"
        );
    }
    let emitted = result
        .updated_records
        .iter()
        .find(|r| r.account_type == source_type && r.txid == txid)
        .expect("the source-account promotion must be emitted to storage consumers");
    assert_eq!(emitted.context, context);
}

Scope and downstream observation

This reproduces wallet-state delivery after finality verification. The synthetic InstantLock does not test BLS verification, peer delivery, consensus validity, or the separate lock-only notification entry point. It also does not run the Platform proof waiter: its preference for a stale in-memory record over other proof sources is a separate downstream concern.

The investigation began with Dash Evo Tool weekly build d94e6245d339ed8aed0e0470a5c8108635d8a471 (platform pin 575d961fe0c54bd7e01a3cf3823494e58c6c4fdb). A Core-to-foreign-Platform transfer spending its full input without owned Core change timed out after 300 seconds despite verified InstantSend; a prior run also saw ChainLock proof. The native tests isolate the record disagreement without relying on those other layers.

Prior work and duplicate check

Open PR inventory and targeted searches across open/closed issues and PRs found no dedicated issue or fixing PR for this remaining two-account case.

🤖 Co-authored by Claudius the Magnificent AI Agent

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