Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 50 additions & 3 deletions dash/src/test_utils/transaction.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
use std::ops::Range;

use crate::bls_sig_utils::BLSSignature;
use crate::bls_sig_utils::{BLSPublicKey, BLSSignature};
use crate::consensus::serialize;
use crate::hash_types::{MerkleRootAssetUnlocks, MerkleRootMasternodeList, MerkleRootQuorums};
use crate::hash_types::{
InputsHash, MerkleRootAssetUnlocks, MerkleRootMasternodeList, MerkleRootQuorums,
};
use crate::sml::masternode_list_entry::MasternodeNetInfo;
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, ScriptBuf, Transaction, TxIn, TxOut, Txid, Witness};
use crate::{Address, OutPoint, PubkeyHash, ScriptBuf, Transaction, TxIn, TxOut, Txid, Witness};

/// A special transaction type no Dash Core version assigns
pub const UNASSIGNED_SPECIAL_TX_TYPE: u16 = 0xffff;
Expand Down Expand Up @@ -59,6 +65,47 @@ impl Transaction {
}
}

/// Creates a ProRegTx registering `collateral`, with `owner_key_hash` as
/// its owner and voting key, paying `outputs`. `input_id` sets its one
/// input and so varies the txid.
pub fn dummy_provider_registration(
collateral: OutPoint,
owner_key_hash: PubkeyHash,
outputs: Vec<TxOut>,
input_id: u8,
) -> Transaction {
Transaction {
version: 3,
lock_time: 0,
input: vec![TxIn {
previous_output: OutPoint::new(Txid::from([input_id; 32]), 0),
..Default::default()
}],
output: outputs,
special_transaction_payload: Some(TransactionPayload::ProviderRegistrationPayloadType(
ProviderRegistrationPayload {
version: 1,
masternode_type: ProviderMasternodeType::Regular,
masternode_mode: 0,
collateral_outpoint: collateral,
service_address: MasternodeNetInfo::Legacy(([127, 0, 0, 1], 19999).into()),
owner_key_hash,
operator_public_key: BLSPublicKey::from([0x11; 48]),
voting_key_hash: owner_key_hash,
operator_reward: 0,
script_payout: ScriptBuf::new(),
inputs_hash: InputsHash::all_zeros(),
signature: vec![0x33; 65],
platform_node_id: None,
platform_p2p_port: None,
platform_http_port: None,
payouts: None,
shared_collateral: None,
},
)),
}
}

pub fn dummy_coinbase(address: &Address, value: u64) -> Transaction {
let inputs = vec![TxIn {
previous_output: OutPoint::null(),
Expand Down
214 changes: 210 additions & 4 deletions key-wallet-manager/src/event_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ use dashcore::ephemerealdata::instant_lock::InstantLock;
use dashcore::hash_types::CycleHash;
use dashcore::opcodes;
use dashcore::{
BlockHash, CompactTarget, OutPoint, PublicKey, ScriptBuf, TxIn, TxMerkleNode, TxOut, Txid,
Witness,
BlockHash, CompactTarget, OutPoint, PubkeyHash, PublicKey, ScriptBuf, TxIn, TxMerkleNode,
TxOut, Txid, Witness,
};
use key_wallet::account::StandardAccountType;
use key_wallet::managed_account::address_pool::{AddressPoolType, PublicKeyType};
use key_wallet::managed_account::managed_account_trait::ManagedAccountTrait;
use key_wallet::managed_account::managed_account_type::ManagedAccountType;
use key_wallet::transaction_checking::{TransactionRouter, TransactionType};
use key_wallet::transaction_checking::{BlockInfo, TransactionRouter, TransactionType};
use key_wallet::wallet::managed_wallet_info::transaction_building::AccountTypePreference;
use key_wallet::AccountType;
use std::collections::BTreeSet;
use std::collections::{BTreeMap, BTreeSet};

fn make_block(txdata: Vec<Transaction>, seed: u8, time: u32) -> Block {
Block {
Expand Down Expand Up @@ -79,7 +79,9 @@ async fn test_mempool_tx_emits_single_event_with_balance() {
balance,
account_balances,
addresses_derived: _,
locked_outpoints,
} => {
assert!(locked_outpoints.is_empty(), "an ordinary payment locks nothing");
assert_eq!(*wid, wallet_id);
assert_eq!(record.txid, tx.txid());
assert_eq!(record.context, TransactionContext::Mempool);
Expand Down Expand Up @@ -132,7 +134,9 @@ async fn test_mempool_tx_with_instant_lock_emits_detected_event_with_locked_bala
balance,
account_balances,
addresses_derived: _,
locked_outpoints,
} => {
assert!(locked_outpoints.is_empty(), "an ordinary payment locks nothing");
assert_eq!(*wid, wallet_id);
assert!(matches!(record.context, TransactionContext::InstantSend(_)));
assert_eq!(balance.confirmed(), TX_AMOUNT);
Expand Down Expand Up @@ -348,7 +352,9 @@ async fn test_block_with_new_tx_emits_inserted_record() {
account_balances,
addresses_derived: _,
chain_lock: _,
locked_outpoints,
} => {
assert!(locked_outpoints.is_empty(), "an ordinary payment locks nothing");
assert_eq!(*wid, wallet_id);
assert_eq!(*height, 100);
assert_eq!(inserted.len(), 1);
Expand Down Expand Up @@ -414,7 +420,9 @@ async fn test_block_confirming_known_mempool_tx_emits_updated_record() {
account_balances,
addresses_derived: _,
chain_lock: _,
locked_outpoints,
} => {
assert!(locked_outpoints.is_empty(), "an ordinary payment locks nothing");
assert_eq!(*wid, wallet_id);
assert_eq!(*height, 200);
assert!(inserted.is_empty());
Expand Down Expand Up @@ -1365,6 +1373,204 @@ async fn test_update_wallet_synced_height_does_not_re_emit_when_unchanged() {
);
}

// ---------------------------------------------------------------------------
// Masternode collateral locks
// ---------------------------------------------------------------------------

/// A ProRegTx registering `collateral` and paying `outputs`. Its fee input and
/// keys belong to no one the test wallet knows; `seed` varies the txid.
fn masternode_registration(collateral: OutPoint, outputs: Vec<TxOut>, seed: u8) -> Transaction {
let owner_key_hash = PubkeyHash::from_byte_array([0x70; 20]);
Transaction::dummy_provider_registration(collateral, owner_key_hash, outputs, seed)
}

fn bip44_account_0() -> AccountType {
AccountType::Standard {
index: 0,
standard_account_type: StandardAccountType::BIP44Account,
}
}

/// A wallet holding one coin of `TX_AMOUNT`, mined at height 100.
async fn manager_holding_a_coin() -> (WalletManager, WalletId, OutPoint) {
let (mut manager, wallet_id, addr) = setup_manager_with_wallet();
let funding = create_tx_paying_to(&addr, 0xc0);
let block = make_block(vec![funding.clone()], 0xc0, 1_000);
manager
.process_block_for_wallets(&block, block.block_hash(), 100, &BTreeSet::from([wallet_id]))
.await;
(manager, wallet_id, OutPoint::new(funding.txid(), 0))
}

/// A ProRegTx locks a collateral it names at the block that holds it, not
/// from the mempool. The mempool sighting changes nothing and emits nothing;
/// the block's `BlockProcessed` names the locked outpoint and carries the coin
/// in the locked balance.
#[tokio::test]
async fn test_registration_locks_a_named_collateral_at_its_block_not_from_the_mempool() {
let (mut manager, wallet_id, collateral) = manager_holding_a_coin().await;
let registration = masternode_registration(collateral, vec![], 0xc1);
let mut rx = manager.subscribe_events();

let result = manager.process_mempool_transaction(&registration, None).await;

assert!(!result.is_relevant);
assert_no_events(&mut rx);
let info = manager.get_wallet_info(&wallet_id).expect("wallet info");
assert!(!info.is_outpoint_locked(&collateral));
assert_eq!(info.balance().spendable(), TX_AMOUNT);
assert_eq!(info.balance().locked(), 0);

let block = make_block(vec![registration], 0xc1, 1_001);
manager
.process_block_for_wallets(&block, block.block_hash(), 101, &BTreeSet::from([wallet_id]))
.await;

assert!(manager
.get_wallet_info(&wallet_id)
.expect("wallet info")
.is_outpoint_locked(&collateral));
let events = drain_events(&mut rx);
assert_eq!(events.len(), 1, "one BlockProcessed expected, got {:?}", events);
match &events[0] {
WalletEvent::BlockProcessed {
inserted,
updated,
balance,
account_balances,
locked_outpoints,
..
} => {
assert!(inserted.is_empty() && updated.is_empty(), "the ProRegTx records nothing");
assert_eq!(locked_outpoints, &vec![collateral]);
assert_eq!(balance.locked(), TX_AMOUNT);
assert_eq!(balance.spendable(), 0);
let account = account_balances.get(&bip44_account_0()).expect("the coin's account");
assert_eq!(account.locked(), TX_AMOUNT);
}
other => panic!("expected BlockProcessed, got {:?}", other),
}
}

/// An InstantSend lock does not make a ProRegTx a registration: the coin it
/// names stays spendable until a block holds the ProRegTx.
#[tokio::test]
async fn test_instant_locked_registration_locks_no_collateral_it_names() {
let (mut manager, wallet_id, collateral) = manager_holding_a_coin().await;
let registration = masternode_registration(collateral, vec![], 0xc2);
let mut rx = manager.subscribe_events();

manager
.process_mempool_transaction(&registration, Some(dummy_instant_lock(registration.txid())))
.await;

assert_no_events(&mut rx);
let info = manager.get_wallet_info(&wallet_id).expect("wallet info");
assert!(!info.is_outpoint_locked(&collateral));
assert_eq!(info.balance().spendable(), TX_AMOUNT);
assert_eq!(info.balance().locked(), 0);
}

/// A ProRegTx that creates its collateral locks it from the mempool, and the
/// `TransactionDetected` for the coin names the locked outpoint and carries
/// the coin in the locked balance.
#[tokio::test]
async fn test_mempool_registration_creating_its_collateral_emits_the_locked_balance() {
let (mut manager, wallet_id, addr) = setup_manager_with_wallet();
let to_wallet = TxOut {
value: TX_AMOUNT,
script_pubkey: addr.script_pubkey(),
};
// A null collateral txid: the collateral is this ProRegTx's output 0.
let registration =
masternode_registration(OutPoint::new(Txid::all_zeros(), 0), vec![to_wallet], 0xc3);
let collateral = OutPoint::new(registration.txid(), 0);
let mut rx = manager.subscribe_events();

let result = manager.process_mempool_transaction(&registration, None).await;

assert!(result.is_relevant);
let events = drain_events(&mut rx);
assert_eq!(events.len(), 1, "one TransactionDetected expected, got {:?}", events);
match &events[0] {
WalletEvent::TransactionDetected {
record,
balance,
account_balances,
locked_outpoints,
..
} => {
assert_eq!(record.txid, registration.txid());
assert_eq!(locked_outpoints, &vec![collateral]);
assert_eq!(balance.locked(), TX_AMOUNT);
assert_eq!(balance.spendable(), 0, "the collateral is not spendable balance");
let account = account_balances.get(&bip44_account_0()).expect("the coin's account");
assert_eq!(account.locked(), TX_AMOUNT);
}
other => panic!("expected TransactionDetected, got {:?}", other),
}
let info = manager.get_wallet_info(&wallet_id).expect("wallet info");
assert!(info.is_outpoint_locked(&collateral));
assert_eq!(info.balance().locked(), TX_AMOUNT);
}

/// A check reports the locks it took per wallet, including for a wallet the
/// transaction is otherwise irrelevant to, so a caller that checks with
/// `update_balance = false` knows which balances to refresh.
#[tokio::test]
async fn test_check_transaction_reports_a_lock_for_a_wallet_it_is_otherwise_irrelevant_to() {
let (mut manager, wallet_id, collateral) = manager_holding_a_coin().await;
let registration = masternode_registration(collateral, vec![], 0xc4);
let mined = TransactionContext::InBlock(BlockInfo::new(101, BlockHash::all_zeros(), 1_001));

let result = manager.check_transaction_in_all_wallets(&registration, mined, true, false).await;

assert!(result.affected_wallets.is_empty());
assert_eq!(result.per_wallet_locked_outpoints, BTreeMap::from([(wallet_id, vec![collateral])]));
}

/// A lock that moves no balance and adds no record still reaches a persister.
/// Here a rescan locks again the collateral of the wallet's own registration,
/// a coin that has not arrived.
#[tokio::test]
async fn test_block_processed_names_a_lock_that_changes_nothing_else() {
let (mut manager, wallet_id, _addr) = setup_manager_with_wallet();
let owner = manager
.get_wallet_info_mut(&wallet_id)
.expect("wallet info")
.provider_owner_keys_managed_account_mut()
.expect("provider owner keys account")
.next_address(None, true)
.expect("owner address");
let owner_key_hash = *owner.payload().as_pubkey_hash().expect("P2PKH owner address");
let collateral = OutPoint::new(Txid::from_byte_array([0xc5; 32]), 0);
let registration =
Transaction::dummy_provider_registration(collateral, owner_key_hash, Vec::new(), 0xc5);
let block = make_block(vec![registration], 0xc5, 1_001);
let wallets = BTreeSet::from([wallet_id]);
manager.process_block_for_wallets(&block, block.block_hash(), 101, &wallets).await;
let info = manager.get_wallet_info_mut(&wallet_id).expect("wallet info");
assert!(info.unlock_outpoint(&collateral));
let mut rx = manager.subscribe_events();

manager.process_block_for_wallets(&block, block.block_hash(), 101, &wallets).await;

let events = drain_events(&mut rx);
assert_eq!(events.len(), 1, "one BlockProcessed expected, got {:?}", events);
match &events[0] {
WalletEvent::BlockProcessed {
inserted,
updated,
locked_outpoints,
..
} => {
assert!(inserted.is_empty() && updated.is_empty(), "already recorded");
assert_eq!(locked_outpoints, &vec![collateral]);
}
other => panic!("expected BlockProcessed, got {:?}", other),
}
}

// ---------------------------------------------------------------------------
// Dry run and irrelevant paths
// ---------------------------------------------------------------------------
Expand Down
17 changes: 15 additions & 2 deletions key-wallet-manager/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,10 @@ pub enum WalletEvent {
/// these rows transactionally with `record` so UTXOs landing on
/// them retain a parent address row.
addresses_derived: Vec<DerivedAddress>,
/// Outpoints this transaction added to the wallet's lock set: the
/// collateral of a ProRegTx. A persister stores them and hands them
/// back with `ManagedWalletInfo::lock_outpoint` on load.
locked_outpoints: Vec<OutPoint>,
Comment thread
llbartekll marked this conversation as resolved.
Resolved
},
/// An InstantSend lock was applied to a previously-seen off-chain
/// wallet-relevant transaction.
Expand Down Expand Up @@ -374,6 +378,11 @@ pub enum WalletEvent {
/// transactionally with the inserted/updated records so UTXOs
/// landing on them retain a parent address row.
addresses_derived: Vec<DerivedAddress>,
/// Outpoints this block added to the wallet's lock set: the
/// collateral of each ProRegTx that locked one. A persister stores
/// them and hands them back with `ManagedWalletInfo::lock_outpoint`
/// on load.
locked_outpoints: Vec<OutPoint>,
},
/// The wallet's scan cursor advanced because the filter pipeline
/// committed a batch covering blocks up to `height`. No records or
Expand Down Expand Up @@ -478,15 +487,17 @@ impl fmt::Display for WalletEvent {
balance,
account_balances,
addresses_derived,
locked_outpoints,
..
} => write!(
f,
"TransactionDetected(txid={}, context={}, balance={}, account_balances={}, derived={})",
"TransactionDetected(txid={}, context={}, balance={}, account_balances={}, derived={}, locked={})",
record.txid,
record.context,
balance,
format_account_balances(account_balances),
addresses_derived.len(),
locked_outpoints.len(),
),
WalletEvent::TransactionInstantLocked {
txid,
Expand Down Expand Up @@ -545,10 +556,11 @@ impl fmt::Display for WalletEvent {
balance,
account_balances,
addresses_derived,
locked_outpoints,
..
} => write!(
f,
"BlockProcessed(height={}, chainlocked={}, inserted={}, updated={}, matured={}, balance={}, account_balances={}, derived={})",
"BlockProcessed(height={}, chainlocked={}, inserted={}, updated={}, matured={}, balance={}, account_balances={}, derived={}, locked={})",
height,
chain_lock.is_some(),
inserted.len(),
Expand All @@ -557,6 +569,7 @@ impl fmt::Display for WalletEvent {
balance,
format_account_balances(account_balances),
addresses_derived.len(),
locked_outpoints.len(),
),
WalletEvent::SyncHeightAdvanced {
height,
Expand Down
Loading
Loading