Skip to main content

hns_wallet_hns/
lib.rs

1#![doc = "Handshake wallet key roles, restoration, UTXO selection, and name workflows."]
2#![forbid(unsafe_code)]
3
4mod embedded_backend;
5mod light_authority;
6mod light_index;
7mod name_workflow;
8mod node_rpc;
9mod peer_coordinator;
10mod recovery_publication;
11mod shakedex_funding;
12mod shakedex_key;
13// The counter boundary stays crate-private until the immutable hns-rs HNSA/HNSR
14// signing APIs are available to consume its opaque committed reservations.
15#[allow(dead_code)]
16mod hnsa_hnsr_publisher;
17
18pub use embedded_backend::{EmbeddedHnsBackend, HnsLightNetwork};
19pub use light_authority::{
20    AcceptedHnsHeader, EncryptedHnsLightAuthority, HNS_LIGHT_CHAIN_FORMAT_VERSION, HnsLightError,
21    HnsLightFloor, MAINNET_WALLET_CHECKPOINT_HEIGHT, MAX_CHECKPOINT_BOOTSTRAP_HEIGHT,
22    MAX_GENESIS_BOOTSTRAP_HEADERS, PersistedHeaderRound,
23};
24pub use light_index::{
25    EncryptedHnsLightIndex, HNS_LIGHT_INDEX_FORMAT_VERSION, HnsLightIndexError, HnsLightScanStatus,
26    HnsLightWatchSet, VerifiedHnsNameProof, VerifiedHnsTransactionObservation,
27    recovered_hns_htlc_funding_locator,
28};
29pub use name_workflow::{
30    AuthorizedNameOperation, CurrentShakedexLockQuery, HnsNameAction, HnsNameLifecycle,
31    NameActionContextEvidence, NameActionIneligibility, NameOperation, NameOperationState,
32    PrepareNameFinalize, PrepareNameTransfer, PrepareNameUpdate, PreparedNameOperation,
33    VerifiedCurrentShakedexLock, VerifiedCurrentShakedexLockBatch,
34    VerifiedCurrentShakedexLockEntry, VerifiedCurrentShakedexTransfer,
35    VerifiedOutgoingNameTransfer,
36};
37pub use node_rpc::{HnsCanonicalBlock, HnsNodeRpcBackend, HnsNodeRpcConfig};
38pub use peer_coordinator::{
39    ConnectedHnsPeer, HnsBlockScanBatchTelemetry, HnsBlockScanProgress, HnsDirectPeerConfig,
40    HnsDirectPeerCoordinator, HnsDirectPeerError, HnsDirectShakescapeListener,
41    HnsDirectShakescapeMessage, HnsDirectShakescapePeer, HnsHeaderRoundProgress,
42    HnsInboundMobilePeer, HnsInboundNetworkPeer, HnsPublicHeaderTransport, HnsPublicPeerSessions,
43    HnsShakescapeCandidate, HnsShakescapeDirectFailure, HnsShakescapeDiscoveryStatus,
44    NativeHnsPeerPool, open_wallet_direct_hns_peer_coordinator,
45    open_wallet_direct_hns_peer_coordinator_with_floor,
46    open_wallet_direct_hns_peer_coordinator_with_floor_and_checkpoint_bootstrap,
47    open_wallet_direct_hns_peer_coordinator_with_floor_and_genesis_bootstrap,
48    open_wallet_direct_hns_peer_coordinator_with_floor_and_public_peer_sessions,
49    open_wallet_direct_hns_peer_coordinator_with_floor_checkpoint_and_public_peer_sessions,
50};
51pub use recovery_publication::{
52    HnsRecoverableFundingPlan, HnsRecoveryContract, build_recovered_hns_htlc,
53    discover_hns_recovery_contracts, hns_recovery_anchor_program, prepare_hns_recoverable_funding,
54    recover_hns_contract_from_ancestors,
55};
56pub use shakedex_funding::{
57    HnsPreparedShakedexFunding, HnsShakedexChangeReservation,
58    HnsShakedexFundingApprovalExpectation, HnsShakedexFundingAuthorization,
59    HnsShakedexFundingPurpose, HnsShakedexFundingReservation, HnsShakedexFundingReservationBatch,
60    HnsShakedexFundingReservationState, HnsShakedexFundingScope, HnsShakedexTransactionObservation,
61    activate_hns_shakedex_funding_reservations, create_hns_shakedex_funding_reservations,
62    delete_hns_shakedex_funding_reservations, retain_active_hns_shakedex_funding_reservations,
63    validate_hns_shakedex_final_fee_quote_evidence,
64    validate_hns_shakedex_finalize_final_fee_quote_evidence,
65    validate_hns_shakedex_funding_reservations, validate_persisted_hns_shakedex_fee_quote_evidence,
66};
67pub use shakedex_key::{
68    HnsShakedexKeyAllocation, HnsShakedexKeyAllocationError, HnsShakedexKeyAllocationRequest,
69    HnsShakedexSellerTerms, HnsShakedexSigner,
70};
71
72use name_workflow::{HnsInputReservationKind, HnsNameWorkflow};
73
74use core::fmt;
75use std::collections::{BTreeMap, BTreeSet, HashSet, btree_map::Entry};
76use std::sync::{Mutex, RwLock};
77use std::time::{SystemTime, UNIX_EPOCH};
78
79use bech32::{Hrp, segwit};
80use bip32::{DerivationPath, XPrv};
81use bip39::{Language, Mnemonic};
82use blake2::Blake2bVar;
83use blake2::digest::VariableOutput;
84use hkdf::Hkdf;
85use hns_covenants::{
86    Covenant, CovenantKind, FinalizeCovenant, MAX_RESOURCE_SIZE, NameState, Resource,
87    TransferCovenant, hash_name, validate_name,
88};
89use hns_primitives::{
90    BlockHash, Dollarydoos, Height, NameHash, TransactionHash as CanonicalTransactionHash, TreeRoot,
91};
92use hns_script::{
93    FeeRate, K256SignatureVerifier, LOCKTIME_FLAG, LOCKTIME_MASK, LOCKTIME_MULTIPLIER,
94    MAX_POLICY_TRANSACTION_SIGOPS, MAX_POLICY_TRANSACTION_WEIGHT, OP_BLAKE160,
95    OP_CHECKLOCKTIMEVERIFY, OP_CHECKSIG, OP_DROP, OP_DUP, OP_ELSE, OP_ENDIF, OP_EQUALVERIFY, OP_IF,
96    OP_SHA256, SIGHASH_ALL, ScriptFlags, minimum_policy_fee, signature_hash,
97    transaction_policy_virtual_size, transaction_sigops, verify_witness_program,
98};
99use hns_swap::{HnsHtlc, HnsHtlcSpend, NetworkBinding, lock_script_hash};
100use hns_transaction::{Address, Coin, Input, Outpoint, Output, Transaction, Witness};
101use hns_urkel_proof::{ProofKind, UrkelProof};
102use hns_wallet_chain_api::{
103    AtomicSettlement, AuthorizeSend, AuthorizedSend, BroadcastReceipt, BroadcastSend, ChainError,
104    ChainModule, HtlcLockRequest, HtlcRedeemRequest, HtlcRefundRequest, ModuleRegistry,
105    ObservePreimageRequest, ObserveSecretRequest, Preimage, PreparedArtifact, PreparedHtlcLock,
106    PreparedHtlcRedeem, PreparedHtlcRefund, PreparedSend, PreparedSettlementLock,
107    PreparedSettlementRedeem, PreparedSettlementRefund, RegistryError, SendRequest,
108    SettlementCapabilities, SettlementLockExpectation, SettlementLockRequest,
109    SettlementRedeemRequest, SettlementRefundRequest, SettlementSigner, Utxo, UtxoChainModule,
110    UtxoFeePolicy, VerifiedHtlcLock, VerifiedLock, VerifiedSettlementLock, VerifyHtlcLockRequest,
111    VerifySettlementLockRequest,
112};
113use hns_wallet_store::{
114    EntityBatchDelete, EntityBatchSave, EntityKind, EntityPrefixSetLease, EntityReadSnapshot,
115    EntityRevisionAssertion, SecretKind, SharedWalletStore, SharedWalletStoreGuard, StoreError,
116    StoredEntity, StoredWorkflow, WalletStore, WorkflowRevisionAssertion,
117};
118use hns_wallet_types::{
119    AccountId, Amount, ApprovalId, BaseUnits, ChainCapabilities, DerivationReference, FeeModel,
120    FinalityModel, HashAlgorithm, HnsNameReceiveTarget, KeyRole, LocalTransactionStatus,
121    LocktimeModel, ModuleId, ObjectHash, ReceiveTarget, SessionId, SignedBaseUnits, SyncPhase,
122    SyncStatus, TransactionHash, TransactionSummary, WalletAsset, WalletId, WorkflowId,
123    WorkflowKind,
124};
125use k256::ecdsa::signature::hazmat::{PrehashSigner, PrehashVerifier};
126use k256::ecdsa::{Signature, SigningKey, VerifyingKey};
127use serde::{Deserialize, Serialize};
128use sha2::{Digest, Sha256};
129use sha3::Sha3_256;
130use thiserror::Error;
131use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
132
133pub const HNS_DERIVATION_DOMAIN: &[u8] = b"hns-wallet-rs/hns-role-key/v1";
134pub const HNS_SETTLEMENT_KEY_DOMAIN: &[u8] = b"hns-wallet-rs/hns-settlement-key/v1";
135pub const MAX_RESTORE_LOOKAHEAD: u32 = 10_000;
136pub const MAX_RESTORE_SCRIPTS_PER_QUERY: usize = 10_000;
137/// The coin, dedicated name, and Shakedex lock branches are queried separately
138/// so no branch reduces another's bounded lookahead. Persisted address records
139/// are nevertheless bounded as one account-owned collection.
140pub const MAX_RESTORE_ADDRESS_RECORDS: usize = MAX_RESTORE_SCRIPTS_PER_QUERY * 3;
141pub const DEFAULT_RESTORE_LOOKAHEAD: u32 = 100;
142pub const MAX_WALLET_COINS: usize = 10_000;
143pub const MAX_HISTORY_RESULTS: usize = 10_000;
144pub const MAX_RECOVERY_CHECKPOINTS: usize = 288;
145pub const MAX_TRANSACTION_INPUTS: usize = 10_000;
146pub const PREPARED_ARTIFACT_LIFETIME_SECONDS: u64 = 300;
147/// Keep a newly submitted send in the durable broadcast state while connected
148/// peers have time to announce it back through their mempool inventory. A
149/// successful socket write is not itself remote mempool evidence.
150pub const SEND_PROPAGATION_GRACE_SECONDS: u64 = 120;
151pub const DEFAULT_DUST_THRESHOLD: u128 = 546;
152pub const HNS_LOCKTIME_THRESHOLD: u64 = 500_000_000;
153pub const MAX_SCAN_PAGE_RESULTS: usize = 256;
154pub const MAX_MEMPOOL_SCAN_RESULTS: usize = 1_024;
155pub const MAX_OUTPOINT_SPEND_BATCH: usize = 256;
156/// Maximum number of exact name/seller lock queries that may share one
157/// selected-account, chain, mempool, and trusted-time observation.
158pub const MAX_CURRENT_SHAKEDEX_LOCK_BATCH: usize = 64;
159pub const MAX_SCAN_CURSOR_BYTES: usize = 4_096;
160pub const MAX_SCAN_PAGES: usize = 128;
161/// Stable diagnostic marker for the one recoverable case where a direct
162/// filtered-block index has reached its tip but a newly discovered trailing
163/// restoration window has not been watched yet. Hosts must expand and rewind
164/// the public watch set before retrying; they must never publish a projection
165/// from the incomplete index.
166pub const DIRECT_WALLET_INDEX_WATCH_SET_INCOMPLETE_MESSAGE: &str =
167    "direct wallet index watch set does not cover the requested derivation scripts";
168/// Incoming TRANSFER pages can return after the first nonempty script, so one
169/// candidate on each supported name derivation can require one page per row.
170/// The additive term covers pages that consume only the endpoint's bounded
171/// batch of empty script prefixes.
172const MAX_INCOMING_TRANSFER_PAGES: usize =
173    MAX_HISTORY_RESULTS + MAX_RESTORE_SCRIPTS_PER_QUERY.div_ceil(MAX_SCAN_PAGE_RESULTS);
174pub const MAX_SNAPSHOT_RESTARTS: usize = 3;
175pub const DEFAULT_FEE_TARGET_BLOCKS: u16 = 6;
176/// Canonical HSD fee-policy algebra is enabled for the integrated product flow.
177/// Final distribution qualification is performed over the assembled product,
178/// rather than blocking runtime exercise of this implementation.
179pub const HNS_FEE_QUOTE_ALGEBRA_RELEASE_QUALIFIED: bool = true;
180/// Protected Shakedex source/funding reservation and suffix signing are enabled
181/// for the integrated product flow.
182pub const HNS_SHAKEDEX_FUNDING_RELEASE_QUALIFIED: bool = true;
183/// Concrete HNS value operations are enabled for integrated mainnet testing.
184pub const HNS_VALUE_RUNTIME_RELEASE_QUALIFIED: bool = true;
185
186#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
187#[serde(rename_all = "lowercase")]
188pub enum HnsNetwork {
189    Mainnet,
190    Testnet,
191    Regtest,
192    Simnet,
193}
194
195impl HnsNetwork {
196    const fn hrp(self) -> &'static str {
197        match self {
198            Self::Mainnet => "hs",
199            Self::Testnet => "ts",
200            Self::Regtest => "rs",
201            Self::Simnet => "ss",
202        }
203    }
204}
205
206/// Explicit chain policy for the one-account native-wallet bootstrap.
207///
208/// Account derivation, gap limits, confirmation policy, dust policy, and all
209/// value gates remain fixed by the reviewed wallet defaults. A product must
210/// choose the network and an honest restore birthday instead of inheriting a
211/// network-dependent implicit value.
212#[derive(Clone, Copy, Debug, Eq, PartialEq)]
213pub struct HnsBootstrapPolicy {
214    pub network: HnsNetwork,
215    pub birthday_height: u64,
216}
217
218impl HnsBootstrapPolicy {
219    pub const fn new(network: HnsNetwork, birthday_height: u64) -> Self {
220        Self {
221            network,
222            birthday_height,
223        }
224    }
225}
226
227fn shakedex_network_binding(network: HnsNetwork) -> Result<NetworkBinding, HnsWalletError> {
228    let (_, genesis_hash) = name_workflow::expected_chain_identity(network)?;
229    let magic = match network {
230        HnsNetwork::Mainnet => 0x5b6e_f2d3,
231        HnsNetwork::Testnet => 0xb152_0dd2,
232        HnsNetwork::Regtest => 0xae38_95cf,
233        HnsNetwork::Simnet => 0x0e64_8edc,
234    };
235    Ok(NetworkBinding {
236        magic,
237        genesis: BlockHash::new(genesis_hash),
238    })
239}
240
241/// Reconstruct the exact local Handshake binding used by the direct Shakescape
242/// HNS/BTC protocol. This is derived only from the selected wallet network;
243/// it has no relay, peer, indexer, or price-policy input.
244pub fn direct_shakescape_network_binding(
245    network: HnsNetwork,
246) -> Result<NetworkBinding, HnsWalletError> {
247    shakedex_network_binding(network)
248}
249
250#[derive(Zeroize, ZeroizeOnDrop)]
251pub struct RecoveryPhrase(String);
252
253impl RecoveryPhrase {
254    /// Dedicated high-risk display boundary. Provider and ordinary FFI
255    /// operations must never call this method.
256    pub fn expose_for_dedicated_display(mut self) -> String {
257        core::mem::take(&mut self.0)
258    }
259}
260
261impl fmt::Debug for RecoveryPhrase {
262    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
263        formatter.write_str("RecoveryPhrase([REDACTED])")
264    }
265}
266
267#[derive(Debug)]
268pub struct CreatedWallet {
269    pub wallet_id: WalletId,
270    pub recovery_phrase: RecoveryPhrase,
271}
272
273fn generate_24_word_mnemonic() -> Result<Mnemonic, HnsWalletError> {
274    Mnemonic::generate_in(Language::English, 24).map_err(|_| HnsWalletError::Randomness)
275}
276
277/// Generates the random wallet-local identifier used by the existing create
278/// path. Recovery deliberately derives its identifier from the mnemonic
279/// instead, preserving the established wallet semantics.
280pub fn generate_wallet_id() -> Result<WalletId, HnsWalletError> {
281    let mut wallet_id = [0_u8; 16];
282    getrandom::fill(&mut wallet_id).map_err(|_| HnsWalletError::Randomness)?;
283    Ok(WalletId::new(wallet_id))
284}
285
286/// Generates a nonzero random account identifier. This identifier is local
287/// profile metadata; on-chain recovery is anchored by the stable account
288/// derivation index rather than this random value.
289pub fn generate_account_id() -> Result<AccountId, HnsWalletError> {
290    for _ in 0..16 {
291        let mut account_id = [0_u8; 16];
292        getrandom::fill(&mut account_id).map_err(|_| HnsWalletError::Randomness)?;
293        if account_id != [0_u8; 16] {
294            return Ok(AccountId::new(account_id));
295        }
296    }
297    Err(HnsWalletError::Randomness)
298}
299
300fn wallet_id_from_mnemonic(mnemonic: &Mnemonic) -> WalletId {
301    let mut hasher = Sha256::new();
302    hasher.update(b"hns-wallet-id/v1");
303    let seed = Zeroizing::new(mnemonic.to_seed_normalized(""));
304    hasher.update(seed.as_slice());
305    let digest: [u8; 32] = hasher.finalize().into();
306    let mut id = [0_u8; 16];
307    id.copy_from_slice(&digest[..16]);
308    WalletId::new(id)
309}
310
311pub fn create_wallet(
312    store: &mut WalletStore,
313    now_unix: u64,
314) -> Result<CreatedWallet, HnsWalletError> {
315    let mnemonic = generate_24_word_mnemonic()?;
316    let wallet_id = generate_wallet_id()?;
317    store_seed(store, wallet_id, &mnemonic, now_unix)?;
318    Ok(CreatedWallet {
319        wallet_id,
320        recovery_phrase: RecoveryPhrase(mnemonic.to_string()),
321    })
322}
323
324pub fn restore_wallet(
325    store: &mut WalletStore,
326    phrase: &str,
327    now_unix: u64,
328) -> Result<WalletId, HnsWalletError> {
329    let mnemonic = Mnemonic::parse_in_normalized(Language::English, phrase)
330        .map_err(|_| HnsWalletError::InvalidRecoveryPhrase)?;
331    let wallet_id = wallet_id_from_mnemonic(&mnemonic);
332    store_seed(store, wallet_id, &mnemonic, now_unix)?;
333    Ok(wallet_id)
334}
335
336fn store_seed(
337    store: &mut WalletStore,
338    wallet_id: WalletId,
339    mnemonic: &Mnemonic,
340    now_unix: u64,
341) -> Result<(), HnsWalletError> {
342    let seed = Zeroizing::new(mnemonic.to_seed_normalized(""));
343    store.put_secret(
344        wallet_id.as_bytes(),
345        SecretKind::RecoverySeed,
346        seed.as_slice(),
347        now_unix,
348    )?;
349    Ok(())
350}
351
352/// Derive ordinary HNS authority from the canonical hsd/Bob BIP-44 tree.
353/// Script-specific ShakeDex and application keys remain role-separated.
354pub fn derive_hns_account_public_key(
355    store: &WalletStore,
356    account: &HnsAccountRecord,
357    reference: DerivationReference,
358) -> Result<[u8; 33], HnsWalletError> {
359    if reference.account != account_number(account) {
360        return Err(HnsWalletError::AccountConfigurationMismatch);
361    }
362    let seed = store
363        .get_secret(
364            account.config.wallet_id.as_bytes(),
365            SecretKind::RecoverySeed,
366        )?
367        .ok_or(HnsWalletError::MissingSeed)?;
368    let secret = derive_account_secret(&seed, account.config.network, reference)?;
369    let signing =
370        SigningKey::from_slice(secret.as_slice()).map_err(|_| HnsWalletError::KeyDerivation)?;
371    signing
372        .verifying_key()
373        .to_sec1_point(true)
374        .as_bytes()
375        .try_into()
376        .map_err(|_| HnsWalletError::KeyDerivation)
377}
378
379fn derive_account_secret(
380    seed: &[u8],
381    network: HnsNetwork,
382    reference: DerivationReference,
383) -> Result<Zeroizing<[u8; 32]>, HnsWalletError> {
384    match reference.role {
385        KeyRole::HnsCoin => derive_hsd_bip44_secret(seed, network, reference),
386        KeyRole::HnsName => Err(HnsWalletError::WrongKeyRole),
387        _ => derive_secret(seed, reference),
388    }
389}
390
391fn derive_hsd_bip44_secret(
392    seed: &[u8],
393    network: HnsNetwork,
394    reference: DerivationReference,
395) -> Result<Zeroizing<[u8; 32]>, HnsWalletError> {
396    if reference.change > 1 {
397        return Err(HnsWalletError::KeyDerivation);
398    }
399    if reference.role != KeyRole::HnsCoin {
400        return Err(HnsWalletError::WrongKeyRole);
401    }
402    // Account zero is exactly m/44'/5353'/0'/change/index, matching hsd and
403    // Bob. HNS value and name ownership use the same ordinary account.
404    let bip44_account = reference.account;
405    let path = format!(
406        "m/44'/{}'/{}'/{}/{}",
407        hsd_bip44_coin_type(network),
408        bip44_account,
409        reference.change,
410        reference.index
411    )
412    .parse::<DerivationPath>()
413    .map_err(|_| HnsWalletError::KeyDerivation)?;
414    let child = XPrv::derive_from_path(seed, &path).map_err(|_| HnsWalletError::KeyDerivation)?;
415    Ok(Zeroizing::new(child.private_key().to_bytes().into()))
416}
417
418const fn hsd_bip44_coin_type(network: HnsNetwork) -> u32 {
419    // hsd lib/protocol/networks.js `keyPrefix.coinType`.
420    match network {
421        HnsNetwork::Mainnet => 5353,
422        HnsNetwork::Testnet => 5354,
423        HnsNetwork::Regtest => 5355,
424        HnsNetwork::Simnet => 5356,
425    }
426}
427
428fn derive_secret(
429    seed: &[u8],
430    reference: DerivationReference,
431) -> Result<Zeroizing<[u8; 32]>, HnsWalletError> {
432    let role = key_role_code(reference.role).ok_or(HnsWalletError::WrongKeyRole)?;
433    for counter in 0_u8..=u8::MAX {
434        let mut info = Vec::with_capacity(HNS_DERIVATION_DOMAIN.len() + 18);
435        info.extend_from_slice(HNS_DERIVATION_DOMAIN);
436        info.extend_from_slice(&role.to_be_bytes());
437        info.extend_from_slice(&reference.account.to_be_bytes());
438        info.extend_from_slice(&reference.change.to_be_bytes());
439        info.extend_from_slice(&reference.index.to_be_bytes());
440        info.push(counter);
441        let hkdf = Hkdf::<Sha256>::new(Some(b"Handshake role separation"), seed);
442        let mut candidate = Zeroizing::new([0_u8; 32]);
443        hkdf.expand(&info, candidate.as_mut())
444            .map_err(|_| HnsWalletError::KeyDerivation)?;
445        if SigningKey::from_slice(candidate.as_slice()).is_ok() {
446            return Ok(candidate);
447        }
448    }
449    Err(HnsWalletError::KeyDerivation)
450}
451
452const fn key_role_code(role: KeyRole) -> Option<u32> {
453    match role {
454        KeyRole::HnsCoin => None,
455        KeyRole::HnsName => None,
456        KeyRole::HnsShakedex => Some(2),
457        KeyRole::HnsAtomicSwap => Some(3),
458        KeyRole::HnsIdentity => Some(4),
459        KeyRole::HnsDappSession => Some(5),
460        _ => None,
461    }
462}
463
464pub fn receive_address(
465    network: HnsNetwork,
466    compressed_public_key: &[u8; 33],
467) -> Result<String, HnsWalletError> {
468    let program = public_key_hash(compressed_public_key)?;
469    encode_v0_address(network, &program)
470}
471
472/// Derive an ordinary payment receive target from authenticated wallet-local
473/// state. Callers fence the selected account before and after this helper; it
474/// never contacts a backend, mutates the store, or advances a derivation
475/// index.
476fn local_hns_payment_receive_target(
477    store: &SharedWalletStore,
478    account: &HnsAccountRecord,
479) -> Result<ReceiveTarget, HnsWalletError> {
480    store.try_with_store(|store| hns_payment_receive_target(store, account))
481}
482
483fn hns_payment_receive_target(
484    store: &WalletStore,
485    account: &HnsAccountRecord,
486) -> Result<ReceiveTarget, HnsWalletError> {
487    let derivation = DerivationReference {
488        role: KeyRole::HnsCoin,
489        account: account_number(account),
490        change: 0,
491        index: account.next_receive_index,
492    };
493    let public_key = derive_hns_account_public_key(store, account, derivation)?;
494    let target = ReceiveTarget {
495        module: ModuleId::Handshake,
496        account: account.config.account_id,
497        display: receive_address(account.config.network, &public_key)?,
498        derivation_index: derivation.index,
499    };
500    target
501        .validate()
502        .map_err(|_| HnsWalletError::InvalidEvidence)?;
503    Ok(target)
504}
505
506/// Project the one canonical hsd/Bob receive target into the name-transfer
507/// DTO without deriving or persisting a second ordinary address branch.
508fn hns_name_receive_target_from_payment(
509    payment: &ReceiveTarget,
510) -> Result<HnsNameReceiveTarget, HnsWalletError> {
511    let target = HnsNameReceiveTarget {
512        module: payment.module,
513        account: payment.account,
514        display: payment.display.clone(),
515        derivation_index: payment.derivation_index,
516    };
517    target
518        .validate()
519        .map_err(|_| HnsWalletError::InvalidEvidence)?;
520    Ok(target)
521}
522
523fn encode_v0_address(network: HnsNetwork, program: &[u8]) -> Result<String, HnsWalletError> {
524    let hrp = Hrp::parse(network.hrp()).map_err(|_| HnsWalletError::Address)?;
525    segwit::encode_v0(hrp, program).map_err(|_| HnsWalletError::Address)
526}
527
528#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
529pub struct WalletCoin {
530    pub outpoint: HnsOutpoint,
531    pub value: BaseUnits,
532    pub confirmation_count: u32,
533    /// Exact active-chain inclusion height supplied by the confirmed wallet
534    /// index. `None` is accepted only while decoding a legacy row; such a row
535    /// cannot become transaction input evidence.
536    #[serde(default)]
537    pub confirmed_height: Option<u32>,
538    /// Exact node evidence. Coinbase outputs remain conservatively excluded
539    /// until a released canonical maturity policy is wired into selection.
540    #[serde(default = "coinbase_evidence_unknown")]
541    pub coinbase: bool,
542    /// Canonical encoded Handshake covenant. An empty legacy default is never
543    /// interpreted as `NONE`; conversion to a consensus coin fails closed.
544    #[serde(default)]
545    pub covenant: Vec<u8>,
546    pub name_locked: bool,
547}
548
549const fn coinbase_evidence_unknown() -> bool {
550    true
551}
552
553#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
554pub struct HnsOutpoint {
555    pub transaction: TransactionHash,
556    pub output_index: u32,
557}
558
559pub fn select_coins(
560    coins: &[WalletCoin],
561    target: BaseUnits,
562) -> Result<CoinSelection, HnsWalletError> {
563    if target.is_zero() || coins.len() > MAX_WALLET_COINS {
564        return Err(HnsWalletError::InvalidAmount);
565    }
566    let mut candidates: Vec<_> = coins
567        .iter()
568        .filter(|coin| !coin.name_locked && !coin.coinbase)
569        .cloned()
570        .collect();
571    candidates.sort_by(|left, right| {
572        right
573            .value
574            .cmp(&left.value)
575            .then_with(|| left.outpoint.cmp(&right.outpoint))
576    });
577    let mut selected = Vec::new();
578    let mut total = BaseUnits::ZERO;
579    for coin in candidates {
580        total = total
581            .checked_add(coin.value)
582            .map_err(|_| HnsWalletError::Arithmetic)?;
583        selected.push(coin);
584        if total >= target {
585            let change = total
586                .checked_sub(target)
587                .map_err(|_| HnsWalletError::Arithmetic)?;
588            return Ok(CoinSelection {
589                coins: selected,
590                total,
591                change,
592            });
593        }
594    }
595    Err(HnsWalletError::InsufficientFunds)
596}
597
598#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
599pub struct CoinSelection {
600    pub coins: Vec<WalletCoin>,
601    pub total: BaseUnits,
602    pub change: BaseUnits,
603}
604
605pub const MAX_SHAKESCAPE_NAME_MARKET_TRANSPORT_PAGE: usize = 256;
606pub const MAX_SHAKESCAPE_NAME_MARKET_ENVELOPE_BYTES: usize = 16 * 1024;
607
608#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
609#[serde(rename_all = "snake_case")]
610pub enum ShakescapeTransportMessageKind {
611    Offer,
612    Cancellation,
613}
614
615/// Exact durable publication attempt sent to the authenticated local node.
616#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
617pub struct ShakescapePublicationHandoff {
618    pub network_magic: u32,
619    pub network_genesis: [u8; 32],
620    pub attempt_id: [u8; 32],
621    pub record_sequence: u64,
622    pub prepared_at_unix: u64,
623    pub envelope_id: [u8; 32],
624    pub envelope_digest: [u8; 32],
625    pub content_id: [u8; 32],
626    pub message_kind: ShakescapeTransportMessageKind,
627    pub request_id: u64,
628}
629
630#[derive(Clone, Debug, Eq, PartialEq)]
631pub struct ShakescapePublicationAcceptance {
632    pub relay_revision: u64,
633    pub kind: ShakescapeTransportMessageKind,
634    pub content_id: [u8; 32],
635    pub inserted: bool,
636    pub accepted_at_unix: u64,
637    pub receipt_bytes: Vec<u8>,
638    pub propagation_attempted: usize,
639    pub propagation_written: usize,
640    pub propagation_failed: usize,
641}
642
643#[derive(Clone, Debug, Eq, PartialEq)]
644pub struct ShakescapeTransportEvent {
645    pub revision: u64,
646    pub received_at_unix: u64,
647    pub kind: ShakescapeTransportMessageKind,
648    pub content_id: [u8; 32],
649    pub envelope_bytes: Vec<u8>,
650}
651
652#[derive(Clone, Debug, Eq, PartialEq)]
653pub struct ShakescapeTransportEventPage {
654    pub instance_nonce: [u8; 32],
655    pub cursor_reset: bool,
656    pub oldest_revision: u64,
657    pub head_revision: u64,
658    pub events: Vec<ShakescapeTransportEvent>,
659}
660
661#[derive(Clone, Debug, Eq, PartialEq)]
662pub struct ShakescapeTransportSnapshotRecord {
663    pub kind: ShakescapeTransportMessageKind,
664    pub content_id: [u8; 32],
665    pub envelope_bytes: Vec<u8>,
666}
667
668#[derive(Clone, Debug, Eq, PartialEq)]
669pub struct ShakescapeTransportSnapshotPage {
670    pub instance_nonce: [u8; 32],
671    pub snapshot_revision: u64,
672    pub next_offset: Option<usize>,
673    pub records: Vec<ShakescapeTransportSnapshotRecord>,
674}
675
676pub trait HnsBackend {
677    /// Returns the current initialized tip and durable chain epoch without
678    /// receiving any wallet script identifiers.
679    fn get_chain_snapshot(&self) -> Result<SnapshotBinding, HnsWalletError>;
680    fn get_chain_tip(&self) -> Result<ChainTip, HnsWalletError>;
681    fn get_block_hash(
682        &self,
683        height: u64,
684        binding: SnapshotBinding,
685    ) -> Result<BlockHashEvidence, HnsWalletError>;
686    /// Pages confirmed history and UTXOs over the complete sorted script set.
687    /// The adapter must reject a stale epoch/cursor with `StaleNodeSnapshot`.
688    fn get_confirmed_wallet_page(
689        &self,
690        request: ConfirmedWalletPageRequest<'_>,
691    ) -> Result<ConfirmedWalletPage, HnsWalletError>;
692    /// Pages active confirmed TRANSFERs whose covenant recipient matches the
693    /// complete sorted script set. These rows are derivation-discovery hints
694    /// only: their Coin is still locked to the old owner's output address.
695    fn get_incoming_transfers_page(
696        &self,
697        _request: IncomingTransfersPageRequest<'_>,
698    ) -> Result<IncomingTransfersPage, HnsWalletError> {
699        Err(HnsWalletError::RuntimeIntegrationUnavailable)
700    }
701    /// Pages mempool history at one node-instance/generation pair, also tied
702    /// to the confirmed chain binding and exact script set. The adapter must
703    /// reject a stale instance, generation, script set, or cursor.
704    fn get_mempool_wallet_page(
705        &self,
706        request: MempoolWalletPageRequest<'_>,
707    ) -> Result<MempoolWalletPage, HnsWalletError>;
708    /// Acquire one process-instance/generation fence for current Shakedex
709    /// lock verification. Full-node adapters retain the default exact-script
710    /// page query. A filtered direct-wallet adapter may override this only
711    /// when its peer coordinator has installed and refreshed a filter that
712    /// covers the exact remote lock outpoints before invoking the verifier.
713    fn get_shakedex_mempool_snapshot(
714        &self,
715        scripts: &[WalletAddressKey],
716        binding: SnapshotBinding,
717        expected_mempool: Option<MempoolSnapshotBinding>,
718    ) -> Result<MempoolSnapshotBinding, HnsWalletError> {
719        let page = self.get_mempool_wallet_page(MempoolWalletPageRequest {
720            scripts,
721            binding,
722            expected_mempool,
723            cursor: None,
724            limit: 1,
725        })?;
726        if page.binding != binding
727            || page.mempool.instance_nonce == [0; 32]
728            || expected_mempool.is_some_and(|expected| page.mempool != expected)
729            || page.history.len() > 1
730        {
731            return Err(HnsWalletError::StaleNodeSnapshot);
732        }
733        Ok(page.mempool)
734    }
735    /// Returns raw bytes, status, and inclusion from one canonical snapshot.
736    /// A pruned node may omit raw bytes, but not the other fields.
737    fn get_transaction_evidence(
738        &self,
739        txid: TransactionHash,
740        binding: SnapshotBinding,
741        expected_mempool: Option<MempoolSnapshotBinding>,
742    ) -> Result<TransactionEvidence, HnsWalletError>;
743    fn get_outpoint_spend_evidence(
744        &self,
745        outpoints: &[HnsOutpoint],
746        binding: SnapshotBinding,
747    ) -> Result<OutpointSpendEvidence, HnsWalletError>;
748    fn broadcast_transaction(&self, raw: &[u8]) -> Result<TransactionHash, HnsWalletError>;
749    /// Extend a direct wallet's public filter for a locally allocated future
750    /// change-gap script while retaining authenticated historical coverage.
751    /// Full-node backends need no such filter maintenance. Embedded backends
752    /// must return `false` unless the persisted account proves the exact safe
753    /// forward-only transition.
754    fn extend_locally_allocated_change_watch_set(
755        &self,
756        _account: &HnsAccountRecord,
757        _now_unix: u64,
758    ) -> Result<bool, HnsWalletError> {
759        Ok(false)
760    }
761    /// Quotes one exact serialized transaction against the complete wallet
762    /// reconciliation binding. The ordered coins are exact wallet evidence;
763    /// the node resolves the same outpoints and returns policy/rate evidence
764    /// for independent local comparison. This method never signs or submits.
765    fn quote_transaction_fee(
766        &self,
767        raw: &[u8],
768        input_coins: &[Coin],
769        target_blocks: u16,
770        binding: SnapshotBinding,
771        expected_mempool: MempoolSnapshotBinding,
772    ) -> Result<HnsTransactionFeeQuote, HnsWalletError>;
773    /// Node estimate in atomic units per 1,000 HSD policy virtual bytes. The
774    /// wallet applies it only through pinned canonical sigop-adjusted policy
775    /// sizing; the enclosing value gate remains independently unavailable.
776    fn estimate_fee_rate(&self, target_blocks: u16) -> Result<BaseUnits, HnsWalletError>;
777    /// Returns the interval-committed proof view and current name view without
778    /// collapsing them. Every field is tied to the supplied snapshot binding.
779    fn get_name_evidence(
780        &self,
781        name_hash: [u8; 32],
782        binding: SnapshotBinding,
783    ) -> Result<NameEvidence, HnsWalletError>;
784    /// Returns the exact active UTXO selected by the current NameState without
785    /// requiring retained transaction or block bytes. This is trusted-node
786    /// discovery evidence, never signing or mutation authority.
787    fn get_active_name_owner_coin(
788        &self,
789        _name_hash: [u8; 32],
790        _binding: SnapshotBinding,
791    ) -> Result<ActiveNameOwnerCoinEvidence, HnsWalletError> {
792        Err(HnsWalletError::RuntimeIntegrationUnavailable)
793    }
794    /// Returns candidate-height TRANSFER/FINALIZE policy, exact owner, active
795    /// chain, and owner-spender evidence from one authenticated chain/mempool
796    /// snapshot. The wallet independently validates every projection.
797    fn get_name_action_context(
798        &self,
799        action: HnsNameAction,
800        name_hash: [u8; 32],
801        binding: SnapshotBinding,
802        expected_mempool: MempoolSnapshotBinding,
803    ) -> Result<NameActionContextEvidence, HnsWalletError>;
804
805    /// Returns the pruning-safe version-2 action context whose active owner
806    /// is represented by exact current UTXO evidence rather than retained raw
807    /// transaction bytes. The default keeps older backend implementations
808    /// source-compatible while failing closed if they are selected for a v2
809    /// operation.
810    fn get_name_action_context_v2(
811        &self,
812        _action: HnsNameAction,
813        _name_hash: [u8; 32],
814        _binding: SnapshotBinding,
815        _expected_mempool: MempoolSnapshotBinding,
816    ) -> Result<NameActionContextEvidence, HnsWalletError> {
817        Err(HnsWalletError::RuntimeIntegrationUnavailable)
818    }
819
820    /// Hand one exact durably prepared Shakescape publication to the authenticated
821    /// local node and require its endpoint-signed acceptance receipt.
822    fn publish_shakescape_name_market(
823        &self,
824        _envelope_bytes: &[u8],
825        _handoff: ShakescapePublicationHandoff,
826    ) -> Result<ShakescapePublicationAcceptance, HnsWalletError> {
827        Err(HnsWalletError::RuntimeIntegrationUnavailable)
828    }
829
830    /// Read one process-instance-bound page of untrusted marketplace events.
831    fn get_shakescape_name_market_events(
832        &self,
833        _expected_instance_nonce: Option<[u8; 32]>,
834        _after_revision: u64,
835        _limit: usize,
836    ) -> Result<ShakescapeTransportEventPage, HnsWalletError> {
837        Err(HnsWalletError::RuntimeIntegrationUnavailable)
838    }
839
840    /// Rebuild from a coherent latest-state snapshot after a node restart or
841    /// retained-event-window gap.
842    fn get_shakescape_name_market_snapshot(
843        &self,
844        _expected_revision: Option<u64>,
845        _offset: usize,
846        _limit: usize,
847    ) -> Result<ShakescapeTransportSnapshotPage, HnsWalletError> {
848        Err(HnsWalletError::RuntimeIntegrationUnavailable)
849    }
850}
851
852#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
853pub struct ChainTip {
854    pub height: u64,
855    pub block_hash: [u8; 32],
856    pub tree_root: [u8; 32],
857    /// Median time past of this exact tip. For a candidate transaction this
858    /// is the consensus parent time used by Shakedex absolute-lock checks.
859    /// A zero from legacy persisted data is non-authoritative until refreshed.
860    #[serde(default)]
861    pub median_time_past: u64,
862}
863
864#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
865pub struct SnapshotBinding {
866    pub tip: ChainTip,
867    /// Durable monotonic canonical-chain epoch owned by the node wallet index.
868    pub chain_epoch: u64,
869}
870
871#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
872pub struct BlockHashEvidence {
873    pub binding: SnapshotBinding,
874    pub height: u64,
875    pub block_hash: Option<[u8; 32]>,
876}
877
878#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
879pub struct TransactionStatus {
880    pub in_mempool: bool,
881    pub confirmation_count: u32,
882    pub conflicted: bool,
883}
884
885#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
886pub struct TransactionInclusion {
887    pub block_hash: [u8; 32],
888    pub height: u64,
889    /// Exact block transaction position when retained payload permits the node
890    /// to derive it. A pruned payload must remain `None`, never invented zero.
891    pub transaction_index: Option<u32>,
892}
893
894#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
895pub struct HistoryEntry {
896    pub txid: TransactionHash,
897    pub height: Option<u64>,
898    pub block_hash: Option<[u8; 32]>,
899    pub transaction_position: Option<u32>,
900    pub spent: bool,
901    /// Exact block time or mempool admission time. Confirmed header time may
902    /// be unavailable and must remain `None`.
903    pub first_seen_unix: Option<u64>,
904    pub script_index: u32,
905}
906
907/// One backend UTXO tied to the index of the requested script. Returning the
908/// index instead of wallet derivation data keeps the node boundary watch-only.
909#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
910pub struct IndexedWalletCoin {
911    pub coin: WalletCoin,
912    pub script_index: u32,
913    /// Canonical output address observed by the node. It must equal the exact
914    /// requested version/hash pair, not merely its hash bytes.
915    pub output_address: WalletAddressKey,
916}
917
918/// Exact canonical Handshake address input for the node's ScriptId conversion.
919/// Restoration derives version-0 20-byte coin/name programs and separated
920/// 32-byte Shakedex lock-script programs.
921#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
922pub struct WalletAddressKey {
923    pub version: u8,
924    pub hash: Vec<u8>,
925}
926
927#[derive(Clone, Debug, Eq, PartialEq)]
928pub struct ConfirmedWalletPageRequest<'a> {
929    pub scripts: &'a [WalletAddressKey],
930    pub expected_tip: ChainTip,
931    pub expected_epoch: Option<u64>,
932    pub cursor: Option<&'a [u8]>,
933    pub limit: u32,
934}
935
936#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
937pub struct ConfirmedWalletPage {
938    pub binding: SnapshotBinding,
939    pub next_cursor: Option<Vec<u8>>,
940    pub history: Vec<HistoryEntry>,
941    pub utxos: Vec<IndexedWalletCoin>,
942}
943
944#[derive(Clone, Debug, Eq, PartialEq)]
945pub struct IncomingTransfersPageRequest<'a> {
946    pub scripts: &'a [WalletAddressKey],
947    pub binding: SnapshotBinding,
948    pub cursor: Option<&'a [u8]>,
949    pub limit: u32,
950}
951
952#[derive(Clone, Copy, Debug, Eq, PartialEq)]
953pub enum IncomingTransferSourceBinding {
954    RetainedBodyVerified,
955    PrunedTrustedNodeProjection,
956}
957
958/// One active TRANSFER addressed by covenant to a requested derivation. The
959/// embedded Coin remains the old owner's active TRANSFER output and must never
960/// be reconciled into the recipient wallet's UTXO set or balance.
961#[derive(Clone, Debug, Eq, PartialEq)]
962pub struct IncomingTransferCandidate {
963    pub script_index: u32,
964    pub recipient: WalletAddressKey,
965    pub name_hash: [u8; 32],
966    pub start_height: u32,
967    pub transfer_coin: Coin,
968    pub inclusion: TransactionInclusion,
969    pub source_output_count: u32,
970    pub source_binding: IncomingTransferSourceBinding,
971}
972
973#[derive(Clone, Debug, Eq, PartialEq)]
974pub struct IncomingTransfersPage {
975    pub projection_version: u8,
976    pub binding: SnapshotBinding,
977    pub entries: Vec<IncomingTransferCandidate>,
978    pub script_examinations: usize,
979    pub next_cursor: Option<Vec<u8>>,
980}
981
982#[derive(Clone, Debug, Eq, PartialEq)]
983pub struct MempoolWalletPageRequest<'a> {
984    pub scripts: &'a [WalletAddressKey],
985    pub binding: SnapshotBinding,
986    /// The adapter must bind this instance/generation pair, the exact sorted
987    /// script set, and the cursor into one page query.
988    pub expected_mempool: Option<MempoolSnapshotBinding>,
989    pub cursor: Option<&'a [u8]>,
990    pub limit: u32,
991}
992
993#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
994pub struct MempoolSnapshotBinding {
995    /// Nonpersistent node-process identity. It prevents a generation counter
996    /// reset after restart from being mistaken for the prior mempool view.
997    pub instance_nonce: [u8; 32],
998    pub generation: u64,
999}
1000
1001#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
1002#[serde(rename_all = "snake_case")]
1003pub enum HnsFeeRateSource {
1004    MinimumRelay,
1005    /// Canonical HSD normal wallet fee floor for the selected network.
1006    NetworkDefault,
1007    Mempool,
1008    /// Legacy serialized source retained for compatibility. Untrusted peer
1009    /// relay filters are no longer used as wallet fee estimates.
1010    PeerRelay,
1011}
1012
1013/// Exact node-resolved HSD policy evidence for one serialized transaction.
1014/// The transaction bytes remain the durable source artifact.
1015#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
1016pub struct HnsTransactionFeeQuote {
1017    pub txid: TransactionHash,
1018    pub binding: SnapshotBinding,
1019    pub mempool: MempoolSnapshotBinding,
1020    pub target_blocks: u16,
1021    pub rate_atomic_units_per_1000_policy_vbytes: u64,
1022    pub rate_sample_count: usize,
1023    pub rate_source: HnsFeeRateSource,
1024    pub transaction_weight: usize,
1025    pub transaction_sigops: u32,
1026    pub sigop_adjusted_policy_vbytes: usize,
1027    pub minimum_policy_fee: BaseUnits,
1028    pub actual_fee: BaseUnits,
1029    pub meets_minimum_policy_fee: bool,
1030    pub minimum_policy_fee_shortfall: BaseUnits,
1031}
1032
1033#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
1034pub struct MempoolWalletPage {
1035    pub binding: SnapshotBinding,
1036    pub mempool: MempoolSnapshotBinding,
1037    pub next_cursor: Option<Vec<u8>>,
1038    pub history: Vec<HistoryEntry>,
1039}
1040
1041#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
1042pub struct TransactionEvidence {
1043    pub binding: SnapshotBinding,
1044    pub mempool: MempoolSnapshotBinding,
1045    pub raw: Option<Vec<u8>>,
1046    pub status: TransactionStatus,
1047    pub inclusion: Option<TransactionInclusion>,
1048}
1049
1050#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
1051pub struct OutpointSpendEvidence {
1052    pub binding: SnapshotBinding,
1053    /// Exactly one echoed entry per requested outpoint, in request order.
1054    pub entries: Vec<OutpointSpendEntry>,
1055}
1056
1057#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
1058pub struct OutpointSpendEntry {
1059    pub outpoint: HnsOutpoint,
1060    pub spending: Option<SpendingTransactionEvidence>,
1061}
1062
1063#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
1064pub struct SpendingTransactionEvidence {
1065    pub transaction: TransactionHash,
1066    pub input_position: u32,
1067    pub block_hash: [u8; 32],
1068    pub height: u64,
1069}
1070
1071#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
1072pub struct NameProofResponse {
1073    pub name_hash: [u8; 32],
1074    pub tree_root: [u8; 32],
1075    pub proof: Vec<u8>,
1076    pub proof_height: u64,
1077}
1078
1079#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
1080pub struct NameEvidence {
1081    pub binding: SnapshotBinding,
1082    pub proof: NameProofResponse,
1083    /// The interval-committed state bytes. These must exactly equal the bytes
1084    /// recovered by strict Urkel proof verification.
1085    pub proof_state: Option<Vec<u8>>,
1086    /// Node projection that the wallet independently binds to `proof_state`.
1087    pub proof_owner_outpoint: Option<HnsOutpoint>,
1088    pub proof_owner_transaction: Option<Vec<u8>>,
1089    #[serde(default)]
1090    pub proof_owner_inclusion: Option<TransactionInclusion>,
1091    /// The node's current canonical view at `binding`. It may differ from the
1092    /// most recently committed name-tree proof view.
1093    pub current_state: Option<Vec<u8>>,
1094    /// Node projection that the wallet independently binds to `current_state`.
1095    pub current_owner_outpoint: Option<HnsOutpoint>,
1096    pub current_owner_transaction: Option<Vec<u8>>,
1097    #[serde(default)]
1098    pub current_owner_inclusion: Option<TransactionInclusion>,
1099    /// Legacy field name retained at the RPC/storage boundary. The wallet
1100    /// accepts these bytes only when they exactly equal canonical
1101    /// `NameState::resource_data` for `current_state`.
1102    pub untrusted_current_raw_resource: Option<Vec<u8>>,
1103}
1104
1105#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
1106#[serde(rename_all = "snake_case")]
1107pub enum ActiveNameOwnerCoinSourceBinding {
1108    TrustedNodeActiveUtxoProjection,
1109    /// Coin reconstructed from a transaction proven in a locally validated
1110    /// filtered block under the wallet's own header authority.
1111    LocallyVerifiedFilteredBlock,
1112}
1113
1114/// Pruning-safe current NameState/owner-Coin projection. The source label
1115/// distinguishes a trusted node UTXO projection from a Coin reconstructed by
1116/// the wallet from a Merkle-verified transaction.
1117#[derive(Clone, Debug, Eq, PartialEq)]
1118pub struct ActiveNameOwnerCoinEvidence {
1119    pub projection_version: u8,
1120    pub binding: SnapshotBinding,
1121    pub current_state: Vec<u8>,
1122    pub owner_coin: Coin,
1123    pub inclusion: TransactionInclusion,
1124    pub source_binding: ActiveNameOwnerCoinSourceBinding,
1125}
1126
1127#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
1128#[serde(rename_all = "snake_case")]
1129pub enum NameResourceStatus {
1130    /// Legacy persisted records remain non-authoritative until reconciliation.
1131    UnavailableCanonicalBinding,
1132    NoCurrentState,
1133    Empty,
1134    CanonicalDecoded,
1135    /// Consensus-authenticated bytes that are not a typed DNS Resource.
1136    CanonicalOpaque,
1137}
1138
1139#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
1140#[serde(rename_all = "snake_case")]
1141pub enum NameOwnershipStatus {
1142    /// Legacy persisted records remain watch-only until fresh reconciliation.
1143    WatchOnlyCanonicalStateDecoderUnavailable,
1144    /// The canonical state and owner outpoint are authenticated, but the
1145    /// filtered wallet index does not contain the owner's historical
1146    /// transaction. The name remains safely trackable while value actions stay
1147    /// disabled until wallet ownership can be proven.
1148    WatchOnlyOwnerTransactionUnavailable,
1149    /// Canonical name state was authenticated without an account address set,
1150    /// so wallet ownership was deliberately not classified.
1151    WalletContextUnavailable,
1152    NoCurrentOwner,
1153    NotWalletOwned,
1154    WalletOwned {
1155        derivation: DerivationReference,
1156    },
1157    IncomingTransfer {
1158        recipient_derivation: DerivationReference,
1159        current_owner: WalletAddressKey,
1160    },
1161    OutgoingTransfer {
1162        owner_derivation: DerivationReference,
1163        recipient: WalletAddressKey,
1164    },
1165}
1166
1167#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
1168pub struct CanonicalNameStateSummary {
1169    pub owner_outpoint: Option<HnsOutpoint>,
1170    pub value: u64,
1171    pub highest: u64,
1172    pub start_height: u32,
1173    pub renewal_height: u32,
1174    pub transfer_height: u32,
1175    pub revoked_height: u32,
1176    pub claimed_height: u32,
1177    pub renewals: u32,
1178    pub registered: bool,
1179    pub expired: bool,
1180    pub weak: bool,
1181}
1182
1183#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
1184pub struct KnownName {
1185    pub name: Vec<u8>,
1186    pub name_hash: [u8; 32],
1187    pub proof_height: u64,
1188    pub unbound_proof_owner_outpoint: Option<HnsOutpoint>,
1189    pub unbound_current_owner_outpoint: Option<HnsOutpoint>,
1190    pub proof_state: Option<Vec<u8>>,
1191    pub current_state: Option<Vec<u8>>,
1192    #[serde(default)]
1193    pub canonical_proof_state: Option<CanonicalNameStateSummary>,
1194    #[serde(default)]
1195    pub canonical_current_state: Option<CanonicalNameStateSummary>,
1196    #[serde(default)]
1197    pub current_raw_resource: Option<Vec<u8>>,
1198    pub resource_status: NameResourceStatus,
1199    pub ownership_status: NameOwnershipStatus,
1200}
1201
1202/// Ephemeral proof that the current runtime snapshot binds a canonical name
1203/// owner output to one persisted account-zero receive derivation. It is deliberately not
1204/// serializable or cloneable; every value workflow must reacquire it and check
1205/// that its exact snapshot is still current before preparing an action.
1206pub struct VerifiedNameOwnership {
1207    binding: SnapshotBinding,
1208    mempool: MempoolSnapshotBinding,
1209    name: Vec<u8>,
1210    name_hash: [u8; 32],
1211    current_state: Vec<u8>,
1212    owner_outpoint: HnsOutpoint,
1213    owner_transaction: Vec<u8>,
1214    owner_output: Output,
1215    owner_inclusion: TransactionInclusion,
1216    derivation: DerivationReference,
1217}
1218
1219impl fmt::Debug for VerifiedNameOwnership {
1220    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1221        formatter
1222            .debug_struct("VerifiedNameOwnership")
1223            .field("binding", &self.binding)
1224            .field("mempool", &self.mempool)
1225            .field("name", &String::from_utf8_lossy(&self.name))
1226            .field("name_hash", &hex::encode(self.name_hash))
1227            .field("owner_outpoint", &self.owner_outpoint)
1228            .field("derivation", &self.derivation)
1229            .finish_non_exhaustive()
1230    }
1231}
1232
1233impl VerifiedNameOwnership {
1234    pub const fn binding(&self) -> SnapshotBinding {
1235        self.binding
1236    }
1237
1238    pub const fn mempool(&self) -> MempoolSnapshotBinding {
1239        self.mempool
1240    }
1241
1242    pub fn name(&self) -> &[u8] {
1243        &self.name
1244    }
1245
1246    pub const fn name_hash(&self) -> [u8; 32] {
1247        self.name_hash
1248    }
1249
1250    pub fn current_state(&self) -> &[u8] {
1251        &self.current_state
1252    }
1253
1254    pub const fn owner_outpoint(&self) -> HnsOutpoint {
1255        self.owner_outpoint
1256    }
1257
1258    pub fn owner_transaction(&self) -> &[u8] {
1259        &self.owner_transaction
1260    }
1261
1262    pub fn owner_output(&self) -> &Output {
1263        &self.owner_output
1264    }
1265
1266    pub const fn owner_inclusion(&self) -> TransactionInclusion {
1267        self.owner_inclusion
1268    }
1269
1270    pub const fn derivation(&self) -> DerivationReference {
1271        self.derivation
1272    }
1273}
1274
1275struct ValidatedNameEvidence {
1276    known_name: KnownName,
1277    current: Option<ValidatedCanonicalNameState>,
1278}
1279
1280struct ValidatedCanonicalNameState {
1281    state: NameState,
1282    summary: CanonicalNameStateSummary,
1283    owner: Option<ValidatedNameOwner>,
1284}
1285
1286struct ValidatedNameOwner {
1287    outpoint: HnsOutpoint,
1288    raw_transaction: Vec<u8>,
1289    output: Output,
1290    inclusion: TransactionInclusion,
1291}
1292
1293pub fn import_known_name<B: HnsBackend>(
1294    backend: &B,
1295    name: &[u8],
1296    binding: SnapshotBinding,
1297) -> Result<KnownName, HnsWalletError> {
1298    Ok(validated_name_evidence(backend, name, binding, None)?.known_name)
1299}
1300
1301fn validated_name_evidence<B: HnsBackend>(
1302    backend: &B,
1303    name: &[u8],
1304    binding: SnapshotBinding,
1305    wallet_name_addresses: Option<&[DerivedHnsAddress]>,
1306) -> Result<ValidatedNameEvidence, HnsWalletError> {
1307    if !validate_name(name) {
1308        return Err(HnsWalletError::InvalidName);
1309    }
1310    let name_hash = hash_name(name)
1311        .map_err(|_| HnsWalletError::InvalidName)?
1312        .into_bytes();
1313    let evidence = backend.get_name_evidence(name_hash, binding)?;
1314    if evidence.binding != binding {
1315        return Err(HnsWalletError::StaleNodeSnapshot);
1316    }
1317    let response = &evidence.proof;
1318    if response.name_hash != name_hash
1319        || response.tree_root != binding.tip.tree_root
1320        || response.proof_height != binding.tip.height
1321    {
1322        return Err(HnsWalletError::InvalidEvidence);
1323    }
1324    let proof = UrkelProof {
1325        name_hash: NameHash::new(name_hash),
1326        kind: if evidence.proof_state.is_some() {
1327            ProofKind::Inclusion
1328        } else {
1329            ProofKind::NonInclusion
1330        },
1331        raw: response.proof.clone(),
1332    };
1333    let proof_state = proof
1334        .verify_strict(TreeRoot::new(response.tree_root))
1335        .map_err(|_| HnsWalletError::InvalidEvidence)?;
1336    if proof_state != evidence.proof_state {
1337        return Err(HnsWalletError::InvalidEvidence);
1338    }
1339    if let Some(wallet_name_addresses) = wallet_name_addresses {
1340        validate_wallet_name_addresses(wallet_name_addresses)?;
1341    }
1342    let canonical_proof = validate_canonical_name_state(
1343        name,
1344        name_hash,
1345        evidence.proof_state.as_deref(),
1346        evidence.proof_owner_outpoint,
1347        evidence.proof_owner_transaction.as_deref(),
1348        evidence.proof_owner_inclusion,
1349    )?;
1350    let canonical_current = validate_canonical_name_state(
1351        name,
1352        name_hash,
1353        evidence.current_state.as_deref(),
1354        evidence.current_owner_outpoint,
1355        evidence.current_owner_transaction.as_deref(),
1356        evidence.current_owner_inclusion,
1357    )?;
1358    let (current_raw_resource, resource_status) = bind_current_name_resource(
1359        canonical_current.as_ref(),
1360        evidence.untrusted_current_raw_resource,
1361    )?;
1362    let ownership_status =
1363        classify_name_ownership(canonical_current.as_ref(), wallet_name_addresses)?;
1364    let known_name = KnownName {
1365        name: name.to_vec(),
1366        name_hash,
1367        proof_height: response.proof_height,
1368        unbound_proof_owner_outpoint: evidence.proof_owner_outpoint,
1369        unbound_current_owner_outpoint: evidence.current_owner_outpoint,
1370        proof_state,
1371        current_state: evidence.current_state,
1372        canonical_proof_state: canonical_proof.as_ref().map(|state| state.summary.clone()),
1373        canonical_current_state: canonical_current
1374            .as_ref()
1375            .map(|state| state.summary.clone()),
1376        current_raw_resource,
1377        resource_status,
1378        ownership_status,
1379    };
1380    Ok(ValidatedNameEvidence {
1381        known_name,
1382        current: canonical_current,
1383    })
1384}
1385
1386fn bind_current_name_resource(
1387    current: Option<&ValidatedCanonicalNameState>,
1388    projected: Option<Vec<u8>>,
1389) -> Result<(Option<Vec<u8>>, NameResourceStatus), HnsWalletError> {
1390    let canonical = current.map(|current| current.state.resource_data.clone());
1391    if canonical != projected {
1392        return Err(HnsWalletError::InvalidEvidence);
1393    }
1394    let status = match current {
1395        None => NameResourceStatus::NoCurrentState,
1396        Some(current) if current.state.resource_data.is_empty() => NameResourceStatus::Empty,
1397        Some(current) if current.state.resource().is_ok() => NameResourceStatus::CanonicalDecoded,
1398        Some(_) => NameResourceStatus::CanonicalOpaque,
1399    };
1400    Ok((canonical, status))
1401}
1402
1403fn validate_canonical_name_state(
1404    expected_name: &[u8],
1405    expected_name_hash: [u8; 32],
1406    raw_state: Option<&[u8]>,
1407    owner: Option<HnsOutpoint>,
1408    raw: Option<&[u8]>,
1409    inclusion: Option<TransactionInclusion>,
1410) -> Result<Option<ValidatedCanonicalNameState>, HnsWalletError> {
1411    let Some(raw_state) = raw_state else {
1412        if owner.is_some() || raw.is_some() || inclusion.is_some() {
1413            return Err(HnsWalletError::InvalidEvidence);
1414        }
1415        return Ok(None);
1416    };
1417    let state = NameState::decode(NameHash::new(expected_name_hash), raw_state)
1418        .map_err(|_| HnsWalletError::InvalidEvidence)?;
1419    if state.is_null() || state.name != expected_name {
1420        return Err(HnsWalletError::InvalidEvidence);
1421    }
1422    let canonical_owner = state.owner_outpoint().map(|owner| HnsOutpoint {
1423        transaction: TransactionHash::new(owner.transaction_hash.into_bytes()),
1424        output_index: owner.index,
1425    });
1426    if canonical_owner != owner {
1427        return Err(HnsWalletError::InvalidEvidence);
1428    }
1429    let validated_owner = match (canonical_owner, raw, inclusion) {
1430        (None, None, None) => None,
1431        (Some(_), None, None) => None,
1432        (Some(owner), Some(raw), Some(inclusion)) => Some(validate_name_owner_transaction(
1433            &state, owner, raw, inclusion,
1434        )?),
1435        _ => return Err(HnsWalletError::InvalidEvidence),
1436    };
1437    let summary = CanonicalNameStateSummary {
1438        owner_outpoint: canonical_owner,
1439        value: state.value.get(),
1440        highest: state.highest.get(),
1441        start_height: state.height.get(),
1442        renewal_height: state.renewal.get(),
1443        transfer_height: state.transfer.get(),
1444        revoked_height: state.revoked.get(),
1445        claimed_height: state.claimed.get(),
1446        renewals: state.renewals,
1447        registered: state.registered,
1448        expired: state.expired,
1449        weak: state.weak,
1450    };
1451    Ok(Some(ValidatedCanonicalNameState {
1452        state,
1453        summary,
1454        owner: validated_owner,
1455    }))
1456}
1457
1458fn validate_active_name_owner_coin_evidence(
1459    evidence: &ActiveNameOwnerCoinEvidence,
1460    expected_name_hash: [u8; 32],
1461    binding: SnapshotBinding,
1462) -> Result<NameState, HnsWalletError> {
1463    let valid_inclusion_shape = match evidence.source_binding {
1464        ActiveNameOwnerCoinSourceBinding::TrustedNodeActiveUtxoProjection => {
1465            evidence.inclusion.transaction_index.is_none()
1466        }
1467        ActiveNameOwnerCoinSourceBinding::LocallyVerifiedFilteredBlock => {
1468            evidence.inclusion.transaction_index.is_some()
1469        }
1470    };
1471    if evidence.projection_version != 1
1472        || evidence.binding != binding
1473        || !valid_inclusion_shape
1474        || evidence.inclusion.height > binding.tip.height
1475        || evidence.inclusion.block_hash == [0; 32]
1476    {
1477        return Err(HnsWalletError::InvalidEvidence);
1478    }
1479    let state = NameState::decode(NameHash::new(expected_name_hash), &evidence.current_state)
1480        .map_err(|_| HnsWalletError::InvalidEvidence)?;
1481    if state.is_null()
1482        || state.name_hash.into_bytes() != expected_name_hash
1483        || !validate_name(&state.name)
1484        || hash_name(&state.name)
1485            .map_err(|_| HnsWalletError::InvalidEvidence)?
1486            .into_bytes()
1487            != expected_name_hash
1488        || state
1489            .encode()
1490            .map_err(|_| HnsWalletError::InvalidEvidence)?
1491            != evidence.current_state
1492    {
1493        return Err(HnsWalletError::InvalidEvidence);
1494    }
1495
1496    let coin = &evidence.owner_coin;
1497    if coin.outpoint != state.owner
1498        || u64::from(coin.height.get()) != evidence.inclusion.height
1499        || coin.outpoint.is_null()
1500        || (state.registered && coin.value != state.value)
1501        || !matches!(
1502            coin.covenant.kind,
1503            CovenantKind::Claim
1504                | CovenantKind::Reveal
1505                | CovenantKind::Register
1506                | CovenantKind::Update
1507                | CovenantKind::Renew
1508                | CovenantKind::Transfer
1509                | CovenantKind::Finalize
1510        )
1511        || coin.covenant.item_name_hash(0) != Some(state.name_hash)
1512        || covenant_item_u32(&coin.covenant, 1) != Some(state.height.get())
1513    {
1514        return Err(HnsWalletError::InvalidEvidence);
1515    }
1516
1517    let valid = match coin.covenant.kind {
1518        CovenantKind::Claim => {
1519            coin.coinbase
1520                && !state.registered
1521                && coin.covenant.items.len() == 6
1522                && coin.covenant.items.get(2).map(Vec::as_slice) == Some(state.name.as_slice())
1523                && covenant_item_u8(&coin.covenant, 3)
1524                    .is_some_and(|flags| flags & 1 == u8::from(state.weak))
1525                && covenant_item_32(&coin.covenant, 4).is_some()
1526                && covenant_item_u32(&coin.covenant, 5) == Some(state.claimed.get())
1527                && state.renewal == coin.height
1528        }
1529        CovenantKind::Reveal => {
1530            !coin.coinbase
1531                && !state.registered
1532                && coin.covenant.items.len() == 3
1533                && covenant_item_32(&coin.covenant, 2).is_some()
1534                && coin.value == state.highest
1535        }
1536        CovenantKind::Register => {
1537            !coin.coinbase
1538                && coin.covenant.items.len() == 4
1539                && coin.covenant.items.get(2).is_some_and(|data| {
1540                    data.len() <= MAX_RESOURCE_SIZE
1541                        && (data.is_empty() || data == &state.resource_data)
1542                })
1543                && covenant_item_32(&coin.covenant, 3).is_some()
1544                && state.registered
1545                && state.transfer.get() == 0
1546                && state.renewal == coin.height
1547        }
1548        CovenantKind::Update => {
1549            !coin.coinbase
1550                && coin.covenant.items.len() == 3
1551                && coin.covenant.items.get(2).is_some_and(|data| {
1552                    data.len() <= MAX_RESOURCE_SIZE
1553                        && (data.is_empty() || data == &state.resource_data)
1554                })
1555                && state.registered
1556                && state.transfer.get() == 0
1557        }
1558        CovenantKind::Renew => {
1559            !coin.coinbase
1560                && coin.covenant.items.len() == 3
1561                && covenant_item_32(&coin.covenant, 2).is_some()
1562                && state.registered
1563                && state.transfer.get() == 0
1564                && state.renewal == coin.height
1565        }
1566        CovenantKind::Transfer => {
1567            TransferCovenant::try_from(&coin.covenant).is_ok_and(|transfer| {
1568                !coin.coinbase
1569                    && state.registered
1570                    && transfer.name_hash == state.name_hash
1571                    && transfer.start_height == state.height
1572                    && state.transfer.get() != 0
1573                    && state.transfer == coin.height
1574            })
1575        }
1576        CovenantKind::Finalize => {
1577            FinalizeCovenant::try_from(&coin.covenant).is_ok_and(|finalize| {
1578                !coin.coinbase
1579                    && state.registered
1580                    && finalize.name_hash == state.name_hash
1581                    && finalize.start_height == state.height
1582                    && finalize.name == state.name
1583                    && finalize.weak() == state.weak
1584                    && finalize.claimed == state.claimed
1585                    && finalize
1586                        .renewals
1587                        .checked_add(1)
1588                        .is_some_and(|renewals| renewals == state.renewals)
1589                    && state.transfer.get() == 0
1590                    && state.renewal == coin.height
1591            })
1592        }
1593        _ => false,
1594    };
1595    if !valid {
1596        return Err(HnsWalletError::InvalidEvidence);
1597    }
1598    Ok(state)
1599}
1600
1601fn covenant_item_u8(covenant: &Covenant, index: usize) -> Option<u8> {
1602    let item = covenant.items.get(index)?;
1603    (item.len() == 1).then_some(item[0])
1604}
1605
1606fn covenant_item_u32(covenant: &Covenant, index: usize) -> Option<u32> {
1607    covenant
1608        .items
1609        .get(index)?
1610        .as_slice()
1611        .try_into()
1612        .ok()
1613        .map(u32::from_le_bytes)
1614}
1615
1616fn covenant_item_32(covenant: &Covenant, index: usize) -> Option<[u8; 32]> {
1617    covenant.items.get(index)?.as_slice().try_into().ok()
1618}
1619
1620fn validate_name_owner_transaction(
1621    state: &NameState,
1622    owner: HnsOutpoint,
1623    raw: &[u8],
1624    inclusion: TransactionInclusion,
1625) -> Result<ValidatedNameOwner, HnsWalletError> {
1626    let transaction = decode_transaction_for_id(raw, owner.transaction)?;
1627    let output = transaction
1628        .outputs
1629        .get(owner.output_index as usize)
1630        .cloned()
1631        .ok_or(HnsWalletError::InvalidEvidence)?;
1632    if output.value != state.value
1633        || output.covenant.item_name_hash(0) != Some(state.name_hash)
1634        || !output.covenant.kind.is_name()
1635    {
1636        return Err(HnsWalletError::InvalidEvidence);
1637    }
1638    match output.covenant.kind {
1639        CovenantKind::Transfer => {
1640            let transfer = TransferCovenant::try_from(&output.covenant)
1641                .map_err(|_| HnsWalletError::InvalidEvidence)?;
1642            if state.transfer.get() == 0
1643                || u64::from(state.transfer.get()) != inclusion.height
1644                || transfer.start_height != state.height
1645            {
1646                return Err(HnsWalletError::InvalidEvidence);
1647            }
1648        }
1649        CovenantKind::Finalize => {
1650            let finalize = FinalizeCovenant::try_from(&output.covenant)
1651                .map_err(|_| HnsWalletError::InvalidEvidence)?;
1652            if state.transfer.get() != 0
1653                || finalize.start_height != state.height
1654                || finalize.name != state.name
1655                || finalize.claimed != state.claimed
1656                || finalize
1657                    .renewals
1658                    .checked_add(1)
1659                    .is_none_or(|renewals| renewals != state.renewals)
1660                || finalize.weak() != state.weak
1661            {
1662                return Err(HnsWalletError::InvalidEvidence);
1663            }
1664        }
1665        _ if state.transfer.get() != 0 => return Err(HnsWalletError::InvalidEvidence),
1666        _ => {}
1667    }
1668    Ok(ValidatedNameOwner {
1669        outpoint: owner,
1670        raw_transaction: raw.to_vec(),
1671        output,
1672        inclusion,
1673    })
1674}
1675
1676fn validate_wallet_name_addresses(
1677    wallet_name_addresses: &[DerivedHnsAddress],
1678) -> Result<(), HnsWalletError> {
1679    if wallet_name_addresses.len() > MAX_RESTORE_SCRIPTS_PER_QUERY {
1680        return Err(HnsWalletError::InvalidEvidence);
1681    }
1682    let mut programs = BTreeSet::new();
1683    let mut identity = None;
1684    for address in wallet_name_addresses {
1685        let current_identity = (address.account_id, address.derivation.account);
1686        if !is_wallet_name_control_derivation(address.derivation)
1687            || address.program.len() != 20
1688            || !programs.insert(address.program.clone())
1689            || identity.is_some_and(|expected| expected != current_identity)
1690        {
1691            return Err(HnsWalletError::InvalidEvidence);
1692        }
1693        identity = Some(current_identity);
1694    }
1695    Ok(())
1696}
1697
1698/// A Handshake TRANSFER recipient is just a version/hash address. External
1699/// wallets send names to ordinary public receive addresses, so the canonical
1700/// account-zero external branch is also the name-control authority.
1701const fn is_wallet_name_control_derivation(derivation: DerivationReference) -> bool {
1702    matches!(derivation.role, KeyRole::HnsCoin) && derivation.change == 0
1703}
1704
1705/// Returns whether a derived script may legitimately contain a tracked active
1706/// name UTXO. The ShakeDex branch is deliberately absent from
1707/// `is_wallet_name_control_derivation`: its P2WSH program does not give the
1708/// wallet ordinary single-key name authority. During an atomic name offer,
1709/// however, that program is the consensus owner between FINALIZE and the
1710/// contract spend and therefore must remain admissible wallet evidence.
1711const fn is_wallet_tracked_name_utxo_derivation(derivation: DerivationReference) -> bool {
1712    matches!(derivation.role, KeyRole::HnsCoin | KeyRole::HnsShakedex) && derivation.change == 0
1713}
1714
1715fn wallet_name_derivation(
1716    address: &Address,
1717    wallet_name_addresses: &[DerivedHnsAddress],
1718) -> Option<DerivationReference> {
1719    (address.version == 0).then_some(())?;
1720    wallet_name_addresses
1721        .iter()
1722        .find(|candidate| candidate.program == address.hash)
1723        .map(|candidate| candidate.derivation)
1724}
1725
1726fn classify_name_ownership(
1727    current: Option<&ValidatedCanonicalNameState>,
1728    wallet_name_addresses: Option<&[DerivedHnsAddress]>,
1729) -> Result<NameOwnershipStatus, HnsWalletError> {
1730    let Some(wallet_name_addresses) = wallet_name_addresses else {
1731        return Ok(NameOwnershipStatus::WalletContextUnavailable);
1732    };
1733    let Some(current) = current else {
1734        return Ok(NameOwnershipStatus::NoCurrentOwner);
1735    };
1736    let Some(owner) = current.owner.as_ref() else {
1737        return Ok(if current.summary.owner_outpoint.is_some() {
1738            NameOwnershipStatus::WatchOnlyOwnerTransactionUnavailable
1739        } else {
1740            NameOwnershipStatus::NoCurrentOwner
1741        });
1742    };
1743    let owner_derivation = wallet_name_derivation(&owner.output.address, wallet_name_addresses);
1744    if current.state.transfer.get() == 0 {
1745        return Ok(
1746            owner_derivation.map_or(NameOwnershipStatus::NotWalletOwned, |derivation| {
1747                NameOwnershipStatus::WalletOwned { derivation }
1748            }),
1749        );
1750    }
1751    let transfer = TransferCovenant::try_from(&owner.output.covenant)
1752        .map_err(|_| HnsWalletError::InvalidEvidence)?;
1753    let recipient = WalletAddressKey {
1754        version: transfer.recipient_version,
1755        hash: transfer.recipient_hash,
1756    };
1757    let recipient_derivation = wallet_name_addresses
1758        .iter()
1759        .find(|candidate| recipient.version == 0 && candidate.program == recipient.hash)
1760        .map(|candidate| candidate.derivation);
1761    match (owner_derivation, recipient_derivation) {
1762        (Some(owner_derivation), _) => Ok(NameOwnershipStatus::OutgoingTransfer {
1763            owner_derivation,
1764            recipient,
1765        }),
1766        (None, Some(recipient_derivation)) => Ok(NameOwnershipStatus::IncomingTransfer {
1767            recipient_derivation,
1768            current_owner: WalletAddressKey {
1769                version: owner.output.address.version,
1770                hash: owner.output.address.hash.clone(),
1771            },
1772        }),
1773        (None, None) => Ok(NameOwnershipStatus::NotWalletOwned),
1774    }
1775}
1776
1777#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
1778pub struct HnsRuntimeConfig {
1779    pub wallet_id: WalletId,
1780    pub account_id: AccountId,
1781    /// Stable HD account component. It is deliberately independent of the
1782    /// random wallet-local `AccountId` and must be backed up with the profile.
1783    pub account_derivation_index: u32,
1784    pub network: HnsNetwork,
1785    pub birthday_height: u64,
1786    pub restore_lookahead: u32,
1787    pub minimum_confirmations: u32,
1788    pub dust_threshold: BaseUnits,
1789    /// This is an application release-policy switch, not a test-network check.
1790    pub value_operations_enabled: bool,
1791    pub settlement_enabled: bool,
1792}
1793
1794impl HnsRuntimeConfig {
1795    /// Builds the fixed, non-value account configuration used by native
1796    /// create/restore bootstrap. Network and restore birthday are explicit;
1797    /// all other policy remains at conservative wallet defaults.
1798    pub fn default_non_value(
1799        wallet_id: WalletId,
1800        account_id: AccountId,
1801        policy: HnsBootstrapPolicy,
1802    ) -> Result<Self, HnsWalletError> {
1803        let config = Self {
1804            wallet_id,
1805            account_id,
1806            account_derivation_index: 0,
1807            network: policy.network,
1808            birthday_height: policy.birthday_height,
1809            restore_lookahead: DEFAULT_RESTORE_LOOKAHEAD,
1810            minimum_confirmations: 2,
1811            dust_threshold: BaseUnits::new(DEFAULT_DUST_THRESHOLD),
1812            value_operations_enabled: false,
1813            settlement_enabled: false,
1814        };
1815        config.validate()?;
1816        Ok(config)
1817    }
1818
1819    /// Validate inert account identity and bounded scan policy only.
1820    ///
1821    /// This deliberately does not validate value-release authority. It exists
1822    /// so an explicitly recovery-only reader can preserve and authenticate
1823    /// historical persisted flags without interpreting them as capability.
1824    /// Calling it does not authorize opening the full runtime, signing,
1825    /// broadcasting, settlement, provider use, or any value mutation.
1826    pub fn validate_structure(&self) -> Result<(), HnsWalletError> {
1827        if self.account_id.as_bytes().iter().all(|byte| *byte == 0) {
1828            return Err(HnsWalletError::InvalidRuntimeConfiguration);
1829        }
1830        if self.restore_lookahead == 0
1831            || self.restore_lookahead > MAX_RESTORE_LOOKAHEAD
1832            || self.restore_lookahead as usize * 2 > MAX_RESTORE_SCRIPTS_PER_QUERY
1833        {
1834            return Err(HnsWalletError::InvalidLookahead);
1835        }
1836        if self.minimum_confirmations == 0 || self.dust_threshold.is_zero() {
1837            return Err(HnsWalletError::InvalidRuntimeConfiguration);
1838        }
1839        Ok(())
1840    }
1841
1842    /// Validate both inert configuration and currently available runtime
1843    /// authority. Every ordinary and full runtime constructor uses this path.
1844    pub fn validate(&self) -> Result<(), HnsWalletError> {
1845        self.validate_structure()?;
1846        if (self.value_operations_enabled || self.settlement_enabled)
1847            && (!HNS_VALUE_RUNTIME_RELEASE_QUALIFIED || !HNS_FEE_QUOTE_ALGEBRA_RELEASE_QUALIFIED)
1848        {
1849            return Err(if self.network == HnsNetwork::Mainnet {
1850                HnsWalletError::MainnetDisabled
1851            } else {
1852                HnsWalletError::RuntimeIntegrationUnavailable
1853            });
1854        }
1855        Ok(())
1856    }
1857}
1858
1859#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
1860pub struct HnsAccountRecord {
1861    pub config: HnsRuntimeConfig,
1862    pub next_receive_index: u32,
1863    pub next_change_index: u32,
1864    /// Next separated Shakedex seller-key derivation. The protected allocation
1865    /// high-water remains authoritative and reconciliation may only advance
1866    /// this restoration projection.
1867    #[serde(default)]
1868    pub next_shakedex_index: u32,
1869    pub external_scan_end: u32,
1870    pub internal_scan_end: u32,
1871    /// Inclusive end of the independent `HnsShakedex`, change-zero scan branch.
1872    #[serde(default)]
1873    pub shakedex_scan_end: u32,
1874    /// True only after a complete bounded Shakedex branch scan has committed.
1875    /// Missing legacy state fails closed until the first successful scan.
1876    #[serde(default)]
1877    pub shakedex_scan_complete: bool,
1878    /// Durable cross-runtime fence set before Shakedex address discovery and
1879    /// cleared only by the same revision line after a complete scan commits.
1880    #[serde(default)]
1881    pub shakedex_scan_in_progress: bool,
1882    pub last_used_external: Option<u32>,
1883    pub last_used_internal: Option<u32>,
1884    #[serde(default)]
1885    pub last_used_shakedex: Option<u32>,
1886}
1887
1888impl HnsAccountRecord {
1889    /// Constructs an empty account projection for a configuration whose value
1890    /// and settlement paths are both disabled. No backend or node is touched.
1891    pub fn initial_non_value(config: HnsRuntimeConfig) -> Result<Self, HnsWalletError> {
1892        config.validate()?;
1893        if config.value_operations_enabled || config.settlement_enabled {
1894            return Err(HnsWalletError::RuntimeIntegrationUnavailable);
1895        }
1896        let scan_end = config
1897            .restore_lookahead
1898            .checked_sub(1)
1899            .ok_or(HnsWalletError::InvalidLookahead)?;
1900        Ok(Self {
1901            config,
1902            next_receive_index: 0,
1903            next_change_index: 0,
1904            next_shakedex_index: 0,
1905            external_scan_end: scan_end,
1906            internal_scan_end: scan_end,
1907            shakedex_scan_end: scan_end,
1908            shakedex_scan_complete: false,
1909            shakedex_scan_in_progress: false,
1910            last_used_external: None,
1911            last_used_internal: None,
1912            last_used_shakedex: None,
1913        })
1914    }
1915}
1916
1917/// Prepared seed plus one exact HNS account for native create or restore.
1918///
1919/// The mnemonic remains in a zeroizing BIP-39 value and is omitted from
1920/// `Debug`. Persistence encrypts the 64-byte recovery seed and the initial
1921/// account record in one store transaction. This type performs no node I/O and
1922/// cannot enable value or settlement operations.
1923pub struct HnsWalletBootstrap {
1924    mnemonic: Mnemonic,
1925    wallet_id: WalletId,
1926    account: HnsAccountRecord,
1927}
1928
1929impl HnsWalletBootstrap {
1930    /// Generates a new 24-word English mnemonic and a random wallet ID.
1931    pub fn generate(policy: HnsBootstrapPolicy) -> Result<Self, HnsWalletError> {
1932        let mnemonic = generate_24_word_mnemonic()?;
1933        let wallet_id = generate_wallet_id()?;
1934        Self::from_mnemonic(mnemonic, wallet_id, policy)
1935    }
1936
1937    /// Parses exactly 24 normalized English BIP-39 words and derives the
1938    /// recovery wallet ID using the existing `hns-wallet-id/v1` rule.
1939    pub fn restore(phrase: &str, policy: HnsBootstrapPolicy) -> Result<Self, HnsWalletError> {
1940        let mnemonic = Mnemonic::parse_in_normalized(Language::English, phrase)
1941            .map_err(|_| HnsWalletError::InvalidRecoveryPhrase)?;
1942        if mnemonic.word_count() != 24 {
1943            return Err(HnsWalletError::InvalidRecoveryPhrase);
1944        }
1945        let wallet_id = wallet_id_from_mnemonic(&mnemonic);
1946        Self::from_mnemonic(mnemonic, wallet_id, policy)
1947    }
1948
1949    fn from_mnemonic(
1950        mnemonic: Mnemonic,
1951        wallet_id: WalletId,
1952        policy: HnsBootstrapPolicy,
1953    ) -> Result<Self, HnsWalletError> {
1954        let account_id = generate_account_id()?;
1955        let config = HnsRuntimeConfig::default_non_value(wallet_id, account_id, policy)?;
1956        let account = HnsAccountRecord::initial_non_value(config)?;
1957        Ok(Self {
1958            mnemonic,
1959            wallet_id,
1960            account,
1961        })
1962    }
1963
1964    pub const fn wallet_id(&self) -> WalletId {
1965        self.wallet_id
1966    }
1967
1968    pub fn account_record(&self) -> &HnsAccountRecord {
1969        &self.account
1970    }
1971
1972    /// Atomically writes the immutable seed and initial account. The store
1973    /// requires both relevant namespaces to be empty, so replaying bootstrap
1974    /// or encountering seed-only/account-only state fails closed.
1975    pub fn persist(&self, store: &mut WalletStore, now_unix: u64) -> Result<u64, StoreError> {
1976        let seed = Zeroizing::new(self.mnemonic.to_seed_normalized(""));
1977        store.initialize_recovery_seed_and_wallet_account(
1978            self.wallet_id.as_bytes(),
1979            seed.as_slice(),
1980            &account_entity_id(&self.account.config),
1981            &self.account,
1982            now_unix,
1983        )
1984    }
1985
1986    /// Converts the mnemonic into the dedicated high-risk display wrapper.
1987    /// Call this only after durable persistence succeeds.
1988    pub fn into_recovery_phrase(self) -> RecoveryPhrase {
1989        RecoveryPhrase(self.mnemonic.to_string())
1990    }
1991}
1992
1993impl fmt::Debug for HnsWalletBootstrap {
1994    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1995        formatter
1996            .debug_struct("HnsWalletBootstrap")
1997            .field("mnemonic", &"[REDACTED]")
1998            .field("wallet_id", &self.wallet_id)
1999            .field("account", &self.account)
2000            .finish()
2001    }
2002}
2003
2004/// Internal validation purpose carried through exact selection and every
2005/// synchronized-read persistence fence.
2006#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2007enum HnsAccountReadMode {
2008    OrdinaryNonValue,
2009    PersistedRecoveryReadOnly,
2010    /// Structure-only selection for a private native lifecycle controller.
2011    /// This mode can authenticate an account whose persisted release flags are
2012    /// enabled, but it is rejected by every synchronized-read constructor and
2013    /// therefore cannot become node, signing, or settlement authority.
2014    LifecycleStructural,
2015}
2016
2017impl HnsAccountReadMode {
2018    fn validate_config(self, config: &HnsRuntimeConfig) -> Result<(), HnsWalletError> {
2019        match self {
2020            Self::OrdinaryNonValue => {
2021                config.validate()?;
2022                if config.value_operations_enabled || config.settlement_enabled {
2023                    return Err(HnsWalletError::RuntimeIntegrationUnavailable);
2024                }
2025            }
2026            Self::PersistedRecoveryReadOnly => {
2027                config.validate_structure()?;
2028                if !config.value_operations_enabled && !config.settlement_enabled {
2029                    return Err(HnsWalletError::InvalidRuntimeConfiguration);
2030                }
2031            }
2032            Self::LifecycleStructural => config.validate_structure()?,
2033        }
2034        Ok(())
2035    }
2036}
2037
2038/// Read-only selector for one exact pre-existing HNS account held by the same
2039/// Arc-backed store/key authority as its caller.
2040///
2041/// Selection reads authenticated account records only. It never creates an
2042/// account, rewrites runtime configuration, contacts a node, restores cached
2043/// chain authority, signs, or enables a value path.
2044#[derive(Clone)]
2045pub struct HnsExistingAccountSelector {
2046    store: SharedWalletStore,
2047    expected: HnsRuntimeConfig,
2048    mode: HnsAccountReadMode,
2049}
2050
2051/// Exact authenticated account row and its monotonic entity revision.
2052///
2053/// The revision is local wallet evidence only: it proves neither chain state
2054/// nor a broker lease. Native compositions can join it to their independently
2055/// held authority and re-read it around dependent use.
2056#[derive(Clone, Debug, Eq, PartialEq)]
2057pub struct SelectedHnsAccountRevision {
2058    pub account: HnsAccountRecord,
2059    pub revision: u64,
2060}
2061
2062impl HnsExistingAccountSelector {
2063    pub fn new(
2064        store: SharedWalletStore,
2065        expected: HnsRuntimeConfig,
2066    ) -> Result<Self, HnsWalletError> {
2067        Self::new_with_mode(store, expected, HnsAccountReadMode::OrdinaryNonValue)
2068    }
2069
2070    /// Select one exact account for private native create/open/lock lifecycle
2071    /// control without interpreting persisted value flags as authority.
2072    ///
2073    /// The resulting selector can be used by the account-only service runtime,
2074    /// but synchronized read and full value constructors independently reject
2075    /// it. This lets an installed wallet remain reopenable while its product-
2076    /// owned node is unavailable or a release gate is temporarily closed.
2077    pub fn new_lifecycle(
2078        store: SharedWalletStore,
2079        expected: HnsRuntimeConfig,
2080    ) -> Result<Self, HnsWalletError> {
2081        Self::new_with_mode(store, expected, HnsAccountReadMode::LifecycleStructural)
2082    }
2083
2084    fn new_with_mode(
2085        store: SharedWalletStore,
2086        expected: HnsRuntimeConfig,
2087        mode: HnsAccountReadMode,
2088    ) -> Result<Self, HnsWalletError> {
2089        mode.validate_config(&expected)?;
2090        Ok(Self {
2091            store,
2092            expected,
2093            mode,
2094        })
2095    }
2096
2097    pub fn expected_record_id(&self) -> [u8; 32] {
2098        account_entity_id(&self.expected)
2099    }
2100
2101    pub fn shares_store_authority(&self, store: &SharedWalletStore) -> bool {
2102        self.store.is_same_authority(store)
2103    }
2104
2105    const fn mode(&self) -> HnsAccountReadMode {
2106        self.mode
2107    }
2108
2109    /// Re-read and authenticate the selected account on every call. This makes
2110    /// a restarted service fail closed if product configuration selects a
2111    /// different account than a persisted provider permission.
2112    pub fn selected_account(&self) -> Result<HnsAccountRecord, HnsWalletError> {
2113        Ok(self.selected_account_with_revision()?.account)
2114    }
2115
2116    /// Re-read the same exact account selection while retaining the
2117    /// authenticated entity revision for a native authority-context join.
2118    pub fn selected_account_with_revision(
2119        &self,
2120    ) -> Result<SelectedHnsAccountRevision, HnsWalletError> {
2121        let expected_id = account_entity_id(&self.expected);
2122        let (accounts, selected) = self
2123            .store
2124            .with_store(|store| {
2125                if store.is_locked() {
2126                    return Err(StoreError::Locked);
2127                }
2128                Ok((
2129                    store.list_entities_by_id_prefix::<HnsAccountRecord>(
2130                        EntityKind::WalletAccount,
2131                        self.expected.wallet_id.as_bytes(),
2132                        MAX_HISTORY_RESULTS,
2133                    )?,
2134                    store.wallet_account::<HnsAccountRecord>(&expected_id)?,
2135                ))
2136            })
2137            .map_err(|error| match error {
2138                StoreError::Locked => HnsWalletError::StoreLocked,
2139                error => HnsWalletError::from(error),
2140            })?;
2141        for stored in accounts {
2142            if stored.id != account_entity_id(&stored.value.config)
2143                || stored.value.config.wallet_id != self.expected.wallet_id
2144            {
2145                return Err(HnsWalletError::InvalidEvidence);
2146            }
2147            if stored.value.config.account_id != self.expected.account_id
2148                && stored.value.config.account_derivation_index
2149                    == self.expected.account_derivation_index
2150            {
2151                return Err(HnsWalletError::DuplicateAccountDerivation);
2152            }
2153        }
2154        let selected = selected.ok_or(HnsWalletError::AccountConfigurationMismatch)?;
2155        if selected.id != expected_id
2156            || selected.value.config != self.expected
2157            || selected.revision == 0
2158        {
2159            return Err(HnsWalletError::AccountConfigurationMismatch);
2160        }
2161        Ok(SelectedHnsAccountRevision {
2162            account: selected.value,
2163            revision: selected.revision,
2164        })
2165    }
2166}
2167
2168/// Exact confirmed-chain and mempool authority for one synchronized account
2169/// read. The trusted service composition retains this binding internally to
2170/// prevent mixed-snapshot projections; website/provider JSON must not receive
2171/// node identity, epoch, tip, or mempool-generation details.
2172#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2173pub struct HnsAccountReadBinding {
2174    pub chain: SnapshotBinding,
2175    pub mempool: MempoolSnapshotBinding,
2176}
2177
2178/// Complete non-value HNS account projection produced by one bounded wallet
2179/// reconciliation. All fields are derived from the same chain/mempool binding.
2180#[derive(Clone, Debug, Eq, PartialEq)]
2181pub struct HnsAccountReadSnapshot {
2182    pub account_id: AccountId,
2183    pub binding: HnsAccountReadBinding,
2184    pub balance: Amount,
2185    pub transactions: Vec<TransactionSummary>,
2186    pub receive_target: ReceiveTarget,
2187    /// Name-transfer presentation of the same canonical account-zero receive
2188    /// target. Handshake distinguishes value and name ownership by covenant,
2189    /// not by assigning a second ordinary address account.
2190    pub name_receive_target: HnsNameReceiveTarget,
2191    pub known_names: Vec<KnownName>,
2192}
2193
2194/// Query-scoped selected-account, network, and trusted-time authority for one
2195/// Shakescape board metadata read or negative cancellation admission.
2196///
2197/// This object is deliberately non-cloneable and non-serializable. It proves
2198/// no current chain state, name ownership, locking coin, publication, signing,
2199/// or value authority. A related read must consume it through
2200/// `revalidate_unchanged_account` inside the same entity snapshot. A related
2201/// write must additionally consume its prefix lease as a guard in the same
2202/// immediate transaction as that write.
2203pub struct VerifiedHnsBoardCancellationContext {
2204    account_id: [u8; 32],
2205    account: HnsAccountRecord,
2206    account_revision: u64,
2207    account_prefix_lease: EntityPrefixSetLease,
2208    network: NetworkBinding,
2209    observed_at_unix: u64,
2210}
2211
2212fn validate_hns_board_account_snapshot(
2213    snapshot: &EntityReadSnapshot<'_>,
2214    account_id: &[u8; 32],
2215    expected_account: &HnsAccountRecord,
2216) -> Result<u64, HnsWalletError> {
2217    let accounts = snapshot.list_entities_by_id_prefix::<HnsAccountRecord>(
2218        EntityKind::WalletAccount,
2219        expected_account.config.wallet_id.as_bytes(),
2220        MAX_HISTORY_RESULTS,
2221    )?;
2222    let mut selected_revision = None;
2223    for stored in accounts {
2224        if stored.id != account_entity_id(&stored.value.config)
2225            || stored.value.config.wallet_id != expected_account.config.wallet_id
2226        {
2227            return Err(HnsWalletError::InvalidEvidence);
2228        }
2229        if stored.value.config.account_id != expected_account.config.account_id
2230            && stored.value.config.account_derivation_index
2231                == expected_account.config.account_derivation_index
2232        {
2233            return Err(HnsWalletError::DuplicateAccountDerivation);
2234        }
2235        if stored.id.as_slice() == account_id.as_slice()
2236            && (stored.value != *expected_account
2237                || selected_revision.replace(stored.revision).is_some())
2238        {
2239            return Err(HnsWalletError::StaleAccountRead);
2240        }
2241    }
2242    selected_revision.ok_or(HnsWalletError::StaleAccountRead)
2243}
2244
2245fn capture_hns_board_account_snapshot(
2246    snapshot: &EntityReadSnapshot<'_>,
2247    account_id: &[u8; 32],
2248    expected_account: &HnsAccountRecord,
2249) -> Result<(u64, EntityPrefixSetLease), HnsWalletError> {
2250    let revision = validate_hns_board_account_snapshot(snapshot, account_id, expected_account)?;
2251    let lease = snapshot.entity_prefix_set_lease(
2252        EntityKind::WalletAccount,
2253        expected_account.config.wallet_id.as_bytes(),
2254        MAX_HISTORY_RESULTS,
2255    )?;
2256    Ok((revision, lease))
2257}
2258
2259impl VerifiedHnsBoardCancellationContext {
2260    pub const fn network(&self) -> NetworkBinding {
2261        self.network
2262    }
2263
2264    pub const fn observed_at_unix(&self) -> u64 {
2265        self.observed_at_unix
2266    }
2267
2268    /// Consume and revalidate the exact encrypted account prefix set inside a
2269    /// caller-owned coherent entity snapshot. The refreshed context remains
2270    /// usable as a read authority or can be consumed as an atomic write guard.
2271    pub fn revalidate_unchanged_account(
2272        mut self,
2273        snapshot: &EntityReadSnapshot<'_>,
2274    ) -> Result<Self, HnsWalletError> {
2275        let revision =
2276            validate_hns_board_account_snapshot(snapshot, &self.account_id, &self.account)?;
2277        if revision != self.account_revision {
2278            return Err(HnsWalletError::StaleAccountRead);
2279        }
2280        self.account_prefix_lease = snapshot
2281            .refresh_entity_prefix_set_lease(self.account_prefix_lease)
2282            .map_err(|error| match error {
2283                StoreError::StaleEntitySet => HnsWalletError::StaleAccountRead,
2284                _ => HnsWalletError::from(error),
2285            })?;
2286        Ok(self)
2287    }
2288
2289    /// Consume this read authority into the ABA-resistant account-set lease
2290    /// used to guard a related entity batch in the same immediate transaction.
2291    pub fn into_account_prefix_lease(self) -> EntityPrefixSetLease {
2292        self.account_prefix_lease
2293    }
2294
2295    /// Perform a coherent read-only recheck of the exact selected account row
2296    /// and revision. This method returns no write guard and is not an atomic
2297    /// precondition for a later mutation on an independent connection. Writes
2298    /// must instead consume `revalidate_unchanged_account` and
2299    /// `into_account_prefix_lease`. The enclosing runtime must separately
2300    /// require the identical `SharedWalletStore` Arc.
2301    pub fn verify_unchanged_account(&self, store: &WalletStore) -> Result<(), HnsWalletError> {
2302        if store.is_locked() {
2303            return Err(HnsWalletError::StoreLocked);
2304        }
2305        store.try_with_entity_read_snapshot(|snapshot| {
2306            let revision =
2307                validate_hns_board_account_snapshot(snapshot, &self.account_id, &self.account)?;
2308            if revision != self.account_revision {
2309                return Err(HnsWalletError::StaleAccountRead);
2310            }
2311            Ok(())
2312        })
2313    }
2314}
2315
2316impl fmt::Debug for VerifiedHnsBoardCancellationContext {
2317    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2318        formatter
2319            .debug_struct("VerifiedHnsBoardCancellationContext")
2320            .field("account", &"[EXACT ACCOUNT FENCE]")
2321            .field("account_revision", &self.account_revision)
2322            .field("network", &self.network)
2323            .field("observed_at_unix", &self.observed_at_unix)
2324            .finish_non_exhaustive()
2325    }
2326}
2327
2328/// Generalized name for the purpose-minimized account/network/time context
2329/// shared by closed Shakescape board metadata reads and cancellation admission.
2330pub type VerifiedHnsBoardContext = VerifiedHnsBoardCancellationContext;
2331
2332/// Synchronized, non-value HNS runtime for product/provider compositions that
2333/// already own an exact account and one process-local store authority.
2334///
2335/// Local encrypted state is staged under short `SharedWalletStore` closures,
2336/// every node call runs after the closure has returned, and the result commits
2337/// only after an exact account/entity revision fence is re-authenticated. This
2338/// type exposes no signing, broadcasting, value, allocation, or settlement
2339/// method and does not alter either HNS value release gate. Its only mutation
2340/// outside synchronization is a trusted-native exact-text name import which
2341/// atomically persists canonical evidence and rotates restoration metadata.
2342/// Before deriving or
2343/// transmitting any wallet script identifiers, synchronization obtains a
2344/// script-free chain binding and binds height-zero evidence to the selected
2345/// account network.
2346pub struct HnsAccountReadRuntime<B, C = SystemClock> {
2347    backend: B,
2348    clock: C,
2349    store: SharedWalletStore,
2350    selector: HnsExistingAccountSelector,
2351    synchronization: Mutex<()>,
2352}
2353
2354impl<B: HnsBackend, C: HnsClock> HnsAccountReadRuntime<B, C> {
2355    pub fn new(
2356        backend: B,
2357        clock: C,
2358        store: SharedWalletStore,
2359        selector: HnsExistingAccountSelector,
2360    ) -> Result<Self, HnsWalletError> {
2361        if selector.mode() != HnsAccountReadMode::OrdinaryNonValue {
2362            return Err(HnsWalletError::RuntimeIntegrationUnavailable);
2363        }
2364        Self::new_with_selector(backend, clock, store, selector)
2365    }
2366
2367    fn new_with_selector(
2368        backend: B,
2369        clock: C,
2370        store: SharedWalletStore,
2371        selector: HnsExistingAccountSelector,
2372    ) -> Result<Self, HnsWalletError> {
2373        if !selector.shares_store_authority(&store) {
2374            return Err(HnsWalletError::StoreAuthorityMismatch);
2375        }
2376        Ok(Self {
2377            backend,
2378            clock,
2379            store,
2380            selector,
2381            synchronization: Mutex::new(()),
2382        })
2383    }
2384
2385    pub fn shares_store_authority(&self, store: &SharedWalletStore) -> bool {
2386        self.store.is_same_authority(store) && self.selector.shares_store_authority(store)
2387    }
2388
2389    pub fn selected_account(&self) -> Result<HnsAccountRecord, HnsWalletError> {
2390        self.selector.selected_account()
2391    }
2392
2393    /// Return the exact authenticated account row and its monotonic entity
2394    /// revision without contacting the node.
2395    pub fn selected_account_with_revision(
2396        &self,
2397    ) -> Result<SelectedHnsAccountRevision, HnsWalletError> {
2398        self.selector.selected_account_with_revision()
2399    }
2400
2401    /// Derive the current ordinary HNS payment receive target using only the
2402    /// authenticated local account and encrypted wallet seed.
2403    ///
2404    /// This deliberately performs no node, peer, mempool, clock, or store
2405    /// mutation operation. It is therefore safe to expose immediately after a
2406    /// successful local unlock, while balance, history, name ownership, and
2407    /// spending remain synchronization-gated.
2408    pub fn local_receive_target(&self) -> Result<ReceiveTarget, HnsWalletError> {
2409        let _synchronization = self
2410            .synchronization
2411            .lock()
2412            .map_err(|_| HnsWalletError::RuntimePoisoned)?;
2413        let selected = self.selector.selected_account_with_revision()?;
2414        let target = local_hns_payment_receive_target(&self.store, &selected.account)?;
2415        if self.selector.selected_account_with_revision()? != selected {
2416            return Err(HnsWalletError::StaleAccountRead);
2417        }
2418        Ok(target)
2419    }
2420
2421    /// Return the configured account network without consulting caller input.
2422    pub const fn configured_network(&self) -> HnsNetwork {
2423        self.selector.expected.network
2424    }
2425
2426    /// Import one canonical Handshake name from exact native text.
2427    ///
2428    /// The input is never trimmed, lowercased, IDNA-converted, normalized, or
2429    /// split on dots. Invalid text is rejected before any backend method is
2430    /// called. Wallet ownership is established only from fresh canonical name
2431    /// evidence and an exact persisted `HnsName` change-zero derivation. The
2432    /// account derivation high-water and name row commit in one store batch.
2433    pub fn import_name_exact_text(&self, name: &str) -> Result<KnownName, HnsWalletError> {
2434        self.import_name_exact_text_bounded(name, MAX_HISTORY_RESULTS)
2435    }
2436
2437    /// Atomically import a bounded set of exact canonical Handshake names.
2438    ///
2439    /// Every name is validated and authenticated against one chain snapshot
2440    /// before the account derivation high-water mark or any known-name row is
2441    /// changed. The final account rotation and all name rows commit in one
2442    /// encrypted store transaction, so a failed item can never leave a prefix
2443    /// of a requested bulk import behind.
2444    pub fn import_names_exact_text_bounded(
2445        &self,
2446        names: &[&str],
2447        maximum_persisted_names: usize,
2448    ) -> Result<Vec<KnownName>, HnsWalletError> {
2449        if names.is_empty()
2450            || names.len() > MAX_HISTORY_RESULTS
2451            || maximum_persisted_names == 0
2452            || maximum_persisted_names > MAX_HISTORY_RESULTS
2453        {
2454            return Err(HnsWalletError::HistoryLimit);
2455        }
2456        let mut requested = Vec::with_capacity(names.len());
2457        let mut requested_hashes = BTreeSet::new();
2458        for name in names {
2459            let name_bytes = name.as_bytes();
2460            if !validate_name(name_bytes) {
2461                return Err(HnsWalletError::InvalidName);
2462            }
2463            let name_hash = hash_name(name_bytes)
2464                .map_err(|_| HnsWalletError::InvalidName)?
2465                .into_bytes();
2466            if !requested_hashes.insert(name_hash) {
2467                return Err(HnsWalletError::InvalidName);
2468            }
2469            requested.push((name_bytes.to_vec(), name_hash));
2470        }
2471
2472        let _synchronization = self
2473            .synchronization
2474            .lock()
2475            .map_err(|_| HnsWalletError::RuntimePoisoned)?;
2476        let selected = self.selector.selected_account()?;
2477        let preparation = self.store.try_with_store(|store| {
2478            prepare_hns_name_bulk_import(store, &selected, &requested, maximum_persisted_names)
2479        })?;
2480        let binding = self.backend.get_chain_snapshot()?;
2481        verify_hns_read_chain_identity(&self.backend, selected.config.network, binding)?;
2482        let name_addresses = self
2483            .store
2484            .try_with_store(|store| derive_hns_name_bulk_import_addresses(store, &preparation))?;
2485        let mut imported = Vec::with_capacity(requested.len());
2486        for (name, _) in &requested {
2487            imported.push(
2488                validated_name_evidence(&self.backend, name, binding, Some(&name_addresses))?
2489                    .known_name,
2490            );
2491        }
2492        let now_unix = self.clock.now_unix()?;
2493        if self.selector.selected_account()? != preparation.account.value {
2494            return Err(HnsWalletError::StaleAccountRead);
2495        }
2496        if self.backend.get_chain_snapshot()? != binding {
2497            return Err(HnsWalletError::StaleNodeSnapshot);
2498        }
2499        self.store.try_with_store_mut(|store| {
2500            commit_hns_name_bulk_import(store, &preparation, &name_addresses, &imported, now_unix)
2501        })?;
2502        Ok(imported)
2503    }
2504
2505    /// Exact-text import with a caller-owned persisted-name result bound.
2506    /// Existing names remain re-importable at the bound; a new row is rejected
2507    /// before node I/O. Native service/mobile projections use this so a
2508    /// successful mutation can never become undisplayable afterward.
2509    pub fn import_name_exact_text_bounded(
2510        &self,
2511        name: &str,
2512        maximum_persisted_names: usize,
2513    ) -> Result<KnownName, HnsWalletError> {
2514        self.import_names_exact_text_bounded(&[name], maximum_persisted_names)?
2515            .pop()
2516            .ok_or(HnsWalletError::InvalidEvidence)
2517    }
2518
2519    /// Observe the exact selected account, its Shakedex network binding, and
2520    /// trusted wall time for one Shakescape board metadata operation.
2521    /// Selected account state is fenced on both sides of the clock call and no
2522    /// backend or node method is invoked.
2523    pub fn observe_board_context(&self) -> Result<VerifiedHnsBoardContext, HnsWalletError> {
2524        let _synchronization = self
2525            .synchronization
2526            .lock()
2527            .map_err(|_| HnsWalletError::RuntimePoisoned)?;
2528        let selected = self.selector.selected_account()?;
2529        let account_id = account_entity_id(&selected.config);
2530        let (account_revision, account_prefix_lease) = self.store.try_with_store(|store| {
2531            if store.is_locked() {
2532                return Err(HnsWalletError::StoreLocked);
2533            }
2534            store.try_with_entity_read_snapshot(|snapshot| {
2535                capture_hns_board_account_snapshot(snapshot, &account_id, &selected)
2536            })
2537        })?;
2538        let observed_at_unix = self.clock.now_unix()?;
2539        let selected_after_clock = self.selector.selected_account()?;
2540        if selected_after_clock != selected {
2541            return Err(HnsWalletError::StaleAccountRead);
2542        }
2543        let context = VerifiedHnsBoardCancellationContext {
2544            account_id,
2545            account: selected,
2546            account_revision,
2547            account_prefix_lease,
2548            network: shakedex_network_binding(selected_after_clock.config.network)?,
2549            observed_at_unix,
2550        };
2551        self.store.try_with_store(|store| {
2552            store.try_with_entity_read_snapshot(|snapshot| {
2553                context.revalidate_unchanged_account(snapshot)
2554            })
2555        })
2556    }
2557
2558    /// Observe the purpose-minimized context used by negative Shakescape board
2559    /// cancellation admission. This preserves the established cancellation
2560    /// API while sharing the exact account/network/time fencing implementation
2561    /// with closed board metadata reads.
2562    pub fn observe_board_cancellation_context(
2563        &self,
2564    ) -> Result<VerifiedHnsBoardCancellationContext, HnsWalletError> {
2565        self.observe_board_context()
2566    }
2567
2568    /// Reconcile every currently supported non-value account projection once.
2569    /// Stale snapshots are surfaced to the caller; this layer never polls.
2570    pub fn synchronize(&self) -> Result<HnsAccountReadSnapshot, HnsWalletError> {
2571        let _synchronization = self
2572            .synchronization
2573            .lock()
2574            .map_err(|_| HnsWalletError::RuntimePoisoned)?;
2575        let now_unix = self.clock.now_unix()?;
2576        let selected = self.selector.selected_account()?;
2577        let preparation = self
2578            .store
2579            .with_store_mut(|store| {
2580                Ok(prepare_hns_account_read(
2581                    store,
2582                    &selected,
2583                    self.selector.mode(),
2584                    now_unix,
2585                ))
2586            })
2587            .map_err(map_shared_store_error)??;
2588        let binding = self.backend.get_chain_snapshot()?;
2589        verify_hns_read_chain_identity(
2590            &self.backend,
2591            preparation.fenced_account.config.network,
2592            binding,
2593        )?;
2594        // Script derivation and every wallet-index query remain after the
2595        // script-free binding has been authenticated against the account's
2596        // selected network.
2597        let scan = scan_hns_account_read(&self.backend, &self.store, &preparation, binding)?;
2598        let tip = binding.tip;
2599        let selected_after_scan = self.selector.selected_account()?;
2600        if selected_after_scan != preparation.fenced_account {
2601            return Err(HnsWalletError::StaleAccountRead);
2602        }
2603
2604        let common_ancestor = hns_read_common_ancestor(
2605            &self.backend,
2606            &preparation.recovery,
2607            scan.binding,
2608            preparation.fenced_account.config.birthday_height,
2609        )?;
2610        let previous_transactions = preparation
2611            .transactions
2612            .iter()
2613            .map(|stored| stored.value.clone())
2614            .collect::<Vec<_>>();
2615        let transactions = reconcile_hns_read_transactions(
2616            &self.backend,
2617            &scan.history,
2618            &scan.addresses,
2619            scan.binding,
2620            scan.mempool,
2621            common_ancestor,
2622            &previous_transactions,
2623        )?;
2624        let coins = reconcile_coins(scan.indexed_coins, &scan.addresses, tip.height)?;
2625        let names = reconcile_hns_read_names(
2626            &self.backend,
2627            &preparation.names,
2628            &scan.addresses,
2629            &coins,
2630            scan.binding,
2631        )?;
2632        let balance = coins.iter().try_fold(BaseUnits::ZERO, |total, coin| {
2633            if is_confirmed_ordinary_hns_spend_candidate(coin) {
2634                total
2635                    .checked_add(coin.coin.value)
2636                    .map_err(|_| HnsWalletError::Arithmetic)
2637            } else {
2638                Ok(total)
2639            }
2640        })?;
2641        let receive_target = hns_read_receive_target(&scan.account, &scan.addresses)?;
2642        let name_receive_target = hns_read_name_receive_target(&scan.account, &scan.addresses)?;
2643        let checkpoints = hns_read_checkpoints(
2644            &self.backend,
2645            scan.binding,
2646            scan.account.config.birthday_height,
2647        )?;
2648        let recovery = HnsRecoveryState {
2649            checkpoints,
2650            last_tip: Some(tip),
2651            last_common_ancestor: common_ancestor,
2652            last_reconciled_unix: now_unix,
2653        };
2654        verify_hns_read_snapshot_current(
2655            &self.backend,
2656            &scan.branch_scripts,
2657            scan.binding,
2658            scan.mempool,
2659        )?;
2660        self.store
2661            .with_store_mut(|store| {
2662                Ok(commit_hns_account_read(
2663                    store,
2664                    &preparation,
2665                    &scan.account,
2666                    &scan.addresses,
2667                    &coins,
2668                    &transactions,
2669                    &names,
2670                    &recovery,
2671                    now_unix,
2672                ))
2673            })
2674            .map_err(map_shared_store_error)??;
2675        if self.selector.selected_account()? != scan.account {
2676            return Err(HnsWalletError::StaleAccountRead);
2677        }
2678
2679        Ok(HnsAccountReadSnapshot {
2680            account_id: scan.account.config.account_id,
2681            binding: HnsAccountReadBinding {
2682                chain: scan.binding,
2683                mempool: scan.mempool,
2684            },
2685            balance: Amount {
2686                asset: WalletAsset::Hns,
2687                base_units: balance,
2688            },
2689            transactions: transactions
2690                .into_iter()
2691                .map(|transaction| transaction.summary)
2692                .collect(),
2693            receive_target,
2694            name_receive_target,
2695            known_names: names,
2696        })
2697    }
2698}
2699
2700/// Explicit recovery-only reader for one exact already-persisted HNS account
2701/// whose historical configuration contains a value or settlement flag.
2702///
2703/// The flags remain authenticated identity facts. They are never converted to
2704/// a permit or capability, and missing or non-exact persisted state fails on
2705/// selection. This wrapper exposes only exact selection and synchronized read
2706/// projection; its inner runtime is private, so current Shakedex-lock, Shakescape,
2707/// signing, import/export, workflow, broadcast, and value APIs are unreachable.
2708/// Synchronization may update WalletAccount scan/index metadata (never its
2709/// configuration), create or replace derived-address, coin, transaction, name,
2710/// and recovery-cache rows, and write or clear the durable discovery fence. It
2711/// cannot create an account, profile, allocation, signer, workflow, or value
2712/// authority or alter the selected account configuration. Every such cache row
2713/// is bounded, authenticated, and scoped to that exact existing account.
2714///
2715/// ```compile_fail
2716/// # use hns_wallet_hns::{HnsBackend, HnsClock, HnsPersistedRecoveryReadOnlyRuntime};
2717/// # fn no_market_authority<B: HnsBackend, C: HnsClock>(
2718/// #     runtime: &HnsPersistedRecoveryReadOnlyRuntime<B, C>,
2719/// # ) {
2720/// let _ = runtime.verify_current_shakedex_lock(b"name", [2_u8; 33]);
2721/// # }
2722/// ```
2723pub struct HnsPersistedRecoveryReadOnlyRuntime<B, C = SystemClock> {
2724    inner: HnsAccountReadRuntime<B, C>,
2725}
2726
2727impl<B: HnsBackend, C: HnsClock> HnsPersistedRecoveryReadOnlyRuntime<B, C> {
2728    /// Select an exact existing flagged account for recovery reads. Construction
2729    /// validates structure only and never writes; later selection requires the
2730    /// complete persisted configuration to match byte-for-byte.
2731    pub fn new(
2732        backend: B,
2733        clock: C,
2734        store: SharedWalletStore,
2735        expected: HnsRuntimeConfig,
2736    ) -> Result<Self, HnsWalletError> {
2737        let selector = HnsExistingAccountSelector::new_with_mode(
2738            store.clone(),
2739            expected,
2740            HnsAccountReadMode::PersistedRecoveryReadOnly,
2741        )?;
2742        Ok(Self {
2743            inner: HnsAccountReadRuntime::new_with_selector(backend, clock, store, selector)?,
2744        })
2745    }
2746
2747    pub fn shares_store_authority(&self, store: &SharedWalletStore) -> bool {
2748        self.inner.shares_store_authority(store)
2749    }
2750
2751    pub fn selected_account(&self) -> Result<HnsAccountRecord, HnsWalletError> {
2752        self.inner.selected_account()
2753    }
2754
2755    pub fn synchronize(&self) -> Result<HnsAccountReadSnapshot, HnsWalletError> {
2756        self.inner.synchronize()
2757    }
2758}
2759
2760#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
2761pub struct DerivedHnsAddress {
2762    pub account_id: AccountId,
2763    pub derivation: DerivationReference,
2764    pub address: String,
2765    pub program: Vec<u8>,
2766    pub used: bool,
2767}
2768
2769#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
2770pub struct TrackedHnsCoin {
2771    pub coin: WalletCoin,
2772    pub derivation: DerivationReference,
2773    pub address_program: Vec<u8>,
2774}
2775
2776impl TrackedHnsCoin {
2777    /// Reconstruct the exact consensus coin used by script and fee policy.
2778    /// Legacy rows and any mismatch between projected and canonical evidence
2779    /// are deliberately unusable until a fresh bound reconciliation replaces
2780    /// them.
2781    pub fn to_canonical_coin(&self) -> Result<Coin, HnsWalletError> {
2782        if self.coin.confirmation_count == 0
2783            || validate_restore_program(self.derivation, &self.address_program).is_err()
2784        {
2785            return Err(HnsWalletError::InvalidEvidence);
2786        }
2787        let covenant = decode_canonical_covenant(&self.coin.covenant)?;
2788        if self.coin.name_locked == matches!(covenant.kind, CovenantKind::None) {
2789            return Err(HnsWalletError::InvalidEvidence);
2790        }
2791        if self.coin.value.is_zero()
2792            && (!is_wallet_tracked_name_utxo_derivation(self.derivation)
2793                || !is_active_name_owner_covenant(covenant.kind))
2794        {
2795            return Err(HnsWalletError::InvalidEvidence);
2796        }
2797        canonical_coin_from_evidence(
2798            self.coin.outpoint,
2799            self.coin.value,
2800            self.coin.confirmed_height,
2801            self.coin.coinbase,
2802            0,
2803            self.address_program.clone(),
2804            covenant,
2805        )
2806    }
2807
2808    fn to_input_evidence(&self) -> Result<HnsInputCoinEvidence, HnsWalletError> {
2809        let canonical = self.to_canonical_coin()?;
2810        HnsInputCoinEvidence::from_canonical_coin(&canonical)
2811    }
2812}
2813
2814/// Serializable, exact input-coin evidence retained beside signed workflows.
2815/// It carries all fields required by canonical script sigop and fee policy so
2816/// restart/rebroadcast validation never falls back to a node assertion.
2817#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
2818pub struct HnsInputCoinEvidence {
2819    pub outpoint: HnsOutpoint,
2820    pub value: BaseUnits,
2821    #[serde(default)]
2822    pub confirmed_height: Option<u32>,
2823    pub coinbase: bool,
2824    pub address_version: u8,
2825    pub address_hash: Vec<u8>,
2826    #[serde(default)]
2827    pub covenant: Vec<u8>,
2828}
2829
2830impl HnsInputCoinEvidence {
2831    pub fn to_canonical_coin(&self) -> Result<Coin, HnsWalletError> {
2832        let covenant = decode_canonical_covenant(&self.covenant)?;
2833        if self.value.is_zero() && !is_active_name_owner_covenant(covenant.kind) {
2834            return Err(HnsWalletError::InvalidEvidence);
2835        }
2836        canonical_coin_from_evidence(
2837            self.outpoint,
2838            self.value,
2839            self.confirmed_height,
2840            self.coinbase,
2841            self.address_version,
2842            self.address_hash.clone(),
2843            covenant,
2844        )
2845    }
2846
2847    fn from_canonical_coin(coin: &Coin) -> Result<Self, HnsWalletError> {
2848        if coin.outpoint.is_null() {
2849            return Err(HnsWalletError::InvalidEvidence);
2850        }
2851        let covenant = coin
2852            .covenant
2853            .encode()
2854            .map_err(|_| HnsWalletError::InvalidEvidence)?;
2855        Ok(Self {
2856            outpoint: HnsOutpoint {
2857                transaction: TransactionHash::new(coin.outpoint.transaction_hash.into_bytes()),
2858                output_index: coin.outpoint.index,
2859            },
2860            value: BaseUnits::new(u128::from(coin.value.get())),
2861            confirmed_height: Some(coin.height.get()),
2862            coinbase: coin.coinbase,
2863            address_version: coin.address.version,
2864            address_hash: coin.address.hash.clone(),
2865            covenant,
2866        })
2867    }
2868}
2869
2870const fn is_active_name_owner_covenant(kind: CovenantKind) -> bool {
2871    matches!(
2872        kind,
2873        CovenantKind::Claim
2874            | CovenantKind::Reveal
2875            | CovenantKind::Register
2876            | CovenantKind::Update
2877            | CovenantKind::Renew
2878            | CovenantKind::Transfer
2879            | CovenantKind::Finalize
2880    )
2881}
2882
2883fn decode_canonical_covenant(encoded: &[u8]) -> Result<Covenant, HnsWalletError> {
2884    if encoded.is_empty() {
2885        return Err(HnsWalletError::InvalidEvidence);
2886    }
2887    let covenant = Covenant::decode(encoded).map_err(|_| HnsWalletError::InvalidEvidence)?;
2888    if covenant
2889        .encode()
2890        .map_err(|_| HnsWalletError::InvalidEvidence)?
2891        != encoded
2892    {
2893        return Err(HnsWalletError::InvalidEvidence);
2894    }
2895    Ok(covenant)
2896}
2897
2898fn canonical_coin_from_evidence(
2899    outpoint: HnsOutpoint,
2900    value: BaseUnits,
2901    confirmed_height: Option<u32>,
2902    coinbase: bool,
2903    address_version: u8,
2904    address_hash: Vec<u8>,
2905    covenant: Covenant,
2906) -> Result<Coin, HnsWalletError> {
2907    let outpoint = Outpoint {
2908        transaction_hash: CanonicalTransactionHash::new(outpoint.transaction.into_bytes()),
2909        index: outpoint.output_index,
2910    };
2911    if outpoint.is_null() {
2912        return Err(HnsWalletError::InvalidEvidence);
2913    }
2914    let value = u64::try_from(value.get()).map_err(|_| HnsWalletError::InvalidEvidence)?;
2915    let height = confirmed_height.ok_or(HnsWalletError::InvalidEvidence)?;
2916    let address =
2917        Address::new(address_version, address_hash).map_err(|_| HnsWalletError::InvalidEvidence)?;
2918    Ok(Coin {
2919        outpoint,
2920        value: Dollarydoos::new(value),
2921        height: Height::new(height),
2922        coinbase,
2923        address,
2924        covenant,
2925    })
2926}
2927
2928pub(crate) fn canonical_input_coins(
2929    inputs: &[TrackedHnsCoin],
2930) -> Result<Vec<Coin>, HnsWalletError> {
2931    if inputs.is_empty() || inputs.len() > MAX_TRANSACTION_INPUTS {
2932        return Err(HnsWalletError::InvalidEvidence);
2933    }
2934    inputs
2935        .iter()
2936        .map(TrackedHnsCoin::to_canonical_coin)
2937        .collect()
2938}
2939
2940fn canonical_evidence_coins(inputs: &[HnsInputCoinEvidence]) -> Result<Vec<Coin>, HnsWalletError> {
2941    if inputs.is_empty() || inputs.len() > MAX_TRANSACTION_INPUTS {
2942        return Err(HnsWalletError::InvalidEvidence);
2943    }
2944    inputs
2945        .iter()
2946        .map(HnsInputCoinEvidence::to_canonical_coin)
2947        .collect()
2948}
2949
2950fn input_coin_evidence(
2951    inputs: &[TrackedHnsCoin],
2952) -> Result<Vec<HnsInputCoinEvidence>, HnsWalletError> {
2953    if inputs.is_empty() || inputs.len() > MAX_TRANSACTION_INPUTS {
2954        return Err(HnsWalletError::InvalidEvidence);
2955    }
2956    inputs
2957        .iter()
2958        .map(TrackedHnsCoin::to_input_evidence)
2959        .collect()
2960}
2961
2962/// Preserve the HTLC funding coin first and append optional ordinary-wallet
2963/// fee sponsors. The generic wallet-input encoder intentionally rejects an
2964/// empty selection, but an HNS settlement that can pay its fee from the HTLC
2965/// value itself has no sponsor inputs and is still a complete one-input
2966/// transaction.
2967fn settlement_input_evidence(
2968    funding_coin: HnsInputCoinEvidence,
2969    sponsors: &[TrackedHnsCoin],
2970) -> Result<Vec<HnsInputCoinEvidence>, HnsWalletError> {
2971    let mut evidence = Vec::with_capacity(1 + sponsors.len());
2972    evidence.push(funding_coin);
2973    if !sponsors.is_empty() {
2974        evidence.extend(input_coin_evidence(sponsors)?);
2975    }
2976    Ok(evidence)
2977}
2978
2979#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
2980pub struct HnsTransactionRecord {
2981    pub summary: TransactionSummary,
2982    pub raw: Vec<u8>,
2983    pub inclusion: Option<TransactionInclusion>,
2984}
2985
2986#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
2987pub struct HnsChainCheckpoint {
2988    pub height: u64,
2989    pub block_hash: [u8; 32],
2990}
2991
2992#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
2993pub struct HnsRecoveryState {
2994    pub checkpoints: Vec<HnsChainCheckpoint>,
2995    pub last_tip: Option<ChainTip>,
2996    pub last_common_ancestor: Option<u64>,
2997    pub last_reconciled_unix: u64,
2998}
2999
3000#[derive(Clone, Debug, Eq, PartialEq)]
3001pub struct HnsReconciliationReport {
3002    pub tip: ChainTip,
3003    pub common_ancestor: Option<u64>,
3004    pub reorg_detected: bool,
3005    pub restored_utxos: usize,
3006    pub reconciled_transactions: usize,
3007    pub revalidated_names: usize,
3008    pub pending_user_actions: Vec<WorkflowId>,
3009}
3010
3011pub trait HnsClock: Send + Sync {
3012    fn now_unix(&self) -> Result<u64, HnsWalletError>;
3013}
3014
3015#[derive(Clone, Copy, Debug, Default)]
3016pub struct SystemClock;
3017
3018impl HnsClock for SystemClock {
3019    fn now_unix(&self) -> Result<u64, HnsWalletError> {
3020        SystemTime::now()
3021            .duration_since(UNIX_EPOCH)
3022            .map_err(|_| HnsWalletError::Clock)
3023            .map(|duration| duration.as_secs())
3024    }
3025}
3026
3027#[derive(Clone, Debug)]
3028struct HnsRuntimeCache {
3029    account: HnsAccountRecord,
3030    account_revision: u64,
3031    sync: SyncStatus,
3032    coins: Vec<TrackedHnsCoin>,
3033    transactions: Vec<HnsTransactionRecord>,
3034    binding: Option<SnapshotBinding>,
3035    mempool_binding: Option<MempoolSnapshotBinding>,
3036}
3037
3038struct HnsReadPreparation {
3039    fenced_account: HnsAccountRecord,
3040    scan_account: HnsAccountRecord,
3041    account_revision: u64,
3042    recovery: HnsRecoveryState,
3043    recovery_row: Option<StoredEntity<HnsRecoveryState>>,
3044    coins: Vec<StoredEntity<TrackedHnsCoin>>,
3045    transactions: Vec<StoredEntity<HnsTransactionRecord>>,
3046    names: Vec<StoredEntity<KnownName>>,
3047}
3048
3049struct HnsNameBulkImportPreparation {
3050    account: StoredEntity<HnsAccountRecord>,
3051    names: Vec<StoredEntity<KnownName>>,
3052}
3053
3054struct HnsReadScan {
3055    account: HnsAccountRecord,
3056    binding: SnapshotBinding,
3057    mempool: MempoolSnapshotBinding,
3058    addresses: Vec<DerivedHnsAddress>,
3059    history: Vec<HistoryEntry>,
3060    indexed_coins: Vec<IndexedWalletCoin>,
3061    branch_scripts: [Vec<WalletAddressKey>; 2],
3062}
3063
3064type RestoreScanResult = (
3065    HnsAccountRecord,
3066    u64,
3067    SnapshotBinding,
3068    MempoolSnapshotBinding,
3069    Vec<DerivedHnsAddress>,
3070    Vec<HistoryEntry>,
3071    Vec<IndexedWalletCoin>,
3072);
3073
3074#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
3075#[serde(rename_all = "snake_case")]
3076pub enum HnsSendStage {
3077    Prepared,
3078    Authorized,
3079    Broadcast,
3080    Mempool,
3081    Confirmed,
3082    Conflicted,
3083    RequiresRebroadcast,
3084    /// The transaction disappeared from authenticated chain and mempool
3085    /// evidence, and its exact approved bytes no longer satisfy the current
3086    /// fee policy. Its inputs are released so a fresh, explicitly reviewed
3087    /// replacement can be prepared.
3088    Abandoned,
3089    Expired,
3090    Cancelled,
3091}
3092
3093#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
3094struct HnsSpendPlan {
3095    wallet_id: WalletId,
3096    account_id: AccountId,
3097    workflow_id: WorkflowId,
3098    request_nonce: u64,
3099    unsigned_transaction: Vec<u8>,
3100    inputs: Vec<TrackedHnsCoin>,
3101    amount: BaseUnits,
3102    fee: BaseUnits,
3103    maximum_fee: BaseUnits,
3104    destination: String,
3105    expires_at_unix: u64,
3106}
3107
3108#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)]
3109struct HnsSendWorkflow {
3110    plan: HnsSpendPlan,
3111    stage: HnsSendStage,
3112    transaction: Option<TransactionHash>,
3113    signed_transaction: Option<Vec<u8>>,
3114    #[serde(default)]
3115    fee_quote: Option<HnsTransactionFeeQuote>,
3116}
3117
3118impl fmt::Debug for HnsSendWorkflow {
3119    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3120        formatter
3121            .debug_struct("HnsSendWorkflow")
3122            .field("workflow_id", &self.plan.workflow_id)
3123            .field("stage", &self.stage)
3124            .field("transaction", &self.transaction)
3125            .field(
3126                "signed_transaction",
3127                &self.signed_transaction.as_ref().map(|_| "[REDACTED]"),
3128            )
3129            .finish()
3130    }
3131}
3132
3133#[derive(Serialize, Deserialize)]
3134struct HnsSendApproval {
3135    workflow_id: WorkflowId,
3136    commitment: [u8; 32],
3137}
3138
3139#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
3140pub struct HnsInputReservation {
3141    wallet_id: WalletId,
3142    account_id: AccountId,
3143    outpoint: HnsOutpoint,
3144    workflow_id: WorkflowId,
3145    expires_at_unix: Option<u64>,
3146    #[serde(default)]
3147    kind: HnsInputReservationKind,
3148}
3149
3150#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
3151#[serde(rename_all = "snake_case")]
3152enum HnsSettlementAction {
3153    Lock,
3154    Redeem,
3155    Refund,
3156}
3157
3158#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
3159#[serde(rename_all = "snake_case")]
3160enum HnsSettlementStage {
3161    Prepared,
3162    Broadcast,
3163    Mempool,
3164    Confirmed,
3165    Conflicted,
3166    RequiresRebroadcast,
3167    Expired,
3168    Cancelled,
3169}
3170
3171/// Non-sensitive state of this wallet's durable HNS redeem submission.
3172#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3173pub enum HnsRedeemSubmissionStage {
3174    Queued,
3175    Submitted,
3176    Seen,
3177    Confirmed,
3178    NeedsRecovery,
3179}
3180
3181#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3182pub struct HnsRedeemSubmission {
3183    pub transaction: TransactionHash,
3184    pub stage: HnsRedeemSubmissionStage,
3185}
3186
3187/// Read the exact session's approved redeem checkpoint. A merely prepared
3188/// transaction is still awaiting approval and must not hide the redeem action.
3189pub fn hns_redeem_submission(
3190    store: &WalletStore,
3191    config: &HnsRuntimeConfig,
3192    session_id: SessionId,
3193) -> Result<Option<HnsRedeemSubmission>, HnsWalletError> {
3194    let id = settlement_workflow_id(config, session_id, HnsSettlementAction::Redeem);
3195    let Some(stored) = store.load_workflow::<serde_json::Value>(id)? else {
3196        return Ok(None);
3197    };
3198    if stored.kind != WorkflowKind::AtomicSwap {
3199        return Err(HnsWalletError::InvalidWorkflow);
3200    }
3201    let state: HnsPreparedSettlement = serde_json::from_value(stored.state)?;
3202    if state.workflow_id != id
3203        || state.session_id != session_id
3204        || state.wallet_id != config.wallet_id
3205        || state.account_id != config.account_id
3206        || state.action != HnsSettlementAction::Redeem
3207    {
3208        return Err(HnsWalletError::InvalidWorkflow);
3209    }
3210    let stage = match state.stage {
3211        HnsSettlementStage::Prepared if stored.irreversible_broadcast_prepared => {
3212            Some(HnsRedeemSubmissionStage::Queued)
3213        }
3214        HnsSettlementStage::Broadcast => Some(HnsRedeemSubmissionStage::Submitted),
3215        HnsSettlementStage::Mempool => Some(HnsRedeemSubmissionStage::Seen),
3216        HnsSettlementStage::Confirmed => Some(HnsRedeemSubmissionStage::Confirmed),
3217        HnsSettlementStage::RequiresRebroadcast => Some(HnsRedeemSubmissionStage::Queued),
3218        HnsSettlementStage::Conflicted => Some(HnsRedeemSubmissionStage::NeedsRecovery),
3219        _ => None,
3220    };
3221    Ok(stage.map(|stage| HnsRedeemSubmission {
3222        transaction: state.transaction,
3223        stage,
3224    }))
3225}
3226
3227/// Exact persisted ShakeScape state that must still authorize a guarded HNS
3228/// redeem when its signed transaction crosses the irreversible broadcast
3229/// checkpoint. The workflow revision binds current funding authority; the
3230/// signed-session entity revision binds the session and network policy that
3231/// produced it.
3232#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
3233#[serde(deny_unknown_fields)]
3234pub struct HnsSettlementBroadcastGuard {
3235    session_id: SessionId,
3236    execution_workflow_id: WorkflowId,
3237    execution_revision: u64,
3238    entity_id: Vec<u8>,
3239    entity_revision: u64,
3240    purpose: HnsSettlementBroadcastGuardPurpose,
3241}
3242
3243#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
3244#[serde(rename_all = "snake_case", tag = "purpose")]
3245enum HnsSettlementBroadcastGuardPurpose {
3246    CurrentRedeem,
3247    SecondFunding {
3248        authorization_id: ObjectHash,
3249        module: ModuleId,
3250        expires_at_unix: u64,
3251    },
3252}
3253
3254impl HnsSettlementBroadcastGuard {
3255    pub fn new(
3256        session_id: SessionId,
3257        execution_workflow_id: WorkflowId,
3258        execution_revision: u64,
3259        session_record_id: Vec<u8>,
3260        session_record_revision: u64,
3261    ) -> Result<Self, HnsWalletError> {
3262        let guard = Self {
3263            session_id,
3264            execution_workflow_id,
3265            execution_revision,
3266            entity_id: session_record_id,
3267            entity_revision: session_record_revision,
3268            purpose: HnsSettlementBroadcastGuardPurpose::CurrentRedeem,
3269        };
3270        if !guard.is_valid() {
3271            return Err(HnsWalletError::InvalidEvidence);
3272        }
3273        Ok(guard)
3274    }
3275
3276    #[allow(clippy::too_many_arguments)]
3277    pub fn new_second_funding(
3278        session_id: SessionId,
3279        execution_workflow_id: WorkflowId,
3280        execution_revision: u64,
3281        authorization_entity_id: Vec<u8>,
3282        authorization_entity_revision: u64,
3283        authorization_id: ObjectHash,
3284        module: ModuleId,
3285        expires_at_unix: u64,
3286    ) -> Result<Self, HnsWalletError> {
3287        let guard = Self {
3288            session_id,
3289            execution_workflow_id,
3290            execution_revision,
3291            entity_id: authorization_entity_id,
3292            entity_revision: authorization_entity_revision,
3293            purpose: HnsSettlementBroadcastGuardPurpose::SecondFunding {
3294                authorization_id,
3295                module,
3296                expires_at_unix,
3297            },
3298        };
3299        if !guard.is_valid() || module != ModuleId::Handshake {
3300            return Err(HnsWalletError::InvalidEvidence);
3301        }
3302        Ok(guard)
3303    }
3304
3305    fn is_valid(&self) -> bool {
3306        !self.session_id.as_bytes().iter().all(|byte| *byte == 0)
3307            && !self
3308                .execution_workflow_id
3309                .as_bytes()
3310                .iter()
3311                .all(|byte| *byte == 0)
3312            && self.execution_revision != 0
3313            && !self.entity_id.is_empty()
3314            && self.entity_revision != 0
3315            && match self.purpose {
3316                HnsSettlementBroadcastGuardPurpose::CurrentRedeem => true,
3317                HnsSettlementBroadcastGuardPurpose::SecondFunding {
3318                    authorization_id,
3319                    module,
3320                    expires_at_unix,
3321                } => {
3322                    authorization_id.as_bytes().iter().any(|byte| *byte != 0)
3323                        && module == ModuleId::Handshake
3324                        && expires_at_unix != 0
3325                }
3326            }
3327    }
3328
3329    fn authorizes_action(
3330        &self,
3331        action: HnsSettlementAction,
3332        session_id: SessionId,
3333        now_unix: Option<u64>,
3334    ) -> bool {
3335        if self.session_id != session_id || !self.is_valid() {
3336            return false;
3337        }
3338        match self.purpose {
3339            HnsSettlementBroadcastGuardPurpose::CurrentRedeem => {
3340                action == HnsSettlementAction::Redeem
3341            }
3342            HnsSettlementBroadcastGuardPurpose::SecondFunding {
3343                expires_at_unix, ..
3344            } => {
3345                action == HnsSettlementAction::Lock
3346                    && now_unix.is_none_or(|now_unix| now_unix < expires_at_unix)
3347            }
3348        }
3349    }
3350
3351    const fn entity_kind(&self) -> EntityKind {
3352        match self.purpose {
3353            HnsSettlementBroadcastGuardPurpose::CurrentRedeem => EntityKind::SwapSession,
3354            HnsSettlementBroadcastGuardPurpose::SecondFunding { .. } => {
3355                EntityKind::SwapFundingAuthorization
3356            }
3357        }
3358    }
3359
3360    const fn consumes_entity(&self) -> bool {
3361        matches!(
3362            self.purpose,
3363            HnsSettlementBroadcastGuardPurpose::SecondFunding { .. }
3364        )
3365    }
3366}
3367
3368#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
3369#[serde(rename_all = "snake_case", tag = "action")]
3370enum HnsSettlementTerms {
3371    Lock { request: SettlementLockRequest },
3372    Redeem { lock: VerifiedLock },
3373    Refund { lock: VerifiedLock },
3374}
3375
3376#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
3377struct HnsVerifiedSettlementRecord {
3378    expected: SettlementLockExpectation,
3379    verified: VerifiedLock,
3380    output_index: u32,
3381    script: Vec<u8>,
3382    /// Exact confirmed funding output used for local script/fee policy. A
3383    /// missing legacy value cannot authorize a settlement spend.
3384    #[serde(default)]
3385    funding_coin: Option<HnsInputCoinEvidence>,
3386}
3387
3388/// A native-HNS HTLC spend authenticated against the wallet's locally
3389/// verified funding coin and the current proof-bound transaction evidence.
3390/// Peer notices never construct this value: the runtime re-executes the HNS
3391/// witness program and reports the branch it observed.
3392#[derive(Clone, Debug, Eq, PartialEq)]
3393pub enum VerifiedNativeHtlcSpend {
3394    Redeem {
3395        transaction: TransactionHash,
3396        confirmation_count: u32,
3397        preimage: Preimage,
3398    },
3399    Refund {
3400        transaction: TransactionHash,
3401        confirmation_count: u32,
3402    },
3403}
3404
3405#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)]
3406struct HnsPreparedSettlement {
3407    wallet_id: WalletId,
3408    account_id: AccountId,
3409    workflow_id: WorkflowId,
3410    session_id: SessionId,
3411    action: HnsSettlementAction,
3412    stage: HnsSettlementStage,
3413    transaction: TransactionHash,
3414    signed_transaction: Vec<u8>,
3415    /// Ordered one-for-one with the transaction inputs. Empty legacy evidence
3416    /// is retained only so decoding succeeds and validation can fail closed.
3417    #[serde(default)]
3418    input_coins: Vec<HnsInputCoinEvidence>,
3419    fee: BaseUnits,
3420    #[serde(default)]
3421    maximum_fee: BaseUnits,
3422    #[serde(default)]
3423    fee_quote: Option<HnsTransactionFeeQuote>,
3424    expires_at_unix: u64,
3425    terms: HnsSettlementTerms,
3426    #[serde(default)]
3427    recovery_publication: Option<recovery_publication::HnsRecoveryPackage>,
3428    #[serde(default)]
3429    broadcast_guard: Option<HnsSettlementBroadcastGuard>,
3430}
3431
3432/// Exact value accounting for a prepared HNS settlement transaction.
3433///
3434/// A small HTLC can require confirmed ordinary wallet inputs to sponsor its
3435/// network fee. Callers must therefore review the transaction's complete
3436/// input and output totals rather than assuming `HTLC amount - fee` describes
3437/// the final transaction.
3438#[derive(Clone, Copy, Debug, Eq, PartialEq)]
3439pub struct HnsPreparedSettlementValueSummary {
3440    pub total_input: BaseUnits,
3441    pub total_output: BaseUnits,
3442    pub settlement_input: BaseUnits,
3443    pub wallet_sponsor_input: BaseUnits,
3444}
3445
3446impl fmt::Debug for HnsPreparedSettlement {
3447    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3448        formatter
3449            .debug_struct("HnsPreparedSettlement")
3450            .field("workflow_id", &self.workflow_id)
3451            .field("session_id", &self.session_id)
3452            .field("action", &self.action)
3453            .field("stage", &self.stage)
3454            .field("transaction", &self.transaction)
3455            .field("fee", &self.fee)
3456            .field("maximum_fee", &self.maximum_fee)
3457            .field("fee_quote", &self.fee_quote)
3458            .field("expires_at_unix", &self.expires_at_unix)
3459            .field("terms", &self.terms)
3460            .field("signed_transaction", &"[REDACTED]")
3461            .finish()
3462    }
3463}
3464
3465impl HnsPreparedSettlement {
3466    fn canonical_input_coins(&self) -> Result<Vec<Coin>, HnsWalletError> {
3467        if self.recovery_publication.is_some() {
3468            recovery_publication::canonical_package_inputs(&self.input_coins)
3469        } else {
3470            canonical_evidence_coins(&self.input_coins)
3471        }
3472    }
3473    fn approved_fee(&self) -> Result<BaseUnits, HnsWalletError> {
3474        let mut fee = self.fee.get();
3475        if let Some(package) = &self.recovery_publication {
3476            for ancestor in &package.ancestors {
3477                fee = fee
3478                    .checked_add(ancestor.fee.get())
3479                    .ok_or(HnsWalletError::Arithmetic)?;
3480            }
3481        }
3482        Ok(BaseUnits::new(fee))
3483    }
3484}
3485
3486pub struct HnsWalletRuntime<B, C = SystemClock> {
3487    backend: B,
3488    clock: C,
3489    store: SharedWalletStore,
3490    cache: RwLock<HnsRuntimeCache>,
3491}
3492
3493impl<B: HnsBackend, C: HnsClock> HnsWalletRuntime<B, C> {
3494    pub fn open(
3495        backend: B,
3496        store: WalletStore,
3497        config: HnsRuntimeConfig,
3498        clock: C,
3499    ) -> Result<Self, HnsWalletError> {
3500        Self::open_shared(backend, SharedWalletStore::new(store), config, clock)
3501    }
3502
3503    /// Open the full HNS runtime over the exact Arc-backed store/key authority
3504    /// shared with provider, browser-service, and Shakescape components.
3505    ///
3506    /// The supplied store must already be unlocked. Every clone observes the
3507    /// same lock transition, and [`Self::shares_store_authority`] lets the
3508    /// enclosing product reject a separately opened connection even when it
3509    /// names the same database path.
3510    pub fn open_shared(
3511        backend: B,
3512        store: SharedWalletStore,
3513        config: HnsRuntimeConfig,
3514        clock: C,
3515    ) -> Result<Self, HnsWalletError> {
3516        config.validate()?;
3517        if store.is_locked()? {
3518            return Err(HnsWalletError::StoreLocked);
3519        }
3520        let (account, account_revision, coins, transactions) =
3521            store.try_with_store_mut(|wallet| {
3522                for stored in wallet.list_entities_by_id_prefix::<HnsAccountRecord>(
3523                    EntityKind::WalletAccount,
3524                    config.wallet_id.as_bytes(),
3525                    MAX_HISTORY_RESULTS,
3526                )? {
3527                    if stored.id != account_entity_id(&stored.value.config)
3528                        || stored.value.config.wallet_id != config.wallet_id
3529                    {
3530                        return Err(HnsWalletError::InvalidEvidence);
3531                    }
3532                    if stored.value.config.account_id != config.account_id
3533                        && stored.value.config.account_derivation_index
3534                            == config.account_derivation_index
3535                    {
3536                        return Err(HnsWalletError::DuplicateAccountDerivation);
3537                    }
3538                }
3539                let existing: Option<StoredEntity<HnsAccountRecord>> =
3540                    wallet.wallet_account(&account_entity_id(&config))?;
3541                let (account, account_revision) = match existing {
3542                    Some(mut stored) => {
3543                        if !same_account_identity(&stored.value.config, &config) {
3544                            return Err(HnsWalletError::AccountConfigurationMismatch);
3545                        }
3546                        if stored.value.config != config {
3547                            stored.value.config = config;
3548                            stored.revision = wallet.save_wallet_account(
3549                                &account_entity_id(&stored.value.config),
3550                                stored.revision,
3551                                &stored.value,
3552                                clock.now_unix()?,
3553                            )?;
3554                        }
3555                        (stored.value, stored.revision)
3556                    }
3557                    None => {
3558                        let external_scan_end = config.restore_lookahead - 1;
3559                        let account = HnsAccountRecord {
3560                            config,
3561                            next_receive_index: 0,
3562                            next_change_index: 0,
3563                            next_shakedex_index: 0,
3564                            external_scan_end,
3565                            internal_scan_end: external_scan_end,
3566                            shakedex_scan_end: external_scan_end,
3567                            shakedex_scan_complete: false,
3568                            shakedex_scan_in_progress: false,
3569                            last_used_external: None,
3570                            last_used_internal: None,
3571                            last_used_shakedex: None,
3572                        };
3573                        let revision = wallet.save_wallet_account(
3574                            &account_entity_id(&account.config),
3575                            0,
3576                            &account,
3577                            clock.now_unix()?,
3578                        )?;
3579                        (account, revision)
3580                    }
3581                };
3582                let entity_prefix = account_entity_prefix(&account.config);
3583                let coins = wallet
3584                    .list_entities_by_id_prefix::<TrackedHnsCoin>(
3585                        EntityKind::HnsUtxo,
3586                        &entity_prefix,
3587                        MAX_WALLET_COINS,
3588                    )?
3589                    .into_iter()
3590                    .map(|entity| entity.value)
3591                    .collect();
3592                let transactions = wallet
3593                    .list_entities_by_id_prefix::<HnsTransactionRecord>(
3594                        EntityKind::HnsTransaction,
3595                        &entity_prefix,
3596                        MAX_HISTORY_RESULTS,
3597                    )?
3598                    .into_iter()
3599                    .map(|entity| entity.value)
3600                    .collect();
3601                Ok::<_, HnsWalletError>((account, account_revision, coins, transactions))
3602            })?;
3603        Ok(Self {
3604            backend,
3605            clock,
3606            store,
3607            cache: RwLock::new(HnsRuntimeCache {
3608                account,
3609                account_revision,
3610                sync: SyncStatus {
3611                    phase: SyncPhase::Starting,
3612                    validated_height: 0,
3613                    scanned_height: 0,
3614                    target_height: None,
3615                    last_error: None,
3616                },
3617                coins,
3618                transactions,
3619                binding: None,
3620                mempool_binding: None,
3621            }),
3622        })
3623    }
3624
3625    pub fn backend(&self) -> &B {
3626        &self.backend
3627    }
3628
3629    /// Trusted wall-clock seconds from the exact clock authority retained by
3630    /// this runtime. Adjacent same-store transports use this instead of
3631    /// introducing a second independently configurable time source.
3632    pub fn trusted_now_unix(&self) -> Result<u64, HnsWalletError> {
3633        self.clock.now_unix()
3634    }
3635
3636    /// Exact canonical network binding for adjacent Shakedex/Shakescape runtime
3637    /// composition.
3638    pub fn shakedex_network(&self) -> Result<NetworkBinding, HnsWalletError> {
3639        shakedex_network_binding(self.configured_runtime_config()?.network)
3640    }
3641
3642    /// Prove that another component retains the identical process-local
3643    /// database/key authority used by this signing runtime.
3644    pub fn shares_store_authority(&self, store: &SharedWalletStore) -> bool {
3645        self.store.is_same_authority(store)
3646    }
3647
3648    /// Return the account policy retained by this full runtime without
3649    /// consulting the node or reopening the encrypted store. Product
3650    /// composition uses this cache-only view while the shared store is locked
3651    /// to verify that the already-open runtime is the exact requested value
3652    /// runtime before exposing any service capability.
3653    pub fn configured_runtime_config(&self) -> Result<HnsRuntimeConfig, HnsWalletError> {
3654        Ok(self.cache_read()?.account.config.clone())
3655    }
3656
3657    /// Reauthenticate the full runtime's cached account against the exact
3658    /// shared store row before an adjacent product component relies on it.
3659    /// A store mutation that has not yet been synchronized into the runtime
3660    /// is reported as stale instead of silently mixing two account revisions.
3661    pub fn selected_account_with_revision(
3662        &self,
3663    ) -> Result<SelectedHnsAccountRevision, HnsWalletError> {
3664        let (account, cached_revision) = {
3665            let cache = self.cache_read()?;
3666            (cache.account.clone(), cache.account_revision)
3667        };
3668        let account_id = account_entity_id(&account.config);
3669        let current_revision = self.store.try_with_store(|store| {
3670            if store.is_locked() {
3671                return Err(HnsWalletError::StoreLocked);
3672            }
3673            store.try_with_entity_read_snapshot(|snapshot| {
3674                validate_hns_board_account_snapshot(snapshot, &account_id, &account)
3675            })
3676        })?;
3677        if current_revision != cached_revision {
3678            return Err(HnsWalletError::StaleAccountRead);
3679        }
3680        Ok(SelectedHnsAccountRevision {
3681            account,
3682            revision: current_revision,
3683        })
3684    }
3685
3686    /// Derive the current ordinary HNS payment receive target from the exact
3687    /// authenticated local account. Unlike the `ChainModule` receive method,
3688    /// this does not assert a synchronized chain view and does not contact a
3689    /// backend. It is intended only for the trusted native receive UI.
3690    pub fn local_receive_target(&self) -> Result<ReceiveTarget, HnsWalletError> {
3691        let selected = self.selected_account_with_revision()?;
3692        let target = local_hns_payment_receive_target(&self.store, &selected.account)?;
3693        if self.selected_account_with_revision()? != selected {
3694            return Err(HnsWalletError::StaleAccountRead);
3695        }
3696        Ok(target)
3697    }
3698
3699    /// Observe the exact full-runtime account, Shakedex network, and trusted
3700    /// time while retaining a refreshable encrypted account-prefix guard.
3701    /// This is metadata/cancellation authority only; it cannot sign or move
3702    /// value and must be consumed by an exact same-store board operation.
3703    pub fn observe_board_context(&self) -> Result<VerifiedHnsBoardContext, HnsWalletError> {
3704        let selected = self.selected_account_with_revision()?;
3705        let account_id = account_entity_id(&selected.account.config);
3706        let (account_revision, account_prefix_lease) = self.store.try_with_store(|store| {
3707            if store.is_locked() {
3708                return Err(HnsWalletError::StoreLocked);
3709            }
3710            store.try_with_entity_read_snapshot(|snapshot| {
3711                capture_hns_board_account_snapshot(snapshot, &account_id, &selected.account)
3712            })
3713        })?;
3714        if account_revision != selected.revision {
3715            return Err(HnsWalletError::StaleAccountRead);
3716        }
3717        let observed_at_unix = self.clock.now_unix()?;
3718        let selected_after_clock = self.selected_account_with_revision()?;
3719        if selected_after_clock != selected {
3720            return Err(HnsWalletError::StaleAccountRead);
3721        }
3722        let context = VerifiedHnsBoardCancellationContext {
3723            account_id,
3724            account: selected.account,
3725            account_revision,
3726            account_prefix_lease,
3727            network: shakedex_network_binding(selected_after_clock.account.config.network)?,
3728            observed_at_unix,
3729        };
3730        self.store.try_with_store(|store| {
3731            store.try_with_entity_read_snapshot(|snapshot| {
3732                context.revalidate_unchanged_account(snapshot)
3733            })
3734        })
3735    }
3736
3737    /// Preserve the purpose-specific cancellation API while sharing the full
3738    /// runtime's exact account/network/time fence implementation.
3739    pub fn observe_board_cancellation_context(
3740        &self,
3741    ) -> Result<VerifiedHnsBoardCancellationContext, HnsWalletError> {
3742        self.observe_board_context()
3743    }
3744
3745    pub fn register<'a>(&'a self, registry: &mut ModuleRegistry<'a>) -> Result<(), RegistryError> {
3746        registry.register_utxo_settlement(self)
3747    }
3748
3749    /// Called only after the trusted approval UI has compared the complete
3750    /// prepared artifact. The stored commitment is encrypted and single-use.
3751    pub fn register_send_approval(
3752        &self,
3753        approval_id: ApprovalId,
3754        origin: &str,
3755        prepared: &PreparedSend,
3756        expires_at_unix: u64,
3757    ) -> Result<(), HnsWalletError> {
3758        let now = self.clock.now_unix()?;
3759        let plan: HnsSpendPlan = serde_json::from_slice(prepared.authorization_commitment())
3760            .map_err(|_| HnsWalletError::InvalidPreparedArtifact)?;
3761        if prepared.module != ModuleId::Handshake
3762            || plan.expires_at_unix != prepared.expires_at_unix
3763            || plan.amount != prepared.amount.base_units
3764            || plan.fee != prepared.fee
3765            || plan.destination != prepared.destination
3766            || expires_at_unix > plan.expires_at_unix
3767        {
3768            return Err(HnsWalletError::InvalidPreparedArtifact);
3769        }
3770        let approval = HnsSendApproval {
3771            workflow_id: plan.workflow_id,
3772            commitment: Sha256::digest(prepared.authorization_commitment()).into(),
3773        };
3774        let encoded = Zeroizing::new(serde_json::to_vec(&approval)?);
3775        self.store_lock()?.put_pending_approval(
3776            approval_id,
3777            origin,
3778            &encoded,
3779            now,
3780            expires_at_unix,
3781        )?;
3782        Ok(())
3783    }
3784
3785    pub fn rebroadcast_pending_send(
3786        &self,
3787        workflow_id: WorkflowId,
3788    ) -> Result<BroadcastReceipt, HnsWalletError> {
3789        let account = {
3790            let cache = self.cache_read()?;
3791            if cache.sync.phase != SyncPhase::Ready
3792                || cache.sync.validated_height != cache.sync.scanned_height
3793            {
3794                return Err(HnsWalletError::StaleNodeSnapshot);
3795            }
3796            cache.account.config.clone()
3797        };
3798        let stored = self
3799            .store_lock()?
3800            .load_workflow::<HnsSendWorkflow>(workflow_id)?
3801            .ok_or(HnsWalletError::InvalidWorkflow)?;
3802        if stored.state.plan.wallet_id != account.wallet_id
3803            || stored.state.plan.account_id != account.account_id
3804        {
3805            return Err(HnsWalletError::InvalidWorkflow);
3806        }
3807        if !matches!(
3808            stored.state.stage,
3809            HnsSendStage::Authorized
3810                | HnsSendStage::Broadcast
3811                | HnsSendStage::Mempool
3812                | HnsSendStage::RequiresRebroadcast
3813        ) {
3814            return Err(HnsWalletError::InvalidWorkflow);
3815        }
3816        let raw = stored
3817            .state
3818            .signed_transaction
3819            .clone()
3820            .ok_or(HnsWalletError::InvalidWorkflow)?;
3821        let expected = stored
3822            .state
3823            .transaction
3824            .ok_or(HnsWalletError::InvalidWorkflow)?;
3825        let prior_quote = stored
3826            .state
3827            .fee_quote
3828            .as_ref()
3829            .ok_or(HnsWalletError::InvalidWorkflow)?;
3830        let input_coins = canonical_input_coins(&stored.state.plan.inputs)?;
3831        let signed = validate_signed_payment_plan(&stored.state.plan, &raw)?;
3832        validate_standard_input_authorizations(&signed, &input_coins)?;
3833        validate_final_fee_quote(
3834            &raw,
3835            &input_coins,
3836            prior_quote,
3837            prior_quote.binding,
3838            prior_quote.mempool,
3839            stored.state.plan.fee,
3840            stored.state.plan.maximum_fee,
3841        )?;
3842        let quote = self.quote_final_transaction(
3843            &raw,
3844            &input_coins,
3845            stored.state.plan.fee,
3846            stored.state.plan.maximum_fee,
3847        )?;
3848        let submission_started_at = self.clock.now_unix()?;
3849        let (submission_revision, submission_state) = {
3850            let mut store = self.store_lock()?;
3851            let current = store
3852                .load_workflow::<HnsSendWorkflow>(workflow_id)?
3853                .ok_or(HnsWalletError::InvalidWorkflow)?;
3854            if current.revision != stored.revision || current.state != stored.state {
3855                return Err(HnsWalletError::InvalidWorkflow);
3856            }
3857            let mut state = current.state;
3858            state.stage = HnsSendStage::RequiresRebroadcast;
3859            state.fee_quote = Some(quote);
3860            let revision = store.save_workflow(
3861                workflow_id,
3862                WorkflowKind::HnsSend,
3863                current.revision,
3864                &state,
3865                true,
3866                submission_started_at,
3867            )?;
3868            (revision, state)
3869        };
3870        let actual = self.backend.broadcast_transaction(&raw)?;
3871        if actual != expected {
3872            return Err(HnsWalletError::InvalidEvidence);
3873        }
3874        let accepted_at = self.clock.now_unix()?;
3875        let mut store = self.store_lock()?;
3876        let current = store
3877            .load_workflow::<HnsSendWorkflow>(workflow_id)?
3878            .ok_or(HnsWalletError::InvalidWorkflow)?;
3879        if current.revision != submission_revision || current.state != submission_state {
3880            return Err(HnsWalletError::InvalidWorkflow);
3881        }
3882        let mut state = current.state;
3883        state.stage = HnsSendStage::Broadcast;
3884        store.save_workflow(
3885            workflow_id,
3886            WorkflowKind::HnsSend,
3887            current.revision,
3888            &state,
3889            true,
3890            accepted_at,
3891        )?;
3892        Ok(BroadcastReceipt {
3893            module: ModuleId::Handshake,
3894            txid: actual,
3895            accepted_at_unix: accepted_at,
3896        })
3897    }
3898
3899    /// Re-submit exact, previously approved send bytes that disappeared from
3900    /// the current authenticated chain and mempool view.
3901    ///
3902    /// Direct-peer backends cannot treat a successful socket write as remote
3903    /// mempool admission. Their process-local mempool also intentionally does
3904    /// not survive controller replacement. A fresh persisted-value read can
3905    /// therefore classify a formerly broadcast transaction as dropped even
3906    /// though its encrypted send workflow still contains the exact signed
3907    /// bytes the user approved. The native mobile value runtime deliberately
3908    /// uses [`Self::synchronize_persisted_value_read`] instead of the legacy
3909    /// workflow-mutating reconciliation path, so selection cannot depend on a
3910    /// dropped record having first appeared in the projected activity cache.
3911    /// This bounded recovery path verifies every active durable signed send
3912    /// directly against the exact synchronized chain and mempool bindings,
3913    /// reuses [`Self::rebroadcast_pending_send`] for all fee, transaction, and
3914    /// workflow validation, and never prepares or signs a new payment.
3915    pub fn rebroadcast_dropped_pending_sends(
3916        &self,
3917    ) -> Result<Vec<BroadcastReceipt>, HnsWalletError> {
3918        let (account, binding, mempool_binding) = {
3919            let cache = self.cache_read()?;
3920            if cache.sync.phase != SyncPhase::Ready
3921                || cache.sync.validated_height != cache.sync.scanned_height
3922            {
3923                return Err(HnsWalletError::StaleNodeSnapshot);
3924            }
3925            (
3926                cache.account.config.clone(),
3927                cache.binding.ok_or(HnsWalletError::StaleNodeSnapshot)?,
3928                cache
3929                    .mempool_binding
3930                    .ok_or(HnsWalletError::StaleNodeSnapshot)?,
3931            )
3932        };
3933        let now = self.clock.now_unix()?;
3934        let workflows = self
3935            .store_lock()?
3936            .list_workflows_complete::<HnsSendWorkflow>(
3937                WorkflowKind::HnsSend,
3938                MAX_HISTORY_RESULTS,
3939            )?;
3940        let mut dropped = BTreeSet::new();
3941        let mut candidates = Vec::new();
3942        for stored in workflows {
3943            if stored.state.plan.wallet_id != account.wallet_id
3944                || stored.state.plan.account_id != account.account_id
3945            {
3946                continue;
3947            }
3948            if stored.state.plan.workflow_id != stored.id {
3949                return Err(HnsWalletError::InvalidWorkflow);
3950            }
3951            if !matches!(
3952                stored.state.stage,
3953                HnsSendStage::Authorized
3954                    | HnsSendStage::Broadcast
3955                    | HnsSendStage::Mempool
3956                    | HnsSendStage::RequiresRebroadcast
3957            ) || stored.state.signed_transaction.is_none()
3958            {
3959                continue;
3960            }
3961            let txid = stored
3962                .state
3963                .transaction
3964                .ok_or(HnsWalletError::InvalidWorkflow)?;
3965            let evidence =
3966                self.backend
3967                    .get_transaction_evidence(txid, binding, Some(mempool_binding))?;
3968            if evidence.binding != binding || evidence.mempool != mempool_binding {
3969                return Err(HnsWalletError::StaleNodeSnapshot);
3970            }
3971            let outpoints = stored
3972                .state
3973                .plan
3974                .inputs
3975                .iter()
3976                .map(|input| input.coin.outpoint)
3977                .collect::<Vec<_>>();
3978            let competing_spender =
3979                has_competing_spender_in_batches(&self.backend, &outpoints, binding, txid)?;
3980            let observed_stage = if evidence.status.conflicted || competing_spender {
3981                Some(HnsSendStage::Conflicted)
3982            } else if evidence.status.confirmation_count > 0 {
3983                Some(HnsSendStage::Confirmed)
3984            } else if evidence.status.in_mempool {
3985                Some(HnsSendStage::Mempool)
3986            } else {
3987                None
3988            };
3989            if let Some(observed_stage) = observed_stage {
3990                let mut store = self.store_lock()?;
3991                persist_observed_send_stage(&mut store, &account, &stored, observed_stage, now)?;
3992                continue;
3993            }
3994            if send_is_within_propagation_grace(stored.state.stage, stored.updated_at_unix, now) {
3995                continue;
3996            }
3997            dropped.insert(txid);
3998            candidates.push(stored.id);
3999        }
4000        candidates.sort();
4001
4002        let mut receipts = Vec::with_capacity(candidates.len());
4003        for workflow_id in candidates {
4004            match self.rebroadcast_pending_send(workflow_id) {
4005                Ok(receipt) => receipts.push(receipt),
4006                // Exact approved bytes cannot be fee-bumped. A transaction
4007                // prepared under an older, lower wallet fee policy remains
4008                // visibly dropped. Signed-send reservations do not expire, so
4009                // atomically abandon this obsolete workflow and release only
4010                // its inputs for a newly reviewed replacement.
4011                Err(HnsWalletError::InvalidFeeQuote) => {
4012                    let now = self.clock.now_unix()?;
4013                    let mut store = self.store_lock()?;
4014                    abandon_obsolete_dropped_send(
4015                        &mut store,
4016                        &account,
4017                        workflow_id,
4018                        &dropped,
4019                        now,
4020                    )?;
4021                }
4022                Err(error) => return Err(error),
4023            }
4024        }
4025        Ok(receipts)
4026    }
4027
4028    pub fn import_name(&self, name: &[u8]) -> Result<KnownName, HnsWalletError> {
4029        self.import_names(&[name])?
4030            .pop()
4031            .ok_or(HnsWalletError::InvalidEvidence)
4032    }
4033
4034    /// Authenticate a bounded name set against the current synchronized
4035    /// binding and commit every resulting known-name row atomically.
4036    pub fn import_names(&self, names: &[&[u8]]) -> Result<Vec<KnownName>, HnsWalletError> {
4037        if names.is_empty() || names.len() > MAX_HISTORY_RESULTS {
4038            return Err(HnsWalletError::HistoryLimit);
4039        }
4040        let mut requested_hashes = BTreeSet::new();
4041        for name in names {
4042            if !validate_name(name) {
4043                return Err(HnsWalletError::InvalidName);
4044            }
4045            let name_hash = hash_name(name)
4046                .map_err(|_| HnsWalletError::InvalidName)?
4047                .into_bytes();
4048            if !requested_hashes.insert(name_hash) {
4049                return Err(HnsWalletError::InvalidName);
4050            }
4051        }
4052        let now = self.clock.now_unix()?;
4053        let cache = self.cache_read()?;
4054        let binding = cache.binding.ok_or(HnsWalletError::StaleNodeSnapshot)?;
4055        let config = cache.account.config.clone();
4056        drop(cache);
4057        let wallet_name_addresses = {
4058            let store = self.store_lock()?;
4059            persisted_name_addresses(&store, &config)?
4060        };
4061        let mut imported = Vec::with_capacity(names.len());
4062        for name in names {
4063            imported.push(
4064                validated_name_evidence(
4065                    &self.backend,
4066                    name,
4067                    binding,
4068                    Some(&wallet_name_addresses),
4069                )?
4070                .known_name,
4071            );
4072        }
4073        let mut store = self.store_lock()?;
4074        if self.cache_read()?.binding != Some(binding) {
4075            return Err(HnsWalletError::StaleNodeSnapshot);
4076        }
4077        let existing = store.list_entities_by_id_prefix::<KnownName>(
4078            EntityKind::KnownName,
4079            &account_entity_prefix(&config),
4080            MAX_HISTORY_RESULTS,
4081        )?;
4082        let existing_hashes = existing
4083            .iter()
4084            .map(|stored| stored.value.name_hash)
4085            .collect::<BTreeSet<_>>();
4086        let existing_revisions = existing
4087            .iter()
4088            .map(|stored| (stored.id.as_slice(), stored.revision))
4089            .collect::<BTreeMap<_, _>>();
4090        let novel = imported
4091            .iter()
4092            .filter(|name| !existing_hashes.contains(&name.name_hash))
4093            .count();
4094        if existing
4095            .len()
4096            .checked_add(novel)
4097            .is_none_or(|count| count > MAX_HISTORY_RESULTS)
4098        {
4099            return Err(HnsWalletError::HistoryLimit);
4100        }
4101        let saves = imported
4102            .iter()
4103            .map(|name| {
4104                let id = namespaced_name_id(&config, name.name_hash);
4105                EntityBatchSave {
4106                    id: id.to_vec(),
4107                    expected_revision: existing_revisions
4108                        .get(id.as_slice())
4109                        .copied()
4110                        .unwrap_or_default(),
4111                    value: name.clone(),
4112                    updated_at_unix: now,
4113                }
4114            })
4115            .collect::<Vec<_>>();
4116        store.apply_entity_batch(EntityKind::KnownName, &saves, &[])?;
4117        Ok(imported)
4118    }
4119
4120    /// Return the bounded, account-scoped canonical name cache. Every entry is
4121    /// replaced from fresh node evidence during reconciliation; legacy rows
4122    /// retain their explicit watch-only status until that succeeds.
4123    pub fn list_names(&self) -> Result<Vec<KnownName>, HnsWalletError> {
4124        let config = self.cache_read()?.account.config.clone();
4125        let mut names = self
4126            .store_lock()?
4127            .list_entities_by_id_prefix::<KnownName>(
4128                EntityKind::KnownName,
4129                &account_entity_prefix(&config),
4130                MAX_HISTORY_RESULTS,
4131            )?
4132            .into_iter()
4133            .map(|stored| stored.value)
4134            .collect::<Vec<_>>();
4135        names.sort_by(|left, right| {
4136            left.name
4137                .cmp(&right.name)
4138                .then_with(|| left.name_hash.cmp(&right.name_hash))
4139        });
4140        Ok(names)
4141    }
4142
4143    /// Return the canonical account-zero receive target for name transfers.
4144    pub fn name_receive_target(&self) -> Result<HnsNameReceiveTarget, HnsWalletError> {
4145        let cache = self.cache_read()?;
4146        ensure_ready(&cache).map_err(|_| HnsWalletError::StaleNodeSnapshot)?;
4147        let account = cache.account.clone();
4148        drop(cache);
4149        let store = self.store_lock()?;
4150        let payment = hns_payment_receive_target(&store, &account)?;
4151        hns_name_receive_target_from_payment(&payment)
4152    }
4153
4154    pub fn get_name(&self, name_hash: [u8; 32]) -> Result<Option<KnownName>, HnsWalletError> {
4155        let config = self.cache_read()?.account.config.clone();
4156        Ok(self
4157            .store_lock()?
4158            .known_name::<KnownName>(&namespaced_name_id(&config, name_hash))?
4159            .map(|stored| stored.value))
4160    }
4161
4162    /// Allocate one immutable seller key from the separated Shakedex role.
4163    /// This atomically changes protected encrypted key metadata and the
4164    /// account's restoration projection; it does not enable a value path,
4165    /// create a listing, reserve funds, sign, or broadcast.
4166    pub fn allocate_shakedex_key(
4167        &self,
4168        request: &HnsShakedexKeyAllocationRequest,
4169    ) -> Result<HnsShakedexKeyAllocation, HnsShakedexKeyAllocationError> {
4170        let config = self
4171            .cache_read()
4172            .map_err(HnsShakedexKeyAllocationError::Wallet)?
4173            .account
4174            .config
4175            .clone();
4176        let now_unix = self
4177            .clock
4178            .now_unix()
4179            .map_err(HnsShakedexKeyAllocationError::Wallet)?;
4180        let mut store = self
4181            .store_lock()
4182            .map_err(HnsShakedexKeyAllocationError::Wallet)?;
4183        let committed =
4184            shakedex_key::allocate_hns_shakedex_key(&mut store, &config, request, now_unix)?;
4185        drop(store);
4186        self.install_loaded_account(committed.account)
4187            .map_err(HnsShakedexKeyAllocationError::Wallet)?;
4188        Ok(committed.allocation)
4189    }
4190
4191    /// Re-authenticate an immutable public Shakedex key binding after restart.
4192    pub fn load_shakedex_key_allocation(
4193        &self,
4194        workflow_id: WorkflowId,
4195    ) -> Result<Option<HnsShakedexKeyAllocation>, HnsShakedexKeyAllocationError> {
4196        let wallet_id = self
4197            .cache_read()
4198            .map_err(HnsShakedexKeyAllocationError::Wallet)?
4199            .account
4200            .config
4201            .wallet_id;
4202        let store = self
4203            .store_lock()
4204            .map_err(HnsShakedexKeyAllocationError::Wallet)?;
4205        shakedex_key::load_hns_shakedex_key_allocation(&store, wallet_id, workflow_id)
4206    }
4207
4208    /// Encode the exact version-zero 32-byte script destination committed by
4209    /// an authenticated seller allocation. This is the only address a product
4210    /// should pass to the ordinary name TRANSFER workflow for that offer.
4211    pub fn shakedex_lock_address(
4212        &self,
4213        allocation: &HnsShakedexKeyAllocation,
4214    ) -> Result<String, HnsShakedexKeyAllocationError> {
4215        {
4216            let cache = self
4217                .cache_read()
4218                .map_err(HnsShakedexKeyAllocationError::Wallet)?;
4219            shakedex_funding::ensure_shakedex_funding_ready(&cache)
4220                .map_err(HnsShakedexKeyAllocationError::Wallet)?;
4221            if cache.account.config.wallet_id != allocation.wallet_id()
4222                || cache.account.config.account_id != allocation.account_id()
4223                || cache.account.config.account_derivation_index
4224                    != allocation.account_derivation_index()
4225                || cache.account.config.network != allocation.network()
4226            {
4227                return Err(HnsShakedexKeyAllocationError::BindingConflict);
4228            }
4229        }
4230        let current = self
4231            .load_shakedex_key_allocation(allocation.workflow_id())?
4232            .ok_or(HnsShakedexKeyAllocationError::AllocationNotFound)?;
4233        if current != *allocation {
4234            return Err(HnsShakedexKeyAllocationError::BindingConflict);
4235        }
4236        encode_v0_address(allocation.network(), allocation.lock_script_hash())
4237            .map_err(HnsShakedexKeyAllocationError::Wallet)
4238    }
4239
4240    /// Project a canonical public address from authenticated Shakedex terms
4241    /// onto the selected Handshake network. This exposes only the ordinary
4242    /// bech32 display string; it does not expose a derivation, key, coin, or
4243    /// signing capability.
4244    pub fn shakedex_address_display(&self, address: &Address) -> Result<String, HnsWalletError> {
4245        address
4246            .validate()
4247            .map_err(|_| HnsWalletError::InvalidAddress)?;
4248        let network = self.cache_read()?.account.config.network;
4249        name_workflow::encode_hns_address(
4250            network,
4251            &WalletAddressKey {
4252                version: address.version,
4253                hash: address.hash.clone(),
4254            },
4255        )
4256    }
4257
4258    /// Re-derive a purpose-bound, redacted seller signer after authenticating
4259    /// the complete protected allocation topology and recovery-seed binding.
4260    pub fn load_shakedex_signer(
4261        &self,
4262        request: &HnsShakedexKeyAllocationRequest,
4263    ) -> Result<HnsShakedexSigner, HnsShakedexKeyAllocationError> {
4264        let config = self
4265            .cache_read()
4266            .map_err(HnsShakedexKeyAllocationError::Wallet)?
4267            .account
4268            .config
4269            .clone();
4270        let store = self
4271            .store_lock()
4272            .map_err(HnsShakedexKeyAllocationError::Wallet)?;
4273        shakedex_key::load_hns_shakedex_signer(&store, &config, request)
4274    }
4275
4276    /// Bind a protected seller allocation to the exact current, unspent
4277    /// Shakedex lock and snapshot-authoritative parent median time.
4278    pub fn verify_allocated_current_shakedex_lock(
4279        &self,
4280        request: &HnsShakedexKeyAllocationRequest,
4281    ) -> Result<VerifiedCurrentShakedexLock, HnsShakedexKeyAllocationError> {
4282        let allocation = self
4283            .load_shakedex_key_allocation(request.workflow_id)?
4284            .ok_or(HnsShakedexKeyAllocationError::AllocationNotFound)?;
4285        if allocation.name() != request.name
4286            || allocation.terms_commitment() != request.terms_commitment()?
4287        {
4288            return Err(HnsShakedexKeyAllocationError::BindingConflict);
4289        }
4290        let signer = self.load_shakedex_signer(request)?;
4291        self.verify_current_shakedex_lock(request.name.as_slice(), *signer.compressed_public_key())
4292            .map_err(HnsShakedexKeyAllocationError::Wallet)
4293    }
4294
4295    /// Reacquire ephemeral action authority from the exact current snapshot.
4296    /// Cached `KnownName` ownership is never accepted as authorization.
4297    pub fn verify_name_ownership(
4298        &self,
4299        name: &[u8],
4300    ) -> Result<VerifiedNameOwnership, HnsWalletError> {
4301        let cache = self.cache_read()?;
4302        let binding = cache.binding.ok_or(HnsWalletError::StaleNodeSnapshot)?;
4303        let mempool = cache
4304            .mempool_binding
4305            .ok_or(HnsWalletError::StaleNodeSnapshot)?;
4306        let config = cache.account.config.clone();
4307        drop(cache);
4308        let wallet_name_addresses = {
4309            let store = self.store_lock()?;
4310            persisted_name_addresses(&store, &config)?
4311        };
4312        let validated =
4313            validated_name_evidence(&self.backend, name, binding, Some(&wallet_name_addresses))?;
4314        let cache = self.cache_read()?;
4315        if cache.binding != Some(binding) || cache.mempool_binding != Some(mempool) {
4316            return Err(HnsWalletError::StaleNodeSnapshot);
4317        }
4318        let current = validated.current.ok_or(HnsWalletError::NameNotOwned)?;
4319        if !current.state.registered
4320            || current.state.revoked.get() != 0
4321            || current.state.transfer.get() != 0
4322        {
4323            return Err(HnsWalletError::NameNotOwned);
4324        }
4325        let derivation = match validated.known_name.ownership_status {
4326            NameOwnershipStatus::WalletOwned { derivation } => derivation,
4327            _ => return Err(HnsWalletError::NameNotOwned),
4328        };
4329        let owner = current.owner.ok_or(HnsWalletError::NameNotOwned)?;
4330        Ok(VerifiedNameOwnership {
4331            binding,
4332            mempool,
4333            name: validated.known_name.name,
4334            name_hash: validated.known_name.name_hash,
4335            current_state: validated
4336                .known_name
4337                .current_state
4338                .ok_or(HnsWalletError::InvalidEvidence)?,
4339            owner_outpoint: owner.outpoint,
4340            owner_transaction: owner.raw_transaction,
4341            owner_output: owner.output,
4342            owner_inclusion: owner.inclusion,
4343            derivation,
4344        })
4345    }
4346
4347    pub fn cancel_prepared_send(&self, workflow_id: WorkflowId) -> Result<(), HnsWalletError> {
4348        let now = self.clock.now_unix()?;
4349        let config = self.cache_read()?.account.config.clone();
4350        let mut store = self.store_lock()?;
4351        let stored = store
4352            .load_workflow::<HnsSendWorkflow>(workflow_id)?
4353            .ok_or(HnsWalletError::InvalidWorkflow)?;
4354        if stored.state.plan.wallet_id != config.wallet_id
4355            || stored.state.plan.account_id != config.account_id
4356            || stored.state.stage != HnsSendStage::Prepared
4357        {
4358            return Err(HnsWalletError::InvalidWorkflow);
4359        }
4360        let mut state = stored.state;
4361        state.stage = HnsSendStage::Cancelled;
4362        let deletes = reservation_deletes(&store, &config, workflow_id)?;
4363        store.save_workflow_with_entity_batch::<_, HnsInputReservation>(
4364            workflow_id,
4365            WorkflowKind::HnsSend,
4366            stored.revision,
4367            &state,
4368            false,
4369            now,
4370            EntityKind::InputReservation,
4371            &[],
4372            &deletes,
4373        )?;
4374        Ok(())
4375    }
4376
4377    /// Release the exact prepared send created by a trusted native caller.
4378    /// The caller has already bound this random nonce to one local approval;
4379    /// the runtime derives the workflow under its own wallet/account identity.
4380    pub fn cancel_prepared_send_by_request_nonce(
4381        &self,
4382        request_nonce: u64,
4383    ) -> Result<(), HnsWalletError> {
4384        if request_nonce == 0 {
4385            return Err(HnsWalletError::InvalidWorkflow);
4386        }
4387        let config = self.cache_read()?.account.config.clone();
4388        self.cancel_prepared_send(send_workflow_id(&config, request_nonce))
4389    }
4390
4391    pub fn cancel_prepared_settlement(
4392        &self,
4393        artifact: &PreparedArtifact,
4394    ) -> Result<(), HnsWalletError> {
4395        if artifact.module != ModuleId::Handshake {
4396            return Err(HnsWalletError::InvalidPreparedArtifact);
4397        }
4398        let prepared: HnsPreparedSettlement = serde_json::from_slice(artifact.commitment_bytes())?;
4399        if prepared.stage != HnsSettlementStage::Prepared
4400            || prepared.session_id != artifact.session_id
4401            || prepared.approved_fee()? != artifact.fee
4402            || prepared.expires_at_unix != artifact.expires_at_unix
4403        {
4404            return Err(HnsWalletError::InvalidPreparedArtifact);
4405        }
4406        let now = self.clock.now_unix()?;
4407        let config = self.cache_read()?.account.config.clone();
4408        let kind = settlement_workflow_kind(prepared.action);
4409        let mut store = self.store_lock()?;
4410        let mut stored = store
4411            .load_workflow::<HnsPreparedSettlement>(prepared.workflow_id)?
4412            .ok_or(HnsWalletError::InvalidWorkflow)?;
4413        if stored.kind != kind
4414            || stored.state.stage != HnsSettlementStage::Prepared
4415            || !same_prepared_settlement(&stored.state, &prepared)
4416        {
4417            return Err(HnsWalletError::InvalidWorkflow);
4418        }
4419        stored.state.stage = HnsSettlementStage::Cancelled;
4420        let deletes = reservation_deletes(&store, &config, stored.id)?;
4421        store.save_workflow_with_entity_batch::<_, HnsInputReservation>(
4422            stored.id,
4423            kind,
4424            stored.revision,
4425            &stored.state,
4426            false,
4427            now,
4428            EntityKind::InputReservation,
4429            &[],
4430            &deletes,
4431        )?;
4432        Ok(())
4433    }
4434
4435    /// Return only the exact transaction identifier committed by a prepared
4436    /// settlement artifact, after re-authenticating its closed persisted
4437    /// payload. This supports native review without exposing transaction bytes.
4438    pub fn prepared_settlement_transaction_id(
4439        &self,
4440        artifact: &PreparedArtifact,
4441    ) -> Result<TransactionHash, HnsWalletError> {
4442        if artifact.module != ModuleId::Handshake {
4443            return Err(HnsWalletError::InvalidPreparedArtifact);
4444        }
4445        let prepared: HnsPreparedSettlement = serde_json::from_slice(artifact.commitment_bytes())?;
4446        if prepared.stage != HnsSettlementStage::Prepared
4447            || prepared.session_id != artifact.session_id
4448            || prepared.approved_fee()? != artifact.fee
4449            || prepared.expires_at_unix != artifact.expires_at_unix
4450        {
4451            return Err(HnsWalletError::InvalidPreparedArtifact);
4452        }
4453        Ok(prepared.transaction)
4454    }
4455
4456    /// Return authenticated complete input/output accounting for native
4457    /// settlement review. This intentionally does not expose transaction
4458    /// bytes, scripts, outpoints, or derivations across the service boundary.
4459    pub fn prepared_settlement_value_summary(
4460        &self,
4461        artifact: &PreparedArtifact,
4462    ) -> Result<HnsPreparedSettlementValueSummary, HnsWalletError> {
4463        if artifact.module != ModuleId::Handshake {
4464            return Err(HnsWalletError::InvalidPreparedArtifact);
4465        }
4466        let prepared: HnsPreparedSettlement = serde_json::from_slice(artifact.commitment_bytes())?;
4467        if prepared.stage != HnsSettlementStage::Prepared
4468            || prepared.session_id != artifact.session_id
4469            || prepared.approved_fee()? != artifact.fee
4470            || prepared.expires_at_unix != artifact.expires_at_unix
4471        {
4472            return Err(HnsWalletError::InvalidPreparedArtifact);
4473        }
4474        let authenticated = Self::prepared_settlement_artifact(&prepared)?;
4475        if authenticated.module != artifact.module
4476            || authenticated.session_id != artifact.session_id
4477            || authenticated.fee != artifact.fee
4478            || authenticated.expires_at_unix != artifact.expires_at_unix
4479            || authenticated.commitment_bytes() != artifact.commitment_bytes()
4480        {
4481            return Err(HnsWalletError::InvalidPreparedArtifact);
4482        }
4483        let transaction = Transaction::decode(&prepared.signed_transaction)
4484            .map_err(|_| HnsWalletError::InvalidPreparedArtifact)?;
4485        let input_coins = prepared.canonical_input_coins()?;
4486        if transaction.inputs.len() != input_coins.len() || input_coins.is_empty() {
4487            return Err(HnsWalletError::InvalidPreparedArtifact);
4488        }
4489        let total_input = input_coins.iter().try_fold(0_u128, |total, coin| {
4490            total
4491                .checked_add(u128::from(coin.value.get()))
4492                .ok_or(HnsWalletError::Arithmetic)
4493        })?;
4494        let total_output = transaction
4495            .outputs
4496            .iter()
4497            .try_fold(0_u128, |total, output| {
4498                total
4499                    .checked_add(u128::from(output.value.get()))
4500                    .ok_or(HnsWalletError::Arithmetic)
4501            })?;
4502        if total_input < total_output || total_input - total_output != prepared.fee.get() {
4503            return Err(HnsWalletError::InvalidPreparedArtifact);
4504        }
4505        let settlement_input = match &prepared.terms {
4506            HnsSettlementTerms::Redeem { lock } | HnsSettlementTerms::Refund { lock } => {
4507                if lock.amount.asset != WalletAsset::Hns {
4508                    return Err(HnsWalletError::InvalidPreparedArtifact);
4509                }
4510                lock.amount.base_units
4511            }
4512            HnsSettlementTerms::Lock { .. } => {
4513                return Err(HnsWalletError::InvalidPreparedArtifact);
4514            }
4515        };
4516        if input_coins[0].value.get()
4517            != u64::try_from(settlement_input.get())
4518                .map_err(|_| HnsWalletError::InvalidPreparedArtifact)?
4519            || total_input < settlement_input.get()
4520        {
4521            return Err(HnsWalletError::InvalidPreparedArtifact);
4522        }
4523        Ok(HnsPreparedSettlementValueSummary {
4524            total_input: BaseUnits::new(total_input),
4525            total_output: BaseUnits::new(total_output),
4526            settlement_input,
4527            wallet_sponsor_input: BaseUnits::new(total_input - settlement_input.get()),
4528        })
4529    }
4530
4531    pub fn settlement_key_target(
4532        &self,
4533        session_id: SessionId,
4534        refund: bool,
4535    ) -> Result<String, HnsWalletError> {
4536        let account = self.cache_read()?.account.clone();
4537        let store = self.store_lock()?;
4538        derive_settlement_public_key(&store, &account, session_id, refund).map(hex::encode)
4539    }
4540
4541    pub fn broadcast_prepared_settlement(
4542        &self,
4543        artifact: &PreparedArtifact,
4544    ) -> Result<BroadcastReceipt, HnsWalletError> {
4545        self.broadcast_prepared_settlement_inner(artifact, None)
4546    }
4547
4548    /// Submit a still-reversible prepared settlement only before an external
4549    /// short-lived authority expires. The deadline is re-read at the same
4550    /// mutex-protected checkpoint that marks the exact signed transaction
4551    /// recoverably broadcastable; it does not disable later recovery after
4552    /// that checkpoint has already been crossed.
4553    pub fn broadcast_prepared_settlement_before(
4554        &self,
4555        artifact: &PreparedArtifact,
4556        not_after_unix: u64,
4557    ) -> Result<BroadcastReceipt, HnsWalletError> {
4558        if not_after_unix == 0 {
4559            return Err(HnsWalletError::InvalidPreparedArtifact);
4560        }
4561        self.broadcast_prepared_settlement_inner(artifact, Some(not_after_unix))
4562    }
4563
4564    fn broadcast_prepared_settlement_inner(
4565        &self,
4566        artifact: &PreparedArtifact,
4567        not_after_unix: Option<u64>,
4568    ) -> Result<BroadcastReceipt, HnsWalletError> {
4569        if artifact.module != ModuleId::Handshake {
4570            return Err(HnsWalletError::InvalidPreparedArtifact);
4571        }
4572        let prepared: HnsPreparedSettlement = serde_json::from_slice(artifact.commitment_bytes())?;
4573        if prepared.session_id != artifact.session_id
4574            || prepared.stage != HnsSettlementStage::Prepared
4575            || prepared.approved_fee()? != artifact.fee
4576            || prepared.maximum_fee.is_zero()
4577            || prepared.fee > prepared.maximum_fee
4578            || prepared.expires_at_unix != artifact.expires_at_unix
4579        {
4580            return Err(HnsWalletError::InvalidPreparedArtifact);
4581        }
4582        let artifact_quote = prepared
4583            .fee_quote
4584            .as_ref()
4585            .ok_or(HnsWalletError::InvalidPreparedArtifact)?;
4586        let artifact_input_coins = prepared.canonical_input_coins()?;
4587        validate_final_fee_quote(
4588            &prepared.signed_transaction,
4589            &artifact_input_coins,
4590            artifact_quote,
4591            artifact_quote.binding,
4592            artifact_quote.mempool,
4593            prepared.fee,
4594            prepared.maximum_fee,
4595        )?;
4596        let transaction =
4597            decode_transaction_for_id(&prepared.signed_transaction, prepared.transaction)?;
4598        let transaction_id = wallet_transaction_hash(&transaction)?;
4599        if transaction_id != prepared.transaction {
4600            return Err(HnsWalletError::InvalidPreparedArtifact);
4601        }
4602        let now = self.clock.now_unix()?;
4603        let config = self.cache_read()?.account.config.clone();
4604        if prepared.wallet_id != config.wallet_id || prepared.account_id != config.account_id {
4605            return Err(HnsWalletError::InvalidPreparedArtifact);
4606        }
4607        let kind = settlement_workflow_kind(prepared.action);
4608        let stored = {
4609            let mut store = self.store_lock()?;
4610            let mut stored = store
4611                .load_workflow::<HnsPreparedSettlement>(prepared.workflow_id)?
4612                .ok_or(HnsWalletError::InvalidWorkflow)?;
4613            if stored.kind != kind || !same_prepared_settlement(&stored.state, &prepared) {
4614                return Err(HnsWalletError::InvalidWorkflow);
4615            }
4616            if stored.state.stage == HnsSettlementStage::Confirmed {
4617                return Ok(BroadcastReceipt {
4618                    module: ModuleId::Handshake,
4619                    txid: stored.state.transaction,
4620                    accepted_at_unix: now,
4621                });
4622            }
4623            let activation_expires_at = not_after_unix
4624                .map_or(stored.state.expires_at_unix, |deadline| {
4625                    deadline.min(stored.state.expires_at_unix)
4626                });
4627            if stored.state.stage == HnsSettlementStage::Prepared && now >= activation_expires_at {
4628                stored.state.stage = HnsSettlementStage::Expired;
4629                let deletes = reservation_deletes(&store, &config, stored.id)?;
4630                store.save_workflow_with_entity_batch::<_, HnsInputReservation>(
4631                    stored.id,
4632                    kind,
4633                    stored.revision,
4634                    &stored.state,
4635                    false,
4636                    now,
4637                    EntityKind::InputReservation,
4638                    &[],
4639                    &deletes,
4640                )?;
4641                return Err(HnsWalletError::PreparedArtifactExpired);
4642            }
4643            if !matches!(
4644                stored.state.stage,
4645                HnsSettlementStage::Prepared
4646                    | HnsSettlementStage::Broadcast
4647                    | HnsSettlementStage::Mempool
4648                    | HnsSettlementStage::RequiresRebroadcast
4649            ) {
4650                return Err(HnsWalletError::InvalidWorkflow);
4651            }
4652            // A recovery package can reach RequiresRebroadcast after only an
4653            // ancestor submission failed. That checkpoint does not authorize
4654            // more network work once the separately persisted fresh funding
4655            // deadline has elapsed: the contract transaction was never
4656            // attempted, so expire locally before retransmitting even one
4657            // public ancestor.
4658            if stored
4659                .state
4660                .recovery_publication
4661                .as_ref()
4662                .is_some_and(|package| package.final_submission_started_at_unix.is_none())
4663                && now >= recovery_funding_submission_limit(&stored.state)
4664            {
4665                stored.state.stage = HnsSettlementStage::Expired;
4666                let deletes = reservation_deletes(&store, &config, stored.id)?;
4667                store.save_workflow_with_entity_batch::<_, HnsInputReservation>(
4668                    stored.id,
4669                    kind,
4670                    stored.revision,
4671                    &stored.state,
4672                    false,
4673                    now,
4674                    EntityKind::InputReservation,
4675                    &[],
4676                    &deletes,
4677                )?;
4678                return Err(HnsWalletError::PreparedArtifactExpired);
4679            }
4680            let prior_quote = stored
4681                .state
4682                .fee_quote
4683                .as_ref()
4684                .ok_or(HnsWalletError::InvalidWorkflow)?;
4685            let input_coins = stored.state.canonical_input_coins()?;
4686            validate_final_fee_quote(
4687                &stored.state.signed_transaction,
4688                &input_coins,
4689                prior_quote,
4690                prior_quote.binding,
4691                prior_quote.mempool,
4692                stored.state.fee,
4693                stored.state.maximum_fee,
4694            )?;
4695            stored
4696        };
4697        let input_coins = stored.state.canonical_input_coins()?;
4698        let quote = self.quote_final_transaction(
4699            &stored.state.signed_transaction,
4700            &input_coins,
4701            stored.state.fee,
4702            stored.state.maximum_fee,
4703        )?;
4704        let (mut submission_revision, mut submission_state) = {
4705            let mut store = self.store_lock()?;
4706            // Read time after acquiring the same mutex that protects the
4707            // guarded transaction. A lease which expires while waiting for
4708            // this lock must not cross the irreversible checkpoint.
4709            let submission_started_at = self.clock.now_unix()?;
4710            let current = store
4711                .load_workflow::<HnsPreparedSettlement>(stored.id)?
4712                .ok_or(HnsWalletError::InvalidWorkflow)?;
4713            if current.revision != stored.revision || current.state != stored.state {
4714                return Err(HnsWalletError::InvalidWorkflow);
4715            }
4716            let activate = current.state.stage == HnsSettlementStage::Prepared;
4717            let activation_expires_at = not_after_unix
4718                .map_or(current.state.expires_at_unix, |deadline| {
4719                    deadline.min(current.state.expires_at_unix)
4720                });
4721            if activate && submission_started_at >= activation_expires_at {
4722                let mut expired = current.state;
4723                expired.stage = HnsSettlementStage::Expired;
4724                let deletes = reservation_deletes(&store, &config, current.id)?;
4725                store.save_workflow_with_entity_batch::<_, HnsInputReservation>(
4726                    current.id,
4727                    kind,
4728                    current.revision,
4729                    &expired,
4730                    false,
4731                    submission_started_at,
4732                    EntityKind::InputReservation,
4733                    &[],
4734                    &deletes,
4735                )?;
4736                return Err(HnsWalletError::PreparedArtifactExpired);
4737            }
4738            let activation_saves = if activate {
4739                reservation_activation_saves(&store, &config, current.id, submission_started_at)?
4740            } else {
4741                Vec::new()
4742            };
4743            let mut state = current.state;
4744            if state.recovery_publication.is_some() {
4745                let limit = recovery_funding_submission_limit(&state);
4746                let limit = not_after_unix.map_or(limit, |deadline| deadline.min(limit));
4747                state
4748                    .recovery_publication
4749                    .as_mut()
4750                    .ok_or(HnsWalletError::InvalidWorkflow)?
4751                    .funding_submission_before_unix = Some(limit);
4752            }
4753            state.stage = HnsSettlementStage::RequiresRebroadcast;
4754            state.fee_quote = Some(quote);
4755            if activate
4756                && state.broadcast_guard.as_ref().is_some_and(|guard| {
4757                    !guard.authorizes_action(
4758                        state.action,
4759                        state.session_id,
4760                        Some(submission_started_at),
4761                    )
4762                })
4763            {
4764                return Err(HnsWalletError::InvalidWorkflow);
4765            }
4766            let revision = match (activate, state.broadcast_guard.as_ref()) {
4767                (true, Some(guard)) => store.save_workflow_with_entity_batch_and_guards(
4768                    current.id,
4769                    kind,
4770                    current.revision,
4771                    &state,
4772                    true,
4773                    submission_started_at,
4774                    EntityKind::InputReservation,
4775                    &activation_saves,
4776                    &[],
4777                    WorkflowRevisionAssertion {
4778                        id: guard.execution_workflow_id,
4779                        kind: WorkflowKind::AtomicSwap,
4780                        expected_revision: guard.execution_revision,
4781                    },
4782                    guard.entity_kind(),
4783                    &EntityRevisionAssertion {
4784                        id: guard.entity_id.clone(),
4785                        expected_revision: guard.entity_revision,
4786                    },
4787                    guard.consumes_entity(),
4788                )?,
4789                _ => store.save_workflow_with_entity_batch(
4790                    current.id,
4791                    kind,
4792                    current.revision,
4793                    &state,
4794                    true,
4795                    submission_started_at,
4796                    EntityKind::InputReservation,
4797                    &activation_saves,
4798                    &[],
4799                )?,
4800            };
4801            (revision, state)
4802        };
4803        if let Some(package) = &stored.state.recovery_publication {
4804            recovery_publication::validate_prepared_publication(&stored.state)?;
4805            for ancestor in &package.ancestors {
4806                let tx = Transaction::decode(&ancestor.raw)
4807                    .map_err(|_| HnsWalletError::InvalidPreparedArtifact)?;
4808                let coins = recovery_publication::canonical_package_inputs(&ancestor.inputs)?;
4809                self.quote_final_transaction(&ancestor.raw, &coins, ancestor.fee, ancestor.fee)?;
4810                if self.backend.broadcast_transaction(&ancestor.raw)?
4811                    != wallet_transaction_hash(&tx)?
4812                {
4813                    return Err(HnsWalletError::InvalidEvidence);
4814                }
4815            }
4816        }
4817        if stored.state.recovery_publication.is_some() {
4818            let mut store = self.store_lock()?;
4819            let now = self.clock.now_unix()?;
4820            let current = store
4821                .load_workflow::<HnsPreparedSettlement>(stored.id)?
4822                .ok_or(HnsWalletError::InvalidWorkflow)?;
4823            if current.revision != submission_revision || current.state != submission_state {
4824                return Err(HnsWalletError::InvalidWorkflow);
4825            }
4826            let limit = recovery_funding_submission_limit(&current.state);
4827            if now >= limit {
4828                let mut state = current.state;
4829                if state
4830                    .recovery_publication
4831                    .as_ref()
4832                    .is_some_and(|package| package.final_submission_started_at_unix.is_none())
4833                {
4834                    state.stage = HnsSettlementStage::Expired;
4835                    let deletes = reservation_deletes(&store, &config, current.id)?;
4836                    store.save_workflow_with_entity_batch::<_, HnsInputReservation>(
4837                        current.id,
4838                        kind,
4839                        current.revision,
4840                        &state,
4841                        false,
4842                        now,
4843                        EntityKind::InputReservation,
4844                        &[],
4845                        &deletes,
4846                    )?;
4847                }
4848                return Err(HnsWalletError::PreparedArtifactExpired);
4849            }
4850            let mut state = current.state;
4851            let package = state
4852                .recovery_publication
4853                .as_mut()
4854                .ok_or(HnsWalletError::InvalidWorkflow)?;
4855            if package.final_submission_started_at_unix.is_none() {
4856                package.final_submission_started_at_unix = Some(now);
4857                submission_revision =
4858                    store.save_workflow(current.id, kind, current.revision, &state, true, now)?;
4859                submission_state = state;
4860            }
4861        }
4862        let accepted = self
4863            .backend
4864            .broadcast_transaction(&stored.state.signed_transaction)?;
4865        if accepted != stored.state.transaction {
4866            return Err(HnsWalletError::InvalidEvidence);
4867        }
4868        let accepted_at = self.clock.now_unix()?;
4869        let mut store = self.store_lock()?;
4870        let current = store
4871            .load_workflow::<HnsPreparedSettlement>(stored.id)?
4872            .ok_or(HnsWalletError::InvalidWorkflow)?;
4873        if current.revision != submission_revision || current.state != submission_state {
4874            return Err(HnsWalletError::InvalidWorkflow);
4875        }
4876        let mut state = current.state;
4877        state.stage = HnsSettlementStage::Broadcast;
4878        store.save_workflow(stored.id, kind, current.revision, &state, true, accepted_at)?;
4879        Ok(BroadcastReceipt {
4880            module: ModuleId::Handshake,
4881            txid: accepted,
4882            accepted_at_unix: accepted_at,
4883        })
4884    }
4885
4886    /// Resume exact HNS settlements that reached the durable submission
4887    /// checkpoint but were not observed in the mempool or chain. The original
4888    /// signed bytes and fee cap remain recoverable after the reversible
4889    /// prepared-artifact review window has elapsed.
4890    pub fn rebroadcast_pending_settlements(&self) -> Result<usize, HnsWalletError> {
4891        let now = self.clock.now_unix()?;
4892        let config = self.cache_read()?.account.config.clone();
4893        let candidates = {
4894            let store = self.store_lock()?;
4895            let mut candidates = Vec::new();
4896            for kind in [WorkflowKind::AtomicSwap, WorkflowKind::Refund] {
4897                for stored in list_hns_prepared_settlement_workflows(&store, kind)? {
4898                    if stored.state.wallet_id == config.wallet_id
4899                        && stored.state.account_id == config.account_id
4900                        && stored.state.stage == HnsSettlementStage::RequiresRebroadcast
4901                        && now.saturating_sub(stored.updated_at_unix)
4902                            >= SEND_PROPAGATION_GRACE_SECONDS
4903                    {
4904                        candidates.push(stored.state);
4905                    }
4906                }
4907            }
4908            candidates
4909        };
4910        let mut submitted = 0_usize;
4911        for mut prepared in candidates {
4912            prepared.stage = HnsSettlementStage::Prepared;
4913            let artifact = PreparedArtifact::new(
4914                ModuleId::Handshake,
4915                prepared.session_id,
4916                prepared.approved_fee()?,
4917                prepared.expires_at_unix,
4918                serde_json::to_vec(&prepared)?,
4919            )
4920            .map_err(|_| HnsWalletError::InvalidPreparedArtifact)?;
4921            match self.broadcast_prepared_settlement(&artifact) {
4922                Ok(_) => {}
4923                Err(HnsWalletError::PreparedArtifactExpired) => continue,
4924                Err(error) => return Err(error),
4925            }
4926            submitted = submitted
4927                .checked_add(1)
4928                .ok_or(HnsWalletError::HistoryLimit)?;
4929        }
4930        Ok(submitted)
4931    }
4932
4933    // These values comprise the complete atomic settlement snapshot and stay
4934    // explicit to keep the persistence boundary straightforward to audit.
4935    #[allow(clippy::too_many_arguments)]
4936    fn persist_prepared_settlement(
4937        &self,
4938        session_id: SessionId,
4939        action: HnsSettlementAction,
4940        signed_transaction: Vec<u8>,
4941        input_coins: Vec<HnsInputCoinEvidence>,
4942        fee: BaseUnits,
4943        maximum_fee: BaseUnits,
4944        fee_quote: HnsTransactionFeeQuote,
4945        terms: HnsSettlementTerms,
4946        recovery_publication: Option<recovery_publication::HnsRecoveryPackage>,
4947        broadcast_guard: Option<HnsSettlementBroadcastGuard>,
4948        reservation_saves: &[EntityBatchSave<HnsInputReservation>],
4949        account_save: Option<&EntityBatchSave<HnsAccountRecord>>,
4950        now_unix: u64,
4951    ) -> Result<PreparedArtifact, HnsWalletError> {
4952        let account = self.cache_read()?.account.clone();
4953        let transaction = Transaction::decode(&signed_transaction)
4954            .map_err(|_| HnsWalletError::InvalidPreparedArtifact)?;
4955        let transaction = wallet_transaction_hash(&transaction)?;
4956        let canonical_input_coins = if recovery_publication.is_some() {
4957            recovery_publication::canonical_package_inputs(&input_coins)?
4958        } else {
4959            canonical_evidence_coins(&input_coins)?
4960        };
4961        validate_final_fee_quote(
4962            &signed_transaction,
4963            &canonical_input_coins,
4964            &fee_quote,
4965            fee_quote.binding,
4966            fee_quote.mempool,
4967            fee,
4968            maximum_fee,
4969        )?;
4970        let workflow_id = settlement_workflow_id(&account.config, session_id, action);
4971        if broadcast_guard
4972            .as_ref()
4973            .is_some_and(|guard| !guard.authorizes_action(action, session_id, Some(now_unix)))
4974        {
4975            return Err(HnsWalletError::InvalidPreparedArtifact);
4976        }
4977        let expires_at_unix = now_unix
4978            .checked_add(PREPARED_ARTIFACT_LIFETIME_SECONDS)
4979            .ok_or(HnsWalletError::Arithmetic)?;
4980        let prepared = HnsPreparedSettlement {
4981            wallet_id: account.config.wallet_id,
4982            account_id: account.config.account_id,
4983            workflow_id,
4984            session_id,
4985            action,
4986            stage: HnsSettlementStage::Prepared,
4987            transaction,
4988            signed_transaction,
4989            input_coins,
4990            fee,
4991            maximum_fee,
4992            fee_quote: Some(fee_quote),
4993            expires_at_unix,
4994            terms,
4995            recovery_publication,
4996            broadcast_guard,
4997        };
4998        let kind = settlement_workflow_kind(action);
4999        let artifact = Self::prepared_settlement_artifact(&prepared)?;
5000        let mut store = self.store_lock()?;
5001        let expected_workflow_revision =
5002            match store.load_workflow::<HnsPreparedSettlement>(workflow_id)? {
5003                Some(stored) if stored.state == prepared && stored.kind == kind => {
5004                    return Ok(artifact);
5005                }
5006                Some(stored)
5007                    if stored.kind == kind
5008                        && stored.state.wallet_id == prepared.wallet_id
5009                        && stored.state.account_id == prepared.account_id
5010                        && stored.state.workflow_id == prepared.workflow_id
5011                        && stored.state.session_id == prepared.session_id
5012                        && stored.state.action == prepared.action
5013                        && settlement_terms_are_retry_compatible(
5014                            &stored.state.terms,
5015                            &prepared.terms,
5016                        )
5017                        && ((matches!(
5018                            stored.state.stage,
5019                            HnsSettlementStage::Expired | HnsSettlementStage::Cancelled
5020                        ) && !stored.irreversible_broadcast_prepared)
5021                            || (stored.state.stage == HnsSettlementStage::Prepared
5022                                && stored.state.expires_at_unix <= now_unix)) =>
5023                {
5024                    if account_input_reservations(&store, &account.config)?
5025                        .into_iter()
5026                        .any(|reservation| reservation.value.workflow_id == workflow_id)
5027                    {
5028                        return Err(HnsWalletError::InvalidWorkflow);
5029                    }
5030                    stored.revision
5031                }
5032                Some(_) => return Err(HnsWalletError::InvalidWorkflow),
5033                None => 0,
5034            };
5035        if let Some(account_save) = account_save {
5036            let (_, next_account_revision) = store.save_workflow_with_account_and_entity_batch(
5037                workflow_id,
5038                kind,
5039                expected_workflow_revision,
5040                &prepared,
5041                false,
5042                now_unix,
5043                account_save,
5044                EntityKind::InputReservation,
5045                reservation_saves,
5046                &[],
5047            )?;
5048            drop(store);
5049            self.install_committed_account(
5050                account_save.expected_revision,
5051                next_account_revision,
5052                account_save.value.clone(),
5053                now_unix,
5054            )?;
5055        } else {
5056            store.save_workflow_with_entity_batch(
5057                workflow_id,
5058                kind,
5059                expected_workflow_revision,
5060                &prepared,
5061                false,
5062                now_unix,
5063                EntityKind::InputReservation,
5064                reservation_saves,
5065                &[],
5066            )?;
5067        }
5068        Ok(artifact)
5069    }
5070
5071    #[allow(clippy::too_many_arguments)]
5072    fn prepare_settlement_spend(
5073        &self,
5074        session_id: SessionId,
5075        lock: VerifiedLock,
5076        preimage: Option<Preimage>,
5077        maximum_fee: BaseUnits,
5078        current_height: Option<u64>,
5079        action: HnsSettlementAction,
5080        external_signer: Option<&dyn SettlementSigner>,
5081        broadcast_guard: Option<HnsSettlementBroadcastGuard>,
5082    ) -> Result<PreparedArtifact, ChainError> {
5083        if lock.module != ModuleId::Handshake
5084            || lock.session_id != session_id
5085            || maximum_fee.is_zero()
5086        {
5087            return Err(ChainError::InvalidRequest(
5088                "invalid Handshake settlement spend",
5089            ));
5090        }
5091        let now = self.clock.now_unix().map_err(map_chain_error)?;
5092        let cache = self.cache_read().map_err(map_chain_error)?;
5093        ensure_settlement_ready(&cache)?;
5094        if action == HnsSettlementAction::Refund {
5095            let current = current_height.ok_or(ChainError::InvalidRequest(
5096                "current Handshake refund authority is required",
5097            ))?;
5098            let locally_validated_current = if hns_locktime_is_time(lock.absolute_timelock)? {
5099                cache
5100                    .binding
5101                    .ok_or(ChainError::NotSynchronized)?
5102                    .tip
5103                    .median_time_past
5104            } else {
5105                cache.sync.validated_height
5106            };
5107            if current != locally_validated_current
5108                || !hns_refund_locktime_mature(lock.absolute_timelock, locally_validated_current)?
5109            {
5110                return Err(ChainError::InvalidRequest(
5111                    "refund locktime is not current or mature",
5112                ));
5113            }
5114        }
5115        let account = cache.account.clone();
5116        let coins = cache.coins.clone();
5117        drop(cache);
5118        let config = account.config.clone();
5119        let workflow_id = settlement_workflow_id(&config, session_id, action);
5120        let mut store = self.store_lock().map_err(map_chain_error)?;
5121        let record = store
5122            .hns_verified_settlement::<HnsVerifiedSettlementRecord>(&settlement_entity_id(
5123                &config, session_id,
5124            ))
5125            .map_err(map_chain_error)?
5126            .ok_or(ChainError::InvalidEvidenceContext(
5127                "verified HNS lock lookup",
5128            ))?
5129            .value;
5130        let lock = refreshed_verified_settlement_lock(&record.verified, &lock)?;
5131        let terms = match action {
5132            HnsSettlementAction::Redeem => HnsSettlementTerms::Redeem { lock: lock.clone() },
5133            HnsSettlementAction::Refund => HnsSettlementTerms::Refund { lock: lock.clone() },
5134            HnsSettlementAction::Lock => {
5135                return Err(ChainError::InvalidRequest(
5136                    "invalid settlement spend action",
5137                ));
5138            }
5139        };
5140        if let Some(mut stored) = store
5141            .load_workflow::<HnsPreparedSettlement>(workflow_id)
5142            .map_err(map_chain_error)?
5143        {
5144            if stored.kind != settlement_workflow_kind(action)
5145                || stored.state.wallet_id != config.wallet_id
5146                || stored.state.account_id != config.account_id
5147                || stored.state.workflow_id != workflow_id
5148                || stored.state.session_id != session_id
5149                || stored.state.action != action
5150                || !settlement_terms_are_retry_compatible(&stored.state.terms, &terms)
5151            {
5152                return Err(ChainError::InvalidRequest(
5153                    "persisted Handshake settlement spend does not match retry",
5154                ));
5155            }
5156            let guard_changed = stored.state.broadcast_guard != broadcast_guard;
5157            let active_retry = stored.state.stage == HnsSettlementStage::Prepared
5158                && stored.state.expires_at_unix > now
5159                && !guard_changed;
5160            if !active_retry {
5161                let replaceable = (stored.state.stage == HnsSettlementStage::Prepared
5162                    && (stored.state.expires_at_unix <= now || guard_changed))
5163                    || (matches!(
5164                        stored.state.stage,
5165                        HnsSettlementStage::Expired | HnsSettlementStage::Cancelled
5166                    ) && !stored.irreversible_broadcast_prepared);
5167                if !replaceable {
5168                    return Err(ChainError::InvalidRequest(
5169                        "persisted Handshake settlement spend does not match retry",
5170                    ));
5171                }
5172                if stored.state.stage == HnsSettlementStage::Prepared {
5173                    stored.state.stage = if stored.state.expires_at_unix <= now {
5174                        HnsSettlementStage::Expired
5175                    } else {
5176                        HnsSettlementStage::Cancelled
5177                    };
5178                    let deletes = reservation_deletes(&store, &config, workflow_id)
5179                        .map_err(map_chain_error)?;
5180                    store
5181                        .save_workflow_with_entity_batch::<_, HnsInputReservation>(
5182                            workflow_id,
5183                            stored.kind,
5184                            stored.revision,
5185                            &stored.state,
5186                            false,
5187                            now,
5188                            EntityKind::InputReservation,
5189                            &[],
5190                            &deletes,
5191                        )
5192                        .map_err(map_chain_error)?;
5193                } else {
5194                    release_reservations(&mut store, &config, workflow_id)
5195                        .map_err(map_chain_error)?;
5196                }
5197            } else {
5198                if stored.state.maximum_fee != maximum_fee || stored.state.fee > maximum_fee {
5199                    return Err(ChainError::InvalidRequest(
5200                        "persisted Handshake settlement spend does not match retry",
5201                    ));
5202                }
5203                let quote = stored
5204                    .state
5205                    .fee_quote
5206                    .as_ref()
5207                    .ok_or(ChainError::InvalidEvidence)?;
5208                let input_coins = stored
5209                    .state
5210                    .canonical_input_coins()
5211                    .map_err(map_chain_error)?;
5212                validate_final_fee_quote(
5213                    &stored.state.signed_transaction,
5214                    &input_coins,
5215                    quote,
5216                    quote.binding,
5217                    quote.mempool,
5218                    stored.state.fee,
5219                    stored.state.maximum_fee,
5220                )
5221                .map_err(map_chain_error)?;
5222                let transaction = Transaction::decode(&stored.state.signed_transaction)
5223                    .map_err(|_| ChainError::InvalidEvidence)?;
5224                if transaction.inputs.is_empty() || transaction.inputs.len() != input_coins.len() {
5225                    return Err(ChainError::InvalidEvidence);
5226                }
5227                let sponsor_outpoints = transaction
5228                    .inputs
5229                    .iter()
5230                    .skip(1)
5231                    .map(|input| HnsOutpoint {
5232                        transaction: TransactionHash::new(
5233                            input.previous_output.transaction_hash.into_bytes(),
5234                        ),
5235                        output_index: input.previous_output.index,
5236                    })
5237                    .collect::<Vec<_>>();
5238                if sponsor_outpoints.is_empty() {
5239                    if account_input_reservations(&store, &config)
5240                        .map_err(map_chain_error)?
5241                        .into_iter()
5242                        .any(|reservation| reservation.value.workflow_id == workflow_id)
5243                    {
5244                        return Err(ChainError::InvalidEvidence);
5245                    }
5246                } else {
5247                    validate_prepared_reservations(
5248                        &store,
5249                        &config,
5250                        workflow_id,
5251                        &sponsor_outpoints,
5252                        stored.state.expires_at_unix,
5253                    )
5254                    .map_err(map_chain_error)?;
5255                }
5256                let artifact =
5257                    Self::prepared_settlement_artifact(&stored.state).map_err(map_chain_error)?;
5258                let committed_account = store
5259                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))
5260                    .map_err(map_chain_error)?
5261                    .ok_or(ChainError::InvalidEvidence)?;
5262                drop(store);
5263                self.install_loaded_account(committed_account)
5264                    .map_err(map_chain_error)?;
5265                return Ok(artifact);
5266            }
5267        }
5268        let refund = action == HnsSettlementAction::Refund;
5269        let public = external_signer.map_or_else(
5270            || {
5271                derive_settlement_public_key(&store, &account, session_id, refund).map_err(
5272                    |error| {
5273                        evidence_error_context(
5274                            map_chain_error(error),
5275                            "HNS settlement public-key derivation",
5276                        )
5277                    },
5278                )
5279            },
5280            |signer| Ok(signer.compressed_public_key()),
5281        )?;
5282        let expected_key = if refund {
5283            decode_compressed_key(&record.expected.refund_target)?
5284        } else {
5285            decode_compressed_key(&record.expected.receiver)?
5286        };
5287        if public != expected_key {
5288            return Err(ChainError::InvalidRequest(
5289                "settlement target is not controlled by this wallet",
5290            ));
5291        }
5292        let change_derivation = DerivationReference {
5293            role: KeyRole::HnsCoin,
5294            account: account_number(&account),
5295            change: 1,
5296            index: account.next_change_index,
5297        };
5298        let change_public = derive_hns_account_public_key(&store, &account, change_derivation)
5299            .map_err(|error| {
5300                evidence_error_context(
5301                    map_chain_error(error),
5302                    "HNS settlement change-key derivation",
5303                )
5304            })?;
5305        let destination = Address::new(
5306            0,
5307            public_key_hash(&change_public)
5308                .map_err(|error| {
5309                    evidence_error_context(
5310                        map_chain_error(error),
5311                        "HNS settlement change-address hashing",
5312                    )
5313                })?
5314                .to_vec(),
5315        )
5316        .map_err(|_| {
5317            ChainError::InvalidEvidenceContext("HNS settlement change-address construction")
5318        })?;
5319        let previous_value = u64::try_from(lock.amount.base_units.get()).map_err(|_| {
5320            ChainError::InvalidEvidenceContext("HNS settlement lock-value conversion")
5321        })?;
5322        let funding_coin =
5323            record
5324                .funding_coin
5325                .clone()
5326                .ok_or(ChainError::InvalidEvidenceContext(
5327                    "verified HNS funding coin lookup",
5328                ))?;
5329        let canonical_funding_coin = funding_coin.to_canonical_coin().map_err(|error| {
5330            evidence_error_context(map_chain_error(error), "verified HNS funding coin decoding")
5331        })?;
5332        if canonical_funding_coin.outpoint.transaction_hash.as_bytes() != lock.funding_id.as_bytes()
5333            || canonical_funding_coin.outpoint.index != record.output_index
5334            || canonical_funding_coin.value.get() != previous_value
5335            || canonical_funding_coin.coinbase
5336            || canonical_funding_coin.address.version != 0
5337            || canonical_funding_coin.address.hash != Sha3_256::digest(&record.script).to_vec()
5338            || canonical_funding_coin.covenant != Covenant::default()
5339        {
5340            return Err(ChainError::InvalidEvidenceContext(
5341                "verified HNS funding coin binding",
5342            ));
5343        }
5344        let sequence = if refund { u32::MAX - 1 } else { u32::MAX };
5345        let locktime = if refund {
5346            u32::try_from(lock.absolute_timelock).map_err(|_| ChainError::InvalidEvidence)?
5347        } else {
5348            0
5349        };
5350        let mut sponsor_candidates = available_unreserved_coins(&mut store, &config, coins, now)
5351            .map_err(|error| {
5352                evidence_error_context(map_chain_error(error), "HNS settlement sponsor selection")
5353            })?;
5354        sponsor_candidates.retain(|coin| {
5355            is_confirmed_ordinary_hns_spend_candidate(coin)
5356                && coin.coin.outpoint != funding_coin.outpoint
5357        });
5358        sponsor_candidates.sort_by(|left, right| {
5359            right
5360                .coin
5361                .value
5362                .cmp(&left.coin.value)
5363                .then_with(|| left.coin.outpoint.cmp(&right.coin.outpoint))
5364        });
5365        let fee_rate = self.backend.estimate_fee_rate(6).map_err(map_chain_error)?;
5366        let mut sponsors = Vec::new();
5367        let (transaction, input_coins, fee) = loop {
5368            let transaction = unsigned_sponsored_htlc_spend(
5369                &lock,
5370                record.output_index,
5371                &record.script,
5372                previous_value,
5373                &sponsors,
5374                destination.clone(),
5375                sequence,
5376                locktime,
5377                refund,
5378            )
5379            .map_err(|error| {
5380                evidence_error_context(
5381                    map_chain_error(error),
5382                    "HNS settlement transaction construction",
5383                )
5384            })?;
5385            let mut input_coins = Vec::with_capacity(1 + sponsors.len());
5386            input_coins.push(canonical_funding_coin.clone());
5387            if !sponsors.is_empty() {
5388                input_coins.extend(canonical_input_coins(&sponsors).map_err(|error| {
5389                    evidence_error_context(
5390                        map_chain_error(error),
5391                        "HNS settlement sponsor-coin encoding",
5392                    )
5393                })?);
5394            }
5395            let fee = canonical_policy_minimum_fee(&transaction, &input_coins, fee_rate).map_err(
5396                |error| {
5397                    evidence_error_context(
5398                        map_chain_error(error),
5399                        "HNS settlement local fee policy",
5400                    )
5401                },
5402            )?;
5403            if fee > maximum_fee {
5404                return Err(ChainError::FeeLimit);
5405            }
5406            let input_total = input_coins.iter().try_fold(0_u128, |total, coin| {
5407                total
5408                    .checked_add(u128::from(coin.value.get()))
5409                    .ok_or(ChainError::Overflow)
5410            })?;
5411            if input_total >= fee.get() && input_total - fee.get() >= config.dust_threshold.get() {
5412                let output_value =
5413                    u64::try_from(input_total - fee.get()).map_err(|_| ChainError::Overflow)?;
5414                let mut transaction = transaction;
5415                transaction.outputs[0].value = Dollarydoos::new(output_value);
5416                break (transaction, input_coins, fee);
5417            }
5418            let next = sponsor_candidates
5419                .get(sponsors.len())
5420                .cloned()
5421                .ok_or_else(|| map_chain_error(HnsWalletError::InsufficientFunds))?;
5422            sponsors.push(next);
5423        };
5424        let unsigned_transaction = transaction.clone();
5425        let transaction = if sponsors.is_empty() {
5426            transaction
5427        } else {
5428            let expected_roles = ordinary_hns_input_roles(&sponsors).map_err(map_chain_error)?;
5429            let signed = sign_ordered_p2pkh_inputs_from(
5430                &store,
5431                &account,
5432                transaction,
5433                1,
5434                &sponsors,
5435                &expected_roles,
5436            )
5437            .map_err(|error| {
5438                evidence_error_context(
5439                    map_chain_error(error),
5440                    "HNS settlement sponsor authorization",
5441                )
5442            })?;
5443            Transaction::decode(&signed).map_err(|_| {
5444                ChainError::InvalidEvidenceContext("HNS settlement sponsor transaction decoding")
5445            })?
5446        };
5447        let signed = match external_signer {
5448            Some(signer) => sign_htlc_spend_with_settlement_signer(
5449                transaction,
5450                &record.script,
5451                previous_value,
5452                preimage.as_ref(),
5453                refund,
5454                signer,
5455            ),
5456            None => sign_htlc_spend(
5457                &store,
5458                &account,
5459                transaction,
5460                session_id,
5461                &record.script,
5462                previous_value,
5463                preimage.as_ref(),
5464                refund,
5465            ),
5466        }
5467        .map_err(|error| {
5468            evidence_error_context(map_chain_error(error), "HNS settlement HTLC authorization")
5469        })?;
5470        let signed_transaction = validate_witness_only_change(&unsigned_transaction, &signed)
5471            .map_err(|error| {
5472                evidence_error_context(
5473                    map_chain_error(error),
5474                    "HNS settlement signed-transaction structure",
5475                )
5476            })?;
5477        validate_standard_input_authorizations(&signed_transaction, &input_coins).map_err(
5478            |error| {
5479                evidence_error_context(map_chain_error(error), "HNS settlement input authorization")
5480            },
5481        )?;
5482        let expires_at_unix = now
5483            .checked_add(PREPARED_ARTIFACT_LIFETIME_SECONDS)
5484            .ok_or(ChainError::Overflow)?;
5485        let reservation_saves =
5486            reservation_saves(&config, workflow_id, &sponsors, expires_at_unix, now).map_err(
5487                |error| {
5488                    evidence_error_context(
5489                        map_chain_error(error),
5490                        "HNS settlement sponsor reservation",
5491                    )
5492                },
5493            )?;
5494        let policy_input_evidence =
5495            settlement_input_evidence(funding_coin, &sponsors).map_err(|error| {
5496                evidence_error_context(
5497                    map_chain_error(error),
5498                    "HNS settlement input evidence encoding",
5499                )
5500            })?;
5501        drop(store);
5502        let quote = self
5503            .quote_final_transaction(&signed, &input_coins, fee, maximum_fee)
5504            .map_err(|error| {
5505                evidence_error_context(map_chain_error(error), "HNS settlement fee quote")
5506            })?;
5507        let cache = self.cache_read().map_err(map_chain_error)?;
5508        // Fee quoting may perform one bounded reconciliation when the newly
5509        // confirmed HTLC input was not present in the quote snapshot. That
5510        // reconciliation is allowed to advance the durable account revision
5511        // without changing the account itself. Rebase the change-address
5512        // reservation onto that authoritative revision, just as the native
5513        // HTLC lock path does, while still rejecting any actual account
5514        // mutation that would make this prepared transaction stale.
5515        let account_revision = authoritative_unchanged_account_revision(
5516            &account,
5517            &cache.account,
5518            cache.account_revision,
5519        )
5520        .map_err(|error| evidence_error_context(error, "HNS settlement account-revision rebase"))?;
5521        drop(cache);
5522        let account_save =
5523            Self::change_account_save(&account, account_revision, change_derivation.index, now)
5524                .map_err(|error| {
5525                    evidence_error_context(
5526                        map_chain_error(error),
5527                        "HNS settlement change-index reservation",
5528                    )
5529                })?;
5530        self.persist_prepared_settlement(
5531            session_id,
5532            action,
5533            signed,
5534            policy_input_evidence,
5535            fee,
5536            maximum_fee,
5537            quote,
5538            terms,
5539            None,
5540            broadcast_guard,
5541            &reservation_saves,
5542            Some(&account_save),
5543            now,
5544        )
5545        .map_err(map_chain_error)
5546    }
5547
5548    pub fn reconcile(&self) -> Result<HnsReconciliationReport, HnsWalletError> {
5549        let now = self.clock.now_unix()?;
5550        self.set_sync_phase(SyncPhase::Headers, None)?;
5551        let tip = self.backend.get_chain_tip()?;
5552        let (cached_account, cached_account_revision) = {
5553            let cache = self.cache_read()?;
5554            (cache.account.clone(), cache.account_revision)
5555        };
5556        let mut store = self.store_lock()?;
5557        let stored_account = store
5558            .wallet_account::<HnsAccountRecord>(&account_entity_id(&cached_account.config))?
5559            .ok_or(HnsWalletError::InvalidEvidence)?;
5560        validate_authoritative_reconcile_account(
5561            &cached_account,
5562            cached_account_revision,
5563            &stored_account.value,
5564            stored_account.revision,
5565        )?;
5566        let stored_account_revision = stored_account.revision;
5567        let account = stored_account.value;
5568        let stored_recovery: Option<StoredEntity<HnsRecoveryState>> =
5569            store.hns_recovery_state(&recovery_entity_id(&account.config))?;
5570        let (mut recovery, recovery_revision) = stored_recovery
5571            .map_or((HnsRecoveryState::default(), 0), |stored| {
5572                (stored.value, stored.revision)
5573            });
5574        self.set_sync_phase(SyncPhase::WalletScan, None)?;
5575        let (
5576            account,
5577            account_revision,
5578            binding,
5579            mempool_binding,
5580            addresses,
5581            history,
5582            indexed_coins,
5583        ) = self.restore_scan(&mut store, account, stored_account_revision, tip, now)?;
5584        let common_ancestor = self.find_common_ancestor(&recovery, binding)?;
5585        let reorg_detected = recovery.last_tip.is_some()
5586            && common_ancestor
5587                != recovery
5588                    .last_tip
5589                    .map(|old_tip| old_tip.height.min(tip.height));
5590        let coins = reconcile_coins(indexed_coins, &addresses, binding.tip.height)?;
5591        let mut transactions = self.reconcile_transactions(
5592            &history,
5593            &addresses,
5594            binding,
5595            mempool_binding,
5596            common_ancestor,
5597        )?;
5598        let revalidated_names = self.revalidate_names(&mut store, binding, now)?;
5599        let mut pending_user_actions =
5600            self.reconcile_name_workflows(&mut store, binding, mempool_binding, now)?;
5601        pending_user_actions.extend(self.reconcile_send_workflows(
5602            &mut store,
5603            binding,
5604            mempool_binding,
5605            now,
5606        )?);
5607        self.retain_or_insert_pending_wallet_activity(&store, &mut transactions)?;
5608        persist_reconciled_entities(&mut store, &account.config, &coins, &transactions, now)?;
5609        pending_user_actions.extend(self.reconcile_settlement_workflows(
5610            &mut store,
5611            binding,
5612            mempool_binding,
5613            now,
5614        )?);
5615        pending_user_actions.sort();
5616        pending_user_actions.dedup();
5617        self.cleanup_input_reservations(
5618            &mut store,
5619            &account.config,
5620            &coins,
5621            binding,
5622            mempool_binding,
5623            now,
5624        )?;
5625
5626        recovery.checkpoints = self.refresh_checkpoints(binding)?;
5627        recovery.last_tip = Some(tip);
5628        recovery.last_common_ancestor = common_ancestor;
5629        recovery.last_reconciled_unix = now;
5630        store.save_hns_recovery_state(
5631            &recovery_entity_id(&account.config),
5632            recovery_revision,
5633            &recovery,
5634            now,
5635        )?;
5636
5637        {
5638            let mut cache = self.cache_write()?;
5639            validate_authoritative_reconcile_account(
5640                &cache.account,
5641                cache.account_revision,
5642                &account,
5643                account_revision,
5644            )?;
5645            cache.account = account;
5646            cache.account_revision = account_revision;
5647            cache.sync = SyncStatus {
5648                phase: SyncPhase::Ready,
5649                validated_height: tip.height,
5650                scanned_height: tip.height,
5651                target_height: Some(tip.height),
5652                last_error: None,
5653            };
5654            cache.coins = coins.clone();
5655            cache.transactions = transactions.clone();
5656            cache.binding = Some(binding);
5657            cache.mempool_binding = Some(mempool_binding);
5658        }
5659        drop(store);
5660        Ok(HnsReconciliationReport {
5661            tip,
5662            common_ancestor,
5663            reorg_detected,
5664            restored_utxos: coins.len(),
5665            reconciled_transactions: transactions.len(),
5666            revalidated_names,
5667            pending_user_actions,
5668        })
5669    }
5670
5671    /// Reconcile the exact persisted value account into a read-only snapshot.
5672    ///
5673    /// The full legacy reconciliation path above still owns workflow state for
5674    /// signing and settlement.  Native balance exposure, however, only needs a
5675    /// bounded authenticated account projection.  Keeping that projection on
5676    /// the same lock discipline as [`HnsAccountReadRuntime`] is essential for
5677    /// direct-peer wallets: an [`EmbeddedHnsBackend`] consults its encrypted
5678    /// light index during page reads, and that index shares this wallet store.
5679    /// Holding a `SharedWalletStoreGuard` while invoking the backend would make
5680    /// the thread wait on its own non-reentrant store mutex forever.
5681    ///
5682    /// This method therefore fences and stages local state under short store
5683    /// closures, performs every backend query after the closure has returned,
5684    /// then commits the complete projection only after re-authenticating the
5685    /// exact account/entity revisions.  It supports only an existing value
5686    /// account and exposes no signing or workflow capability.
5687    pub fn synchronize_persisted_value_read(
5688        &self,
5689    ) -> Result<HnsAccountReadSnapshot, HnsWalletError> {
5690        let now = self.clock.now_unix()?;
5691        self.set_sync_phase(SyncPhase::Headers, None)?;
5692
5693        let selected = {
5694            let cache = self.cache_read()?;
5695            cache.account.clone()
5696        };
5697        let preparation = self
5698            .store
5699            .with_store_mut(|store| {
5700                Ok(prepare_hns_account_read(
5701                    store,
5702                    &selected,
5703                    HnsAccountReadMode::PersistedRecoveryReadOnly,
5704                    now,
5705                ))
5706            })
5707            .map_err(map_shared_store_error)??;
5708
5709        // `prepare_hns_account_read` durably records a crash-safe discovery
5710        // fence before any direct-peer request. Keep the full runtime cache at
5711        // that exact fence immediately: a temporary read failure must leave a
5712        // retryable unlocked session rather than a stale in-memory revision
5713        // that can only be repaired by reopening the wallet.
5714        {
5715            let mut cache = self.cache_write()?;
5716            validate_authoritative_reconcile_account(
5717                &cache.account,
5718                cache.account_revision,
5719                &preparation.fenced_account,
5720                preparation.account_revision,
5721            )?;
5722            cache.account = preparation.fenced_account.clone();
5723            cache.account_revision = preparation.account_revision;
5724        }
5725
5726        let binding = annotate_persisted_value_read_unavailable(
5727            "obtaining the direct chain snapshot",
5728            self.backend.get_chain_snapshot(),
5729        )?;
5730        annotate_persisted_value_read_unavailable(
5731            "verifying the direct chain identity",
5732            verify_hns_read_chain_identity(
5733                &self.backend,
5734                preparation.fenced_account.config.network,
5735                binding,
5736            ),
5737        )?;
5738        self.set_sync_phase(SyncPhase::WalletScan, None)?;
5739        let scan = annotate_persisted_value_read_unavailable(
5740            "reading the direct wallet index",
5741            scan_hns_account_read(&self.backend, &self.store, &preparation, binding),
5742        )?;
5743        let common_ancestor = annotate_persisted_value_read_unavailable(
5744            "checking the wallet recovery checkpoints",
5745            hns_read_common_ancestor(
5746                &self.backend,
5747                &preparation.recovery,
5748                scan.binding,
5749                preparation.fenced_account.config.birthday_height,
5750            ),
5751        )?;
5752        let mut previous_transactions = preparation
5753            .transactions
5754            .iter()
5755            .map(|stored| stored.value.clone())
5756            .collect::<Vec<_>>();
5757        // Durable locally submitted sends and name actions may not yet be in
5758        // the restored script history. Seed them before reconciliation so the
5759        // exact synchronized mempool evidence can classify them immediately.
5760        self.store.try_with_store(|store| {
5761            retain_or_insert_pending_wallet_activity_for_config(
5762                store,
5763                &scan.account.config,
5764                &mut previous_transactions,
5765            )
5766        })?;
5767        let mut transactions = annotate_persisted_value_read_unavailable(
5768            "reconciling the direct wallet history",
5769            reconcile_hns_read_transactions(
5770                &self.backend,
5771                &scan.history,
5772                &scan.addresses,
5773                scan.binding,
5774                scan.mempool,
5775                common_ancestor,
5776                &previous_transactions,
5777            ),
5778        )?;
5779        let coins = annotate_persisted_value_read_unavailable(
5780            "reconciling direct wallet coins",
5781            reconcile_coins(scan.indexed_coins, &scan.addresses, scan.binding.tip.height),
5782        )?;
5783        let names = annotate_persisted_value_read_unavailable(
5784            "reconciling wallet-owned names",
5785            reconcile_hns_read_names(
5786                &self.backend,
5787                &preparation.names,
5788                &scan.addresses,
5789                &coins,
5790                scan.binding,
5791            ),
5792        )?;
5793        let reserved = self.store.try_with_store(|store| {
5794            active_input_reservation_outpoints(store, &scan.account.config, now)
5795        })?;
5796        self.store.try_with_store(|store| {
5797            retain_or_insert_pending_wallet_activity_for_config(
5798                store,
5799                &scan.account.config,
5800                &mut transactions,
5801            )
5802        })?;
5803        let balance = coins.iter().try_fold(BaseUnits::ZERO, |total, coin| {
5804            if is_confirmed_ordinary_hns_spend_candidate(coin)
5805                && !reserved.contains(&coin.coin.outpoint)
5806            {
5807                total
5808                    .checked_add(coin.coin.value)
5809                    .map_err(|_| HnsWalletError::Arithmetic)
5810            } else {
5811                Ok(total)
5812            }
5813        })?;
5814        let receive_target = hns_read_receive_target(&scan.account, &scan.addresses)?;
5815        let name_receive_target = hns_read_name_receive_target(&scan.account, &scan.addresses)?;
5816        let recovery = HnsRecoveryState {
5817            checkpoints: annotate_persisted_value_read_unavailable(
5818                "recording direct chain checkpoints",
5819                hns_read_checkpoints(
5820                    &self.backend,
5821                    scan.binding,
5822                    scan.account.config.birthday_height,
5823                ),
5824            )?,
5825            last_tip: Some(scan.binding.tip),
5826            last_common_ancestor: common_ancestor,
5827            last_reconciled_unix: now,
5828        };
5829        annotate_persisted_value_read_unavailable(
5830            "revalidating the direct wallet snapshot",
5831            verify_hns_read_snapshot_current(
5832                &self.backend,
5833                &scan.branch_scripts,
5834                scan.binding,
5835                scan.mempool,
5836            ),
5837        )?;
5838        self.store
5839            .with_store_mut(|store| {
5840                Ok(commit_hns_account_read(
5841                    store,
5842                    &preparation,
5843                    &scan.account,
5844                    &scan.addresses,
5845                    &coins,
5846                    &transactions,
5847                    &names,
5848                    &recovery,
5849                    now,
5850                ))
5851            })
5852            .map_err(map_shared_store_error)??;
5853        let persisted_account = self.store.try_with_store(|store| {
5854            store
5855                .wallet_account::<HnsAccountRecord>(&account_entity_id(&scan.account.config))?
5856                .ok_or(HnsWalletError::StaleAccountRead)
5857        })?;
5858        if persisted_account.value != scan.account {
5859            return Err(HnsWalletError::StaleAccountRead);
5860        }
5861
5862        {
5863            let mut cache = self.cache_write()?;
5864            validate_authoritative_reconcile_account(
5865                &cache.account,
5866                cache.account_revision,
5867                &persisted_account.value,
5868                persisted_account.revision,
5869            )?;
5870            cache.account = persisted_account.value;
5871            cache.account_revision = persisted_account.revision;
5872            cache.sync = SyncStatus {
5873                phase: SyncPhase::Ready,
5874                validated_height: scan.binding.tip.height,
5875                scanned_height: scan.binding.tip.height,
5876                target_height: Some(scan.binding.tip.height),
5877                last_error: None,
5878            };
5879            cache.coins = coins;
5880            cache.transactions = transactions.clone();
5881            cache.binding = Some(scan.binding);
5882            cache.mempool_binding = Some(scan.mempool);
5883        }
5884
5885        Ok(HnsAccountReadSnapshot {
5886            account_id: scan.account.config.account_id,
5887            binding: HnsAccountReadBinding {
5888                chain: scan.binding,
5889                mempool: scan.mempool,
5890            },
5891            balance: Amount {
5892                asset: WalletAsset::Hns,
5893                base_units: balance,
5894            },
5895            transactions: transactions
5896                .into_iter()
5897                .map(|transaction| transaction.summary)
5898                .collect(),
5899            receive_target,
5900            name_receive_target,
5901            known_names: names,
5902        })
5903    }
5904
5905    fn find_common_ancestor(
5906        &self,
5907        recovery: &HnsRecoveryState,
5908        binding: SnapshotBinding,
5909    ) -> Result<Option<u64>, HnsWalletError> {
5910        let tip = binding.tip;
5911        if recovery.last_tip.is_none() {
5912            return Ok(None);
5913        }
5914        for checkpoint in recovery.checkpoints.iter().rev() {
5915            if checkpoint.height > tip.height {
5916                continue;
5917            }
5918            let evidence = self.backend.get_block_hash(checkpoint.height, binding)?;
5919            if evidence.binding != binding || evidence.height != checkpoint.height {
5920                return Err(HnsWalletError::StaleNodeSnapshot);
5921            }
5922            if evidence.block_hash == Some(checkpoint.block_hash) {
5923                return Ok(Some(checkpoint.height));
5924            }
5925        }
5926        Ok(account_birthday_ancestor(
5927            self.cache_read()?.account.config.birthday_height,
5928        ))
5929    }
5930
5931    fn refresh_checkpoints(
5932        &self,
5933        binding: SnapshotBinding,
5934    ) -> Result<Vec<HnsChainCheckpoint>, HnsWalletError> {
5935        let tip = binding.tip;
5936        let birthday = self.cache_read()?.account.config.birthday_height;
5937        let start = tip
5938            .height
5939            .saturating_sub((MAX_RECOVERY_CHECKPOINTS - 1) as u64)
5940            .max(birthday);
5941        let mut checkpoints = Vec::new();
5942        for height in start..=tip.height {
5943            let block_hash = if height == tip.height {
5944                Some(tip.block_hash)
5945            } else {
5946                let evidence = self.backend.get_block_hash(height, binding)?;
5947                if evidence.binding != binding || evidence.height != height {
5948                    return Err(HnsWalletError::StaleNodeSnapshot);
5949                }
5950                evidence.block_hash
5951            };
5952            let block_hash = block_hash.ok_or(HnsWalletError::InvalidEvidence)?;
5953            checkpoints.push(HnsChainCheckpoint { height, block_hash });
5954        }
5955        Ok(checkpoints)
5956    }
5957
5958    fn set_sync_phase(
5959        &self,
5960        phase: SyncPhase,
5961        last_error: Option<String>,
5962    ) -> Result<(), HnsWalletError> {
5963        let mut cache = self.cache_write()?;
5964        cache.sync.phase = phase;
5965        cache.sync.last_error = last_error;
5966        Ok(())
5967    }
5968
5969    fn change_account_save(
5970        account: &HnsAccountRecord,
5971        account_revision: u64,
5972        used_index: u32,
5973        now_unix: u64,
5974    ) -> Result<EntityBatchSave<HnsAccountRecord>, HnsWalletError> {
5975        if account.next_change_index != used_index {
5976            return Err(HnsWalletError::StaleAddressReservation);
5977        }
5978        let next = used_index
5979            .checked_add(1)
5980            .ok_or(HnsWalletError::ScanCapacityExhausted)?;
5981        ensure_trailing_gap(Some(used_index), account.config.restore_lookahead)?;
5982        let mut next_account = account.clone();
5983        next_account.next_change_index = next;
5984        next_account.internal_scan_end = next_account.internal_scan_end.max(required_scan_end(
5985            Some(used_index),
5986            next_account.internal_scan_end,
5987            next_account.config.restore_lookahead,
5988        ));
5989        Ok(EntityBatchSave {
5990            id: account_entity_id(&next_account.config).to_vec(),
5991            expected_revision: account_revision,
5992            value: next_account,
5993            updated_at_unix: now_unix,
5994        })
5995    }
5996
5997    fn install_committed_account(
5998        &self,
5999        expected_revision: u64,
6000        next_revision: u64,
6001        next_account: HnsAccountRecord,
6002        now_unix: u64,
6003    ) -> Result<(), HnsWalletError> {
6004        {
6005            let cache = self.cache_read()?;
6006            if cache.account_revision != expected_revision {
6007                if cache.account_revision == next_revision && cache.account == next_account {
6008                    return Ok(());
6009                }
6010                return Err(HnsWalletError::StaleAddressReservation);
6011            }
6012        }
6013        // The account row is already durably committed by the caller. Even if
6014        // backend filter maintenance fails, advance the in-memory projection
6015        // to that durable truth before returning the error. Synchronization or
6016        // reopen can then repair the watch set without this live runtime
6017        // continuing from a stale change index.
6018        let watch_extension = self
6019            .backend
6020            .extend_locally_allocated_change_watch_set(&next_account, now_unix);
6021        let mut cache = self.cache_write()?;
6022        if cache.account_revision != expected_revision {
6023            if cache.account_revision == next_revision && cache.account == next_account {
6024                return watch_extension.map(|_| ());
6025            }
6026            return Err(HnsWalletError::StaleAddressReservation);
6027        }
6028        cache.account = next_account;
6029        cache.account_revision = next_revision;
6030        watch_extension.map(|_| ())
6031    }
6032
6033    fn install_loaded_account(
6034        &self,
6035        loaded: StoredEntity<HnsAccountRecord>,
6036    ) -> Result<(), HnsWalletError> {
6037        let mut cache = self.cache_write()?;
6038        if !same_account_identity(&cache.account.config, &loaded.value.config) {
6039            return Err(HnsWalletError::AccountConfigurationMismatch);
6040        }
6041        if loaded.revision < cache.account_revision {
6042            return Ok(());
6043        }
6044        if loaded.revision == cache.account_revision && loaded.value != cache.account {
6045            return Err(HnsWalletError::AccountConfigurationMismatch);
6046        }
6047        cache.account = loaded.value;
6048        cache.account_revision = loaded.revision;
6049        Ok(())
6050    }
6051
6052    fn prepared_send_from_plan(plan: &HnsSpendPlan) -> Result<PreparedSend, ChainError> {
6053        let payload = serde_json::to_vec(plan)
6054            .map_err(|_| ChainError::Backend("prepared send encoding failed".to_owned()))?;
6055        PreparedSend::new(
6056            ModuleId::Handshake,
6057            Amount {
6058                asset: WalletAsset::Hns,
6059                base_units: plan.amount,
6060            },
6061            plan.fee,
6062            plan.destination.clone(),
6063            plan.expires_at_unix,
6064            payload,
6065        )
6066    }
6067
6068    fn recover_prepared_send(
6069        stored: &StoredWorkflow<HnsSendWorkflow>,
6070        request: &SendRequest,
6071        config: &HnsRuntimeConfig,
6072        workflow_id: WorkflowId,
6073        now_unix: u64,
6074    ) -> Result<PreparedSend, ChainError> {
6075        let state = &stored.state;
6076        if stored.kind != WorkflowKind::HnsSend
6077            || state.stage != HnsSendStage::Prepared
6078            || state.transaction.is_some()
6079            || state.signed_transaction.is_some()
6080            || state.fee_quote.is_some()
6081            || state.plan.wallet_id != config.wallet_id
6082            || state.plan.account_id != config.account_id
6083            || state.plan.workflow_id != workflow_id
6084            || state.plan.request_nonce != request.request_nonce
6085            || state.plan.amount != request.amount.base_units
6086            || state.plan.maximum_fee != request.maximum_fee
6087            || state.plan.fee > state.plan.maximum_fee
6088            || state.plan.destination != request.destination
6089            || state.plan.inputs.is_empty()
6090            || state
6091                .plan
6092                .inputs
6093                .iter()
6094                .any(|input| !is_ordinary_hns_derivation(input.derivation))
6095            || state.plan.expires_at_unix <= now_unix
6096        {
6097            return Err(ChainError::InvalidRequest(
6098                "persisted Handshake send does not match retry",
6099            ));
6100        }
6101        canonical_input_coins(&state.plan.inputs).map_err(|_| ChainError::InvalidEvidence)?;
6102        Self::prepared_send_from_plan(&state.plan)
6103    }
6104
6105    fn prepared_settlement_artifact(
6106        prepared: &HnsPreparedSettlement,
6107    ) -> Result<PreparedArtifact, HnsWalletError> {
6108        recovery_publication::validate_prepared_publication(prepared)?;
6109        if prepared.broadcast_guard.as_ref().is_some_and(|guard| {
6110            !guard.authorizes_action(prepared.action, prepared.session_id, None)
6111        }) {
6112            return Err(HnsWalletError::InvalidPreparedArtifact);
6113        }
6114        let decoded = Transaction::decode(&prepared.signed_transaction)
6115            .map_err(|_| HnsWalletError::InvalidPreparedArtifact)?;
6116        if wallet_transaction_hash(&decoded)? != prepared.transaction {
6117            return Err(HnsWalletError::InvalidPreparedArtifact);
6118        }
6119        let fee_quote = prepared
6120            .fee_quote
6121            .as_ref()
6122            .ok_or(HnsWalletError::InvalidPreparedArtifact)?;
6123        let input_coins = prepared.canonical_input_coins()?;
6124        validate_final_fee_quote(
6125            &prepared.signed_transaction,
6126            &input_coins,
6127            fee_quote,
6128            fee_quote.binding,
6129            fee_quote.mempool,
6130            prepared.fee,
6131            prepared.maximum_fee,
6132        )?;
6133        let payload = serde_json::to_vec(prepared)?;
6134        PreparedArtifact::new(
6135            ModuleId::Handshake,
6136            prepared.session_id,
6137            prepared.approved_fee()?,
6138            prepared.expires_at_unix,
6139            payload,
6140        )
6141        .map_err(|_| HnsWalletError::InvalidPreparedArtifact)
6142    }
6143
6144    fn restore_scan(
6145        &self,
6146        store: &mut WalletStore,
6147        mut account: HnsAccountRecord,
6148        expected_account_revision: u64,
6149        expected_tip: ChainTip,
6150        now_unix: u64,
6151    ) -> Result<RestoreScanResult, HnsWalletError> {
6152        // Fence allocation before the first Shakedex discovery read. A stale
6153        // concurrent allocator or scan loses this WalletAccount CAS before it
6154        // can derive or commit a seller key. A failed/crashed scan leaves the
6155        // fence set; a later scan can take over with a new revision, while key
6156        // allocation remains fail-closed.
6157        account.shakedex_scan_in_progress = true;
6158        let expected_account_revision = store.save_wallet_account(
6159            &account_entity_id(&account.config),
6160            expected_account_revision,
6161            &account,
6162            now_unix,
6163        )?;
6164        let allocated_next = shakedex_key::allocation_next_index(store, &account.config)
6165            .map_err(map_shakedex_restore_error)?;
6166        normalize_restore_scan_account(&mut account, allocated_next)?;
6167        let scan = scan_restore_snapshot(&self.backend, account, expected_tip, None, |account| {
6168            Ok([
6169                derive_restore_addresses(store, account, KeyRole::HnsCoin)?,
6170                derive_restore_addresses(store, account, KeyRole::HnsShakedex)?,
6171            ])
6172        })?;
6173        persist_derived_addresses(store, &scan.account.config, &scan.addresses, now_unix)?;
6174        let account_revision = store.save_wallet_account(
6175            &account_entity_id(&scan.account.config),
6176            expected_account_revision,
6177            &scan.account,
6178            now_unix,
6179        )?;
6180        Ok((
6181            scan.account,
6182            account_revision,
6183            scan.binding,
6184            scan.mempool,
6185            scan.addresses,
6186            scan.history,
6187            scan.indexed_coins,
6188        ))
6189    }
6190
6191    fn cache_read(
6192        &self,
6193    ) -> Result<std::sync::RwLockReadGuard<'_, HnsRuntimeCache>, HnsWalletError> {
6194        self.cache
6195            .read()
6196            .map_err(|_| HnsWalletError::RuntimePoisoned)
6197    }
6198
6199    fn cache_write(
6200        &self,
6201    ) -> Result<std::sync::RwLockWriteGuard<'_, HnsRuntimeCache>, HnsWalletError> {
6202        self.cache
6203            .write()
6204            .map_err(|_| HnsWalletError::RuntimePoisoned)
6205    }
6206
6207    fn store_lock(&self) -> Result<SharedWalletStoreGuard<'_>, HnsWalletError> {
6208        self.store.runtime_guard().map_err(HnsWalletError::from)
6209    }
6210
6211    fn quote_final_transaction_once(
6212        &self,
6213        raw: &[u8],
6214        input_coins: &[Coin],
6215        expected_fee: BaseUnits,
6216        maximum_fee: BaseUnits,
6217    ) -> Result<HnsTransactionFeeQuote, HnsWalletError> {
6218        let cache = self.cache_read()?;
6219        let binding = cache.binding.ok_or(HnsWalletError::StaleNodeSnapshot)?;
6220        let mempool = cache
6221            .mempool_binding
6222            .ok_or(HnsWalletError::StaleNodeSnapshot)?;
6223        drop(cache);
6224        let quote = self.backend.quote_transaction_fee(
6225            raw,
6226            input_coins,
6227            DEFAULT_FEE_TARGET_BLOCKS,
6228            binding,
6229            mempool,
6230        )?;
6231        validate_final_fee_quote(
6232            raw,
6233            input_coins,
6234            &quote,
6235            binding,
6236            mempool,
6237            expected_fee,
6238            maximum_fee,
6239        )?;
6240        Ok(quote)
6241    }
6242
6243    /// Performs at most one explicit reconciliation and one quote retry. This
6244    /// is a bounded recovery transition, not a polling loop.
6245    fn quote_final_transaction(
6246        &self,
6247        raw: &[u8],
6248        input_coins: &[Coin],
6249        expected_fee: BaseUnits,
6250        maximum_fee: BaseUnits,
6251    ) -> Result<HnsTransactionFeeQuote, HnsWalletError> {
6252        match self.quote_final_transaction_once(raw, input_coins, expected_fee, maximum_fee) {
6253            Err(HnsWalletError::StaleNodeSnapshot)
6254            | Err(HnsWalletError::FeeQuoteInputUnavailable) => {
6255                self.reconcile()?;
6256                self.quote_final_transaction_once(raw, input_coins, expected_fee, maximum_fee)
6257            }
6258            result => result,
6259        }
6260    }
6261
6262    /// Fund the exact native-HNS descriptor committed by a bilateral swap
6263    /// session.  This deliberately accepts the descriptor, rather than an
6264    /// application-level deadline, so no caller can silently translate HNS's
6265    /// encoded median-time lock into a height lock.
6266    pub fn prepare_native_htlc_lock(
6267        &self,
6268        session_id: SessionId,
6269        descriptor: HnsHtlc,
6270        maximum_fee: BaseUnits,
6271    ) -> Result<PreparedSettlementLock, ChainError> {
6272        let cache = self.cache_read().map_err(map_chain_error)?;
6273        let network =
6274            shakedex_network_binding(cache.account.config.network).map_err(map_chain_error)?;
6275        drop(cache);
6276        descriptor
6277            .verify_for_network(network)
6278            .map_err(|_| ChainError::InvalidRequest("invalid native Handshake HTLC descriptor"))?;
6279        self.prepare_lock(SettlementLockRequest {
6280            session_id,
6281            module: ModuleId::Handshake,
6282            amount: Amount::new(WalletAsset::Hns, u128::from(descriptor.value.get())),
6283            hashlock: ObjectHash::new(descriptor.hashlock),
6284            receiver: hex::encode(descriptor.receiver_public_key),
6285            refund_target: hex::encode(descriptor.refund_public_key),
6286            absolute_timelock: u64::from(descriptor.refund_locktime),
6287            maximum_fee,
6288        })
6289    }
6290
6291    /// Native Shakescape funding requires the complete public recovery terms
6292    /// to be present in ordinary-wallet ancestors before its HTLC can exist.
6293    pub fn prepare_native_recoverable_htlc_lock(
6294        &self,
6295        session_id: SessionId,
6296        descriptor: HnsHtlc,
6297        maximum_fee: BaseUnits,
6298        publication: hns_wallet_chain_api::SwapRecoveryPublication,
6299    ) -> Result<PreparedSettlementLock, ChainError> {
6300        self.verify_native_htlc_network(&descriptor)?;
6301        if publication.terms().session_id != session_id.into_bytes()
6302            || recovery_publication::build_recovered_hns_htlc(
6303                publication.terms(),
6304                publication.side(),
6305            )
6306            .map_err(map_chain_error)?
6307                != descriptor
6308        {
6309            return Err(ChainError::InvalidEvidence);
6310        }
6311        self.prepare_lock_with_publication(
6312            SettlementLockRequest {
6313                session_id,
6314                module: ModuleId::Handshake,
6315                amount: Amount::new(WalletAsset::Hns, u128::from(descriptor.value.get())),
6316                hashlock: ObjectHash::new(descriptor.hashlock),
6317                receiver: hex::encode(descriptor.receiver_public_key),
6318                refund_target: hex::encode(descriptor.refund_public_key),
6319                absolute_timelock: u64::from(descriptor.refund_locktime),
6320                maximum_fee,
6321            },
6322            Some(publication),
6323        )
6324    }
6325
6326    /// Bind or refresh a reversible prepared HNS lock with the exact durable
6327    /// second-funding authority that its first irreversible submission must
6328    /// consume. The signed transaction and reservations remain unchanged.
6329    pub fn bind_prepared_native_htlc_lock_broadcast_guard(
6330        &self,
6331        artifact: &PreparedSettlementLock,
6332        broadcast_guard: HnsSettlementBroadcastGuard,
6333    ) -> Result<PreparedSettlementLock, ChainError> {
6334        let mut prepared: HnsPreparedSettlement =
6335            serde_json::from_slice(artifact.0.commitment_bytes())
6336                .map_err(|_| ChainError::InvalidEvidence)?;
6337        let now_unix = self.clock.now_unix().map_err(map_chain_error)?;
6338        if artifact.0.module != ModuleId::Handshake
6339            || prepared.stage != HnsSettlementStage::Prepared
6340            || prepared.action != HnsSettlementAction::Lock
6341            || prepared.session_id != artifact.0.session_id
6342            || prepared.approved_fee().map_err(map_chain_error)? != artifact.0.fee
6343            || prepared.expires_at_unix != artifact.0.expires_at_unix
6344            || prepared.expires_at_unix <= now_unix
6345            || !broadcast_guard.authorizes_action(
6346                HnsSettlementAction::Lock,
6347                prepared.session_id,
6348                Some(now_unix),
6349            )
6350        {
6351            return Err(ChainError::InvalidEvidence);
6352        }
6353        let kind = settlement_workflow_kind(HnsSettlementAction::Lock);
6354        let mut store = self.store_lock().map_err(map_chain_error)?;
6355        let stored = store
6356            .load_workflow::<HnsPreparedSettlement>(prepared.workflow_id)
6357            .map_err(map_chain_error)?
6358            .ok_or(ChainError::InvalidEvidence)?;
6359        if stored.kind != kind
6360            || stored.state.stage != HnsSettlementStage::Prepared
6361            || !same_prepared_settlement_except_guard(&stored.state, &prepared)
6362        {
6363            return Err(ChainError::InvalidEvidence);
6364        }
6365        prepared = stored.state;
6366        prepared.broadcast_guard = Some(broadcast_guard);
6367        store
6368            .save_workflow(
6369                prepared.workflow_id,
6370                kind,
6371                stored.revision,
6372                &prepared,
6373                false,
6374                now_unix,
6375            )
6376            .map_err(map_chain_error)?;
6377        Self::prepared_settlement_artifact(&prepared)
6378            .map(PreparedSettlementLock)
6379            .map_err(map_chain_error)
6380    }
6381
6382    /// Independently retrieve and verify the exact native-HNS lock committed
6383    /// by a bilateral session. Confirmation status comes from the runtime's
6384    /// authenticated backend binding; callers provide neither raw bytes nor a
6385    /// claimed confirmation count.
6386    pub fn verify_native_htlc_lock(
6387        &self,
6388        session_id: SessionId,
6389        descriptor: HnsHtlc,
6390        funding_transaction: TransactionHash,
6391        minimum_confirmations: u32,
6392    ) -> Result<Option<VerifiedLock>, ChainError> {
6393        self.verify_native_htlc_network(&descriptor)?;
6394        if minimum_confirmations == 0 {
6395            return Err(ChainError::InvalidRequest(
6396                "invalid HNS confirmation minimum",
6397            ));
6398        }
6399        let cache = self.cache_read().map_err(map_chain_error)?;
6400        ensure_settlement_ready(&cache)?;
6401        let binding = cache.binding.ok_or(ChainError::NotSynchronized)?;
6402        let mempool = cache.mempool_binding.ok_or(ChainError::NotSynchronized)?;
6403        // A peer's signed minimum is a floor, not authority to weaken this
6404        // wallet's local settlement policy. Legacy mobile terms advertised
6405        // one confirmation while the native wallet default required two;
6406        // rejecting those locks forever was unnecessary once the locally
6407        // authenticated chain had reached the stronger threshold. Elevate
6408        // verification to the stronger of both policies and return `None`
6409        // normally until that threshold is reached.
6410        let required_confirmations =
6411            minimum_confirmations.max(cache.account.config.minimum_confirmations);
6412        drop(cache);
6413        let evidence = self
6414            .backend
6415            .get_transaction_evidence(funding_transaction, binding, Some(mempool))
6416            .map_err(|error| {
6417                evidence_error_context(map_chain_error(error), "HNS lock evidence retrieval")
6418            })?;
6419        if evidence.binding != binding || evidence.mempool != mempool || evidence.status.conflicted
6420        {
6421            return Err(ChainError::InvalidEvidenceContext(
6422                "HNS lock snapshot binding",
6423            ));
6424        }
6425        if evidence.status.confirmation_count < required_confirmations {
6426            return Ok(None);
6427        }
6428        let raw = evidence.raw.ok_or(ChainError::InvalidEvidenceContext(
6429            "HNS lock transaction lookup",
6430        ))?;
6431        let verified = <Self as AtomicSettlement>::verify_lock(
6432            self,
6433            VerifySettlementLockRequest {
6434                expected: SettlementLockExpectation {
6435                    session_id,
6436                    module: ModuleId::Handshake,
6437                    amount: Amount::new(WalletAsset::Hns, u128::from(descriptor.value.get())),
6438                    hashlock: ObjectHash::new(descriptor.hashlock),
6439                    receiver: hex::encode(descriptor.receiver_public_key),
6440                    refund_target: hex::encode(descriptor.refund_public_key),
6441                    absolute_timelock: u64::from(descriptor.refund_locktime),
6442                    minimum_confirmations: required_confirmations,
6443                },
6444                transaction_or_receipt: raw,
6445                confirmation_count: evidence.status.confirmation_count,
6446            },
6447        )
6448        .map_err(|error| evidence_error_context(error, "HNS lock verification"))?;
6449        Ok(Some(verified.0))
6450    }
6451
6452    /// Resume verification of this wallet's persisted native lock after
6453    /// restart without requiring the platform to retain transaction bytes or
6454    /// a broadcast receipt.
6455    pub fn verify_persisted_native_htlc_lock(
6456        &self,
6457        session_id: SessionId,
6458        descriptor: HnsHtlc,
6459        minimum_confirmations: u32,
6460    ) -> Result<Option<VerifiedLock>, ChainError> {
6461        self.verify_native_htlc_network(&descriptor)?;
6462        let config = self
6463            .cache_read()
6464            .map_err(map_chain_error)?
6465            .account
6466            .config
6467            .clone();
6468        let workflow_id = settlement_workflow_id(&config, session_id, HnsSettlementAction::Lock);
6469        let Some(stored) = self
6470            .store_lock()
6471            .map_err(map_chain_error)?
6472            .load_workflow::<HnsPreparedSettlement>(workflow_id)
6473            .map_err(map_chain_error)?
6474        else {
6475            // No locally prepared/broadcast lock is the normal pre-funding
6476            // condition. It is absence of evidence, not invalid evidence.
6477            return Ok(None);
6478        };
6479        let HnsSettlementTerms::Lock { request } = &stored.state.terms else {
6480            return Err(ChainError::InvalidEvidence);
6481        };
6482        if stored.kind != settlement_workflow_kind(HnsSettlementAction::Lock)
6483            || stored.state.session_id != session_id
6484            || stored.state.action != HnsSettlementAction::Lock
6485            || !matches!(
6486                stored.state.stage,
6487                HnsSettlementStage::Broadcast
6488                    | HnsSettlementStage::Mempool
6489                    | HnsSettlementStage::Confirmed
6490                    | HnsSettlementStage::RequiresRebroadcast
6491            )
6492            || request.amount != Amount::new(WalletAsset::Hns, u128::from(descriptor.value.get()))
6493            || request.hashlock != ObjectHash::new(descriptor.hashlock)
6494            || request.receiver != hex::encode(descriptor.receiver_public_key)
6495            || request.refund_target != hex::encode(descriptor.refund_public_key)
6496            || request.absolute_timelock != u64::from(descriptor.refund_locktime)
6497        {
6498            return Err(ChainError::InvalidEvidence);
6499        }
6500        let transaction = stored.state.transaction;
6501        drop(stored);
6502        self.verify_native_htlc_lock(session_id, descriptor, transaction, minimum_confirmations)
6503    }
6504
6505    /// Recover the transaction identifier of an irreversibly submitted native
6506    /// HNS lock after a caller loses the broadcast response. This checks the
6507    /// exact descriptor against the wallet's persisted terms and never treats
6508    /// a merely prepared or expired artifact as submitted chain evidence.
6509    pub fn submitted_native_htlc_lock_transaction_id(
6510        &self,
6511        session_id: SessionId,
6512        descriptor: HnsHtlc,
6513    ) -> Result<Option<TransactionHash>, ChainError> {
6514        self.verify_native_htlc_network(&descriptor)?;
6515        let config = self
6516            .cache_read()
6517            .map_err(map_chain_error)?
6518            .account
6519            .config
6520            .clone();
6521        let workflow_id = settlement_workflow_id(&config, session_id, HnsSettlementAction::Lock);
6522        let Some(stored) = self
6523            .store_lock()
6524            .map_err(map_chain_error)?
6525            .load_workflow::<HnsPreparedSettlement>(workflow_id)
6526            .map_err(map_chain_error)?
6527        else {
6528            return Ok(None);
6529        };
6530        let HnsSettlementTerms::Lock { request } = &stored.state.terms else {
6531            return Err(ChainError::InvalidEvidence);
6532        };
6533        if stored.kind != settlement_workflow_kind(HnsSettlementAction::Lock)
6534            || stored.state.wallet_id != config.wallet_id
6535            || stored.state.account_id != config.account_id
6536            || stored.state.workflow_id != workflow_id
6537            || stored.state.session_id != session_id
6538            || stored.state.action != HnsSettlementAction::Lock
6539            || request.amount != Amount::new(WalletAsset::Hns, u128::from(descriptor.value.get()))
6540            || request.hashlock != ObjectHash::new(descriptor.hashlock)
6541            || request.receiver != hex::encode(descriptor.receiver_public_key)
6542            || request.refund_target != hex::encode(descriptor.refund_public_key)
6543            || request.absolute_timelock != u64::from(descriptor.refund_locktime)
6544        {
6545            return Err(ChainError::InvalidEvidence);
6546        }
6547        if !stored.irreversible_broadcast_prepared {
6548            return Ok(None);
6549        }
6550        if matches!(
6551            stored.state.stage,
6552            HnsSettlementStage::Broadcast
6553                | HnsSettlementStage::Mempool
6554                | HnsSettlementStage::Confirmed
6555                | HnsSettlementStage::RequiresRebroadcast
6556        ) {
6557            Ok(Some(stored.state.transaction))
6558        } else {
6559            Err(ChainError::InvalidEvidence)
6560        }
6561    }
6562
6563    /// Recover the exact submitted redeem or refund transaction after an
6564    /// interrupted caller response. The wallet checks the persisted verified
6565    /// lock against the descriptor and funding ID before reporting an ID.
6566    pub fn submitted_native_htlc_spend_transaction_id(
6567        &self,
6568        session_id: SessionId,
6569        descriptor: HnsHtlc,
6570        funding_id: TransactionHash,
6571        refund: bool,
6572    ) -> Result<Option<TransactionHash>, ChainError> {
6573        self.verify_native_htlc_network(&descriptor)?;
6574        let config = self
6575            .cache_read()
6576            .map_err(map_chain_error)?
6577            .account
6578            .config
6579            .clone();
6580        let action = if refund {
6581            HnsSettlementAction::Refund
6582        } else {
6583            HnsSettlementAction::Redeem
6584        };
6585        let workflow_id = settlement_workflow_id(&config, session_id, action);
6586        let Some(stored) = self
6587            .store_lock()
6588            .map_err(map_chain_error)?
6589            .load_workflow::<HnsPreparedSettlement>(workflow_id)
6590            .map_err(map_chain_error)?
6591        else {
6592            return Ok(None);
6593        };
6594        let lock = match (&stored.state.terms, action) {
6595            (HnsSettlementTerms::Redeem { lock }, HnsSettlementAction::Redeem)
6596            | (HnsSettlementTerms::Refund { lock }, HnsSettlementAction::Refund) => lock,
6597            _ => return Err(ChainError::InvalidEvidence),
6598        };
6599        if stored.kind != settlement_workflow_kind(action)
6600            || stored.state.wallet_id != config.wallet_id
6601            || stored.state.account_id != config.account_id
6602            || stored.state.workflow_id != workflow_id
6603            || stored.state.session_id != session_id
6604            || stored.state.action != action
6605            || lock.funding_id != funding_id
6606        {
6607            return Err(ChainError::InvalidEvidence);
6608        }
6609        validate_native_htlc_lock(&descriptor, session_id, lock)?;
6610        if !stored.irreversible_broadcast_prepared {
6611            return Ok(None);
6612        }
6613        if matches!(
6614            stored.state.stage,
6615            HnsSettlementStage::Broadcast
6616                | HnsSettlementStage::Mempool
6617                | HnsSettlementStage::Confirmed
6618                | HnsSettlementStage::RequiresRebroadcast
6619        ) {
6620            Ok(Some(stored.state.transaction))
6621        } else {
6622            Err(ChainError::InvalidEvidence)
6623        }
6624    }
6625
6626    /// Prepare a refund from the exact descriptor committed by a bilateral
6627    /// swap session.  Height locktimes are bound to the validated tip height;
6628    /// HNS median-time locktimes are bound to that same tip's validated median
6629    /// time past.  Neither value is supplied by the caller.
6630    pub fn prepare_native_htlc_refund_with_settlement_signer(
6631        &self,
6632        session_id: SessionId,
6633        descriptor: HnsHtlc,
6634        lock: VerifiedLock,
6635        maximum_fee: BaseUnits,
6636        signer: &dyn SettlementSigner,
6637    ) -> Result<PreparedSettlementRefund, ChainError> {
6638        self.prepare_native_htlc_refund_with_optional_signer(
6639            session_id,
6640            descriptor,
6641            lock,
6642            maximum_fee,
6643            Some(signer),
6644            None,
6645        )
6646    }
6647
6648    /// Prepare the exact native-HNS refund with this wallet's durable,
6649    /// session-derived refund key. The descriptor and verified lock must bind
6650    /// to that key; the caller cannot supply a scalar or a claimed chain time.
6651    pub fn prepare_native_htlc_refund_with_wallet_key(
6652        &self,
6653        session_id: SessionId,
6654        descriptor: HnsHtlc,
6655        lock: VerifiedLock,
6656        maximum_fee: BaseUnits,
6657    ) -> Result<PreparedSettlementRefund, ChainError> {
6658        self.prepare_native_htlc_refund_with_optional_signer(
6659            session_id,
6660            descriptor,
6661            lock,
6662            maximum_fee,
6663            None,
6664            None,
6665        )
6666    }
6667
6668    fn prepare_native_htlc_refund_with_optional_signer(
6669        &self,
6670        session_id: SessionId,
6671        descriptor: HnsHtlc,
6672        lock: VerifiedLock,
6673        maximum_fee: BaseUnits,
6674        signer: Option<&dyn SettlementSigner>,
6675        broadcast_guard: Option<HnsSettlementBroadcastGuard>,
6676    ) -> Result<PreparedSettlementRefund, ChainError> {
6677        self.verify_native_htlc_network(&descriptor)?;
6678        validate_native_htlc_lock(&descriptor, session_id, &lock)?;
6679        let cache = self.cache_read().map_err(map_chain_error)?;
6680        let current = if hns_locktime_is_time(lock.absolute_timelock)? {
6681            cache
6682                .binding
6683                .ok_or(ChainError::NotSynchronized)?
6684                .tip
6685                .median_time_past
6686        } else {
6687            cache.sync.validated_height
6688        };
6689        drop(cache);
6690        self.prepare_settlement_spend(
6691            session_id,
6692            lock,
6693            None,
6694            maximum_fee,
6695            Some(current),
6696            HnsSettlementAction::Refund,
6697            signer,
6698            broadcast_guard,
6699        )
6700        .map(PreparedSettlementRefund)
6701    }
6702
6703    /// Prepare the receiver branch of the exact native-HNS descriptor
6704    /// committed by a bilateral swap session.
6705    pub fn prepare_native_htlc_redeem_with_settlement_signer(
6706        &self,
6707        session_id: SessionId,
6708        descriptor: HnsHtlc,
6709        lock: VerifiedLock,
6710        preimage: Preimage,
6711        maximum_fee: BaseUnits,
6712        signer: &dyn SettlementSigner,
6713    ) -> Result<PreparedSettlementRedeem, ChainError> {
6714        self.prepare_native_htlc_redeem_with_optional_signer(
6715            session_id,
6716            descriptor,
6717            lock,
6718            preimage,
6719            maximum_fee,
6720            Some(signer),
6721            None,
6722        )
6723    }
6724
6725    /// Prepare the receiver branch using this wallet's durable,
6726    /// session-derived receiver key. The verified lock, descriptor, and
6727    /// preimage are checked before the wallet signs or persists an artifact.
6728    pub fn prepare_native_htlc_redeem_with_wallet_key(
6729        &self,
6730        session_id: SessionId,
6731        descriptor: HnsHtlc,
6732        lock: VerifiedLock,
6733        preimage: Preimage,
6734        maximum_fee: BaseUnits,
6735    ) -> Result<PreparedSettlementRedeem, ChainError> {
6736        self.prepare_native_htlc_redeem_with_optional_signer(
6737            session_id,
6738            descriptor,
6739            lock,
6740            preimage,
6741            maximum_fee,
6742            None,
6743            None,
6744        )
6745    }
6746
6747    /// Prepare a native-HNS redeem whose first submission is atomically bound
6748    /// to the exact ShakeScape funding and signed-session revisions that
6749    /// authorized it. A stale guard can never cross the irreversible
6750    /// broadcast checkpoint; an already checkpointed transaction remains
6751    /// recoverable through the ordinary rebroadcast path.
6752    #[allow(clippy::too_many_arguments)]
6753    pub fn prepare_native_htlc_redeem_with_settlement_signer_and_broadcast_guard(
6754        &self,
6755        session_id: SessionId,
6756        descriptor: HnsHtlc,
6757        lock: VerifiedLock,
6758        preimage: Preimage,
6759        maximum_fee: BaseUnits,
6760        signer: &dyn SettlementSigner,
6761        broadcast_guard: HnsSettlementBroadcastGuard,
6762    ) -> Result<PreparedSettlementRedeem, ChainError> {
6763        self.prepare_native_htlc_redeem_with_optional_signer(
6764            session_id,
6765            descriptor,
6766            lock,
6767            preimage,
6768            maximum_fee,
6769            Some(signer),
6770            Some(broadcast_guard),
6771        )
6772    }
6773
6774    #[allow(clippy::too_many_arguments)]
6775    fn prepare_native_htlc_redeem_with_optional_signer(
6776        &self,
6777        session_id: SessionId,
6778        descriptor: HnsHtlc,
6779        lock: VerifiedLock,
6780        preimage: Preimage,
6781        maximum_fee: BaseUnits,
6782        signer: Option<&dyn SettlementSigner>,
6783        broadcast_guard: Option<HnsSettlementBroadcastGuard>,
6784    ) -> Result<PreparedSettlementRedeem, ChainError> {
6785        self.verify_native_htlc_network(&descriptor)?;
6786        validate_native_htlc_lock(&descriptor, session_id, &lock)
6787            .map_err(|error| evidence_error_context(error, "HNS redeem descriptor binding"))?;
6788        if HnsHtlc::hash_preimage(preimage.expose_for_settlement()) != descriptor.hashlock {
6789            return Err(ChainError::InvalidEvidenceContext(
6790                "HNS redeem preimage binding",
6791            ));
6792        }
6793        self.prepare_settlement_spend(
6794            session_id,
6795            lock,
6796            Some(preimage),
6797            maximum_fee,
6798            None,
6799            HnsSettlementAction::Redeem,
6800            signer,
6801            broadcast_guard,
6802        )
6803        .map(PreparedSettlementRedeem)
6804    }
6805
6806    /// Observe and fully verify one spend of the exact native-HNS HTLC
6807    /// descriptor committed by a bilateral session. The transaction bytes and
6808    /// status are fetched through this wallet's current local chain authority;
6809    /// the witness program is then executed against the retained verified
6810    /// funding coin before a redeem preimage is returned.
6811    pub fn verify_native_htlc_spend(
6812        &self,
6813        session_id: SessionId,
6814        descriptor: HnsHtlc,
6815        lock: VerifiedLock,
6816        spending_transaction: TransactionHash,
6817    ) -> Result<Option<VerifiedNativeHtlcSpend>, ChainError> {
6818        self.verify_native_htlc_network(&descriptor)?;
6819        validate_native_htlc_lock(&descriptor, session_id, &lock)?;
6820        let cache = self.cache_read().map_err(map_chain_error)?;
6821        ensure_settlement_ready(&cache)?;
6822        let binding = cache.binding.ok_or(ChainError::NotSynchronized)?;
6823        let mempool_binding = cache.mempool_binding.ok_or(ChainError::NotSynchronized)?;
6824        let config = cache.account.config.clone();
6825        drop(cache);
6826        let record = self
6827            .store_lock()
6828            .map_err(map_chain_error)?
6829            .hns_verified_settlement::<HnsVerifiedSettlementRecord>(&settlement_entity_id(
6830                &config, session_id,
6831            ))
6832            .map_err(map_chain_error)?
6833            .ok_or(ChainError::InvalidEvidence)?
6834            .value;
6835        if record.verified != lock {
6836            return Err(ChainError::InvalidEvidence);
6837        }
6838        let funding_coin = record
6839            .funding_coin
6840            .ok_or(ChainError::InvalidEvidence)?
6841            .to_canonical_coin()
6842            .map_err(map_chain_error)?;
6843        let evidence = self
6844            .backend
6845            .get_transaction_evidence(spending_transaction, binding, Some(mempool_binding))
6846            .map_err(map_chain_error)?;
6847        if evidence.binding != binding || evidence.mempool != mempool_binding {
6848            return Err(ChainError::InvalidEvidence);
6849        }
6850        if evidence.status.conflicted
6851            || (!evidence.status.in_mempool && evidence.status.confirmation_count == 0)
6852        {
6853            return Ok(None);
6854        }
6855        let raw = evidence.raw.ok_or(ChainError::InvalidEvidence)?;
6856        let transaction =
6857            decode_transaction_for_id(&raw, spending_transaction).map_err(map_chain_error)?;
6858        let expected_outpoint = Outpoint {
6859            transaction_hash: CanonicalTransactionHash::new(lock.funding_id.into_bytes()),
6860            index: record.output_index,
6861        };
6862        let matching_input = transaction
6863            .inputs
6864            .iter()
6865            .enumerate()
6866            .filter(|(_, input)| input.previous_output == expected_outpoint)
6867            .collect::<Vec<_>>();
6868        let [(input_index, _)] = matching_input.as_slice() else {
6869            return Err(ChainError::InvalidEvidence);
6870        };
6871        let spend = descriptor
6872            .verify_spend(&transaction, *input_index, &funding_coin)
6873            .map_err(|_| ChainError::InvalidEvidence)?;
6874        match spend {
6875            HnsHtlcSpend::Redeem { preimage } => {
6876                let preimage = Preimage::new(*preimage.expose_for_settlement());
6877                Ok(Some(VerifiedNativeHtlcSpend::Redeem {
6878                    transaction: spending_transaction,
6879                    confirmation_count: evidence.status.confirmation_count,
6880                    preimage,
6881                }))
6882            }
6883            HnsHtlcSpend::Refund => Ok(Some(VerifiedNativeHtlcSpend::Refund {
6884                transaction: spending_transaction,
6885                confirmation_count: evidence.status.confirmation_count,
6886            })),
6887        }
6888    }
6889
6890    /// Discover and verify the confirmed transaction spending an exact native
6891    /// HNS HTLC funding outpoint. The backend supplies only the candidate
6892    /// transaction identifier; `verify_native_htlc_spend` still fetches the
6893    /// raw bytes and executes the committed witness script locally.
6894    pub fn verify_observed_native_htlc_spend(
6895        &self,
6896        session_id: SessionId,
6897        descriptor: HnsHtlc,
6898        lock: VerifiedLock,
6899    ) -> Result<Option<VerifiedNativeHtlcSpend>, ChainError> {
6900        self.verify_native_htlc_network(&descriptor)?;
6901        validate_native_htlc_lock(&descriptor, session_id, &lock)?;
6902        let cache = self.cache_read().map_err(map_chain_error)?;
6903        ensure_settlement_ready(&cache)?;
6904        let binding = cache.binding.ok_or(ChainError::NotSynchronized)?;
6905        let config = cache.account.config.clone();
6906        drop(cache);
6907        let record = self
6908            .store_lock()
6909            .map_err(map_chain_error)?
6910            .hns_verified_settlement::<HnsVerifiedSettlementRecord>(&settlement_entity_id(
6911                &config, session_id,
6912            ))
6913            .map_err(map_chain_error)?
6914            .ok_or(ChainError::InvalidEvidence)?
6915            .value;
6916        if record.verified != lock {
6917            return Err(ChainError::InvalidEvidence);
6918        }
6919        let outpoint = HnsOutpoint {
6920            transaction: lock.funding_id,
6921            output_index: record.output_index,
6922        };
6923        let evidence = self
6924            .backend
6925            .get_outpoint_spend_evidence(&[outpoint], binding)
6926            .map_err(map_chain_error)?;
6927        validate_spend_evidence(&evidence, binding, &[outpoint]).map_err(map_chain_error)?;
6928        let Some(spending) = evidence.entries[0].spending else {
6929            return Ok(None);
6930        };
6931        self.verify_native_htlc_spend(session_id, descriptor, lock, spending.transaction)
6932    }
6933
6934    fn verify_native_htlc_network(&self, descriptor: &HnsHtlc) -> Result<(), ChainError> {
6935        let cache = self.cache_read().map_err(map_chain_error)?;
6936        let network =
6937            shakedex_network_binding(cache.account.config.network).map_err(map_chain_error)?;
6938        drop(cache);
6939        descriptor
6940            .verify_for_network(network)
6941            .map_err(|_| ChainError::InvalidRequest("invalid native Handshake HTLC descriptor"))
6942    }
6943
6944    /// Prepare a native-HNS redeem with a chain-neutral per-session signer.
6945    /// The signer must exactly equal the receiver key frozen in the verified
6946    /// lock; its scalar never enters this runtime or its persistence layer.
6947    pub fn prepare_redeem_with_settlement_signer(
6948        &self,
6949        request: SettlementRedeemRequest,
6950        signer: &dyn SettlementSigner,
6951    ) -> Result<PreparedSettlementRedeem, ChainError> {
6952        let expected_hash: [u8; 32] =
6953            Sha256::digest(request.preimage.expose_for_settlement()).into();
6954        if expected_hash != *request.lock.hashlock.as_bytes() {
6955            return Err(ChainError::InvalidEvidence);
6956        }
6957        self.prepare_settlement_spend(
6958            request.session_id,
6959            request.lock,
6960            Some(request.preimage),
6961            request.maximum_fee,
6962            None,
6963            HnsSettlementAction::Redeem,
6964            Some(signer),
6965            None,
6966        )
6967        .map(PreparedSettlementRedeem)
6968    }
6969
6970    /// Prepare a native-HNS refund with a chain-neutral per-session signer.
6971    /// The caller supplies the exact local validated HNS height and the signer
6972    /// must equal the refund key frozen in the verified lock.
6973    pub fn prepare_refund_with_settlement_signer(
6974        &self,
6975        request: SettlementRefundRequest,
6976        signer: &dyn SettlementSigner,
6977    ) -> Result<PreparedSettlementRefund, ChainError> {
6978        if !hns_refund_locktime_mature(request.lock.absolute_timelock, request.current_chain_time)
6979            .map_err(|_| ChainError::InvalidRequest("refund timelock is invalid or not mature"))?
6980        {
6981            return Err(ChainError::InvalidRequest("refund timelock is not mature"));
6982        }
6983        self.prepare_settlement_spend(
6984            request.session_id,
6985            request.lock,
6986            None,
6987            request.maximum_fee,
6988            Some(request.current_chain_time),
6989            HnsSettlementAction::Refund,
6990            Some(signer),
6991            None,
6992        )
6993        .map(PreparedSettlementRefund)
6994    }
6995}
6996
6997impl<B: HnsBackend, C: HnsClock> HnsWalletRuntime<B, C> {
6998    fn reconcile_transactions(
6999        &self,
7000        history: &[HistoryEntry],
7001        addresses: &[DerivedHnsAddress],
7002        binding: SnapshotBinding,
7003        mempool_binding: MempoolSnapshotBinding,
7004        common_ancestor: Option<u64>,
7005    ) -> Result<Vec<HnsTransactionRecord>, HnsWalletError> {
7006        let previous = self.cache_read()?.transactions.clone();
7007        reconcile_hns_read_transactions(
7008            &self.backend,
7009            history,
7010            addresses,
7011            binding,
7012            mempool_binding,
7013            common_ancestor,
7014            &previous,
7015        )
7016    }
7017
7018    fn revalidate_names(
7019        &self,
7020        store: &mut WalletStore,
7021        binding: SnapshotBinding,
7022        now_unix: u64,
7023    ) -> Result<usize, HnsWalletError> {
7024        let config = self.cache_read()?.account.config.clone();
7025        let wallet_name_addresses = persisted_name_addresses(store, &config)?;
7026        let names = store.list_entities_by_id_prefix::<KnownName>(
7027            EntityKind::KnownName,
7028            &account_entity_prefix(&config),
7029            MAX_HISTORY_RESULTS,
7030        )?;
7031        let addresses = wallet_name_addresses;
7032        let current_names = revalidate_hns_read_names(&self.backend, &names, &addresses, binding)?;
7033        let revisions = names
7034            .iter()
7035            .map(|stored| (stored.value.name_hash, stored.revision))
7036            .collect::<BTreeMap<_, _>>();
7037        let count = current_names.len();
7038        for current in current_names {
7039            let revision = revisions
7040                .get(&current.name_hash)
7041                .copied()
7042                .ok_or(HnsWalletError::InvalidEvidence)?;
7043            store.save_known_name(
7044                &namespaced_name_id(&config, current.name_hash),
7045                revision,
7046                &current,
7047                now_unix,
7048            )?;
7049        }
7050        Ok(count)
7051    }
7052
7053    fn reconcile_send_workflows(
7054        &self,
7055        store: &mut WalletStore,
7056        binding: SnapshotBinding,
7057        mempool_binding: MempoolSnapshotBinding,
7058        now_unix: u64,
7059    ) -> Result<Vec<WorkflowId>, HnsWalletError> {
7060        let workflows = store.list_workflows_complete::<HnsSendWorkflow>(
7061            WorkflowKind::HnsSend,
7062            MAX_HISTORY_RESULTS,
7063        )?;
7064        let config = self.cache_read()?.account.config.clone();
7065        let mut pending = Vec::new();
7066        for stored in workflows {
7067            if stored.state.plan.wallet_id != config.wallet_id
7068                || stored.state.plan.account_id != config.account_id
7069            {
7070                continue;
7071            }
7072            if stored.state.stage == HnsSendStage::Prepared
7073                && stored.state.plan.expires_at_unix <= now_unix
7074            {
7075                let mut state = stored.state;
7076                state.stage = HnsSendStage::Expired;
7077                let deletes = reservation_deletes(store, &config, stored.id)?;
7078                store.save_workflow_with_entity_batch::<_, HnsInputReservation>(
7079                    stored.id,
7080                    WorkflowKind::HnsSend,
7081                    stored.revision,
7082                    &state,
7083                    false,
7084                    now_unix,
7085                    EntityKind::InputReservation,
7086                    &[],
7087                    &deletes,
7088                )?;
7089                continue;
7090            }
7091            let Some(txid) = stored.state.transaction else {
7092                continue;
7093            };
7094            let evidence =
7095                self.backend
7096                    .get_transaction_evidence(txid, binding, Some(mempool_binding))?;
7097            if evidence.binding != binding || evidence.mempool != mempool_binding {
7098                return Err(HnsWalletError::StaleNodeSnapshot);
7099            }
7100            let chain_status = evidence.status;
7101            let outpoints: Vec<HnsOutpoint> = stored
7102                .state
7103                .plan
7104                .inputs
7105                .iter()
7106                .map(|input| input.coin.outpoint)
7107                .collect();
7108            let competing_spender =
7109                has_competing_spender_in_batches(&self.backend, &outpoints, binding, txid)?;
7110            let next_stage = if chain_status.conflicted || competing_spender {
7111                HnsSendStage::Conflicted
7112            } else if chain_status.confirmation_count > 0 {
7113                HnsSendStage::Confirmed
7114            } else if chain_status.in_mempool {
7115                HnsSendStage::Mempool
7116            } else if send_is_within_propagation_grace(
7117                stored.state.stage,
7118                stored.updated_at_unix,
7119                now_unix,
7120            ) {
7121                HnsSendStage::Broadcast
7122            } else if matches!(
7123                stored.state.stage,
7124                HnsSendStage::Authorized
7125                    | HnsSendStage::Broadcast
7126                    | HnsSendStage::Mempool
7127                    | HnsSendStage::RequiresRebroadcast
7128            ) {
7129                pending.push(stored.id);
7130                HnsSendStage::RequiresRebroadcast
7131            } else {
7132                stored.state.stage
7133            };
7134            if next_stage != stored.state.stage {
7135                let mut state = stored.state;
7136                state.stage = next_stage;
7137                let deletes = if matches!(
7138                    next_stage,
7139                    HnsSendStage::Confirmed | HnsSendStage::Conflicted
7140                ) {
7141                    reservation_deletes(store, &config, stored.id)?
7142                } else {
7143                    Vec::new()
7144                };
7145                store.save_workflow_with_entity_batch::<_, HnsInputReservation>(
7146                    stored.id,
7147                    WorkflowKind::HnsSend,
7148                    stored.revision,
7149                    &state,
7150                    state.signed_transaction.is_some(),
7151                    now_unix,
7152                    EntityKind::InputReservation,
7153                    &[],
7154                    &deletes,
7155                )?;
7156            }
7157        }
7158        Ok(pending)
7159    }
7160
7161    fn retain_or_insert_pending_wallet_activity(
7162        &self,
7163        store: &WalletStore,
7164        transactions: &mut Vec<HnsTransactionRecord>,
7165    ) -> Result<(), HnsWalletError> {
7166        let config = self.cache_read()?.account.config.clone();
7167        retain_or_insert_pending_wallet_activity_for_config(store, &config, transactions)
7168    }
7169
7170    fn has_competing_spender(
7171        &self,
7172        transaction_id: TransactionHash,
7173        transaction: &Transaction,
7174        binding: SnapshotBinding,
7175    ) -> Result<bool, HnsWalletError> {
7176        hns_read_has_competing_spender(&self.backend, transaction_id, transaction, binding)
7177    }
7178
7179    fn cleanup_input_reservations(
7180        &self,
7181        store: &mut WalletStore,
7182        config: &HnsRuntimeConfig,
7183        coins: &[TrackedHnsCoin],
7184        binding: SnapshotBinding,
7185        mempool_binding: MempoolSnapshotBinding,
7186        now_unix: u64,
7187    ) -> Result<(), HnsWalletError> {
7188        let unspent: BTreeSet<HnsOutpoint> = coins
7189            .iter()
7190            .filter(|coin| is_ordinary_hns_derivation(coin.derivation))
7191            .map(|coin| coin.coin.outpoint)
7192            .collect();
7193        let mut name_workflows = BTreeMap::new();
7194        for kind in [WorkflowKind::NameTransfer, WorkflowKind::NameFinalize] {
7195            for workflow in
7196                store.list_workflows_complete::<HnsNameWorkflow>(kind, MAX_HISTORY_RESULTS)?
7197            {
7198                if workflow.state.plan.wallet_id != config.wallet_id
7199                    || workflow.state.plan.account_id != config.account_id
7200                {
7201                    continue;
7202                }
7203                if workflow.state.plan.workflow_id != workflow.id
7204                    || workflow.state.plan.action.workflow_kind() != kind
7205                {
7206                    return Err(HnsWalletError::InvalidWorkflow);
7207                }
7208                let mut expected_reservations = BTreeMap::new();
7209                expected_reservations.insert(
7210                    workflow.state.plan.source.owner_outpoint,
7211                    HnsInputReservationKind::Name {
7212                        name_hash: workflow.state.plan.name_hash,
7213                    },
7214                );
7215                for input in &workflow.state.plan.funding_inputs {
7216                    if !is_ordinary_hns_spend_candidate(input)
7217                        || expected_reservations
7218                            .insert(input.coin.outpoint, HnsInputReservationKind::Ordinary)
7219                            .is_some()
7220                    {
7221                        return Err(HnsWalletError::InvalidWorkflow);
7222                    }
7223                }
7224                let terminal = matches!(
7225                    workflow.state.stage,
7226                    NameOperationState::Conflicted
7227                        | NameOperationState::Expired
7228                        | NameOperationState::Cancelled
7229                );
7230                if name_workflows
7231                    .insert(workflow.id, (expected_reservations, terminal))
7232                    .is_some()
7233                {
7234                    return Err(HnsWalletError::InvalidWorkflow);
7235                }
7236            }
7237        }
7238        let reservations = account_input_reservations(store, config)?;
7239        let mut observed_name_reservations: BTreeMap<WorkflowId, BTreeSet<HnsOutpoint>> =
7240            BTreeMap::new();
7241        let mut deletes = Vec::new();
7242        for stored in reservations {
7243            if let Some((expected_reservations, terminal)) =
7244                name_workflows.get(&stored.value.workflow_id)
7245            {
7246                if expected_reservations.get(&stored.value.outpoint) != Some(&stored.value.kind) {
7247                    return Err(HnsWalletError::InvalidWorkflow);
7248                }
7249                if !observed_name_reservations
7250                    .entry(stored.value.workflow_id)
7251                    .or_default()
7252                    .insert(stored.value.outpoint)
7253                {
7254                    return Err(HnsWalletError::InvalidWorkflow);
7255                }
7256                if *terminal {
7257                    deletes.push(EntityBatchDelete {
7258                        id: stored.id,
7259                        expected_revision: stored.revision,
7260                    });
7261                }
7262                continue;
7263            }
7264            if matches!(stored.value.kind, HnsInputReservationKind::Name { .. }) {
7265                deletes.push(EntityBatchDelete {
7266                    id: stored.id,
7267                    expected_revision: stored.revision,
7268                });
7269                continue;
7270            }
7271            // Shakedex value workflows own these reservations explicitly.
7272            // Generic expiry, UTXO disappearance, and settlement cleanup must
7273            // never release either their script-controlled source or their
7274            // ordinary fee/payment suffix after a restart or reorg.
7275            if stored.value.kind.is_protected_shakedex() {
7276                continue;
7277            }
7278            let expired = stored
7279                .value
7280                .expires_at_unix
7281                .is_some_and(|expiry| expiry <= now_unix);
7282            let spent = !unspent.contains(&stored.value.outpoint);
7283            let conflicted = if stored.value.expires_at_unix.is_none() {
7284                match store.load_workflow::<HnsPreparedSettlement>(stored.value.workflow_id) {
7285                    Ok(Some(workflow)) => {
7286                        let evidence = self.backend.get_transaction_evidence(
7287                            workflow.state.transaction,
7288                            binding,
7289                            Some(mempool_binding),
7290                        )?;
7291                        if evidence.binding != binding || evidence.mempool != mempool_binding {
7292                            return Err(HnsWalletError::StaleNodeSnapshot);
7293                        }
7294                        evidence.status.conflicted
7295                    }
7296                    Ok(None) => true,
7297                    Err(_) => false,
7298                }
7299            } else {
7300                false
7301            };
7302            if expired || spent || conflicted {
7303                deletes.push(EntityBatchDelete {
7304                    id: stored.id,
7305                    expected_revision: stored.revision,
7306                });
7307            }
7308        }
7309        for (workflow_id, (expected, releases_reservations)) in &name_workflows {
7310            if !*releases_reservations {
7311                let observed = observed_name_reservations.get(workflow_id);
7312                if observed.is_none_or(|observed| {
7313                    observed.len() != expected.len()
7314                        || expected.keys().any(|outpoint| !observed.contains(outpoint))
7315                }) {
7316                    return Err(HnsWalletError::InvalidWorkflow);
7317                }
7318            }
7319        }
7320        if !deletes.is_empty() {
7321            store.apply_entity_batch::<HnsInputReservation>(
7322                EntityKind::InputReservation,
7323                &[],
7324                &deletes,
7325            )?;
7326        }
7327        Ok(())
7328    }
7329
7330    fn reconcile_settlement_workflows(
7331        &self,
7332        store: &mut WalletStore,
7333        binding: SnapshotBinding,
7334        mempool_binding: MempoolSnapshotBinding,
7335        now_unix: u64,
7336    ) -> Result<Vec<WorkflowId>, HnsWalletError> {
7337        let config = self.cache_read()?.account.config.clone();
7338        let mut pending = Vec::new();
7339        for kind in [WorkflowKind::AtomicSwap, WorkflowKind::Refund] {
7340            let workflows = list_hns_prepared_settlement_workflows(store, kind)?;
7341            for mut stored in workflows {
7342                if stored.state.wallet_id != config.wallet_id
7343                    || stored.state.account_id != config.account_id
7344                    || settlement_workflow_kind(stored.state.action) != kind
7345                {
7346                    continue;
7347                }
7348                let previous_stage = stored.state.stage;
7349                let observe_transaction = settlement_requires_chain_observation(
7350                    previous_stage,
7351                    stored.irreversible_broadcast_prepared,
7352                );
7353                let next_stage = if observe_transaction {
7354                    let evidence = self.backend.get_transaction_evidence(
7355                        stored.state.transaction,
7356                        binding,
7357                        Some(mempool_binding),
7358                    )?;
7359                    if evidence.binding != binding || evidence.mempool != mempool_binding {
7360                        return Err(HnsWalletError::StaleNodeSnapshot);
7361                    }
7362                    if evidence.status.conflicted {
7363                        HnsSettlementStage::Conflicted
7364                    } else if evidence.status.confirmation_count > 0 {
7365                        HnsSettlementStage::Confirmed
7366                    } else if evidence.status.in_mempool {
7367                        HnsSettlementStage::Mempool
7368                    } else {
7369                        let (unobserved_stage, requires_rebroadcast) = unobserved_settlement_stage(
7370                            previous_stage,
7371                            stored.irreversible_broadcast_prepared,
7372                            stored.state.expires_at_unix,
7373                            now_unix,
7374                        );
7375                        if requires_rebroadcast {
7376                            pending.push(stored.id);
7377                        }
7378                        unobserved_stage
7379                    }
7380                } else {
7381                    previous_stage
7382                };
7383                let terminal_settlement = matches!(
7384                    next_stage,
7385                    HnsSettlementStage::Confirmed
7386                        | HnsSettlementStage::Conflicted
7387                        | HnsSettlementStage::Expired
7388                        | HnsSettlementStage::Cancelled
7389                );
7390                if next_stage != previous_stage {
7391                    stored.state.stage = next_stage;
7392                    let deletes = if terminal_settlement {
7393                        reservation_deletes(store, &config, stored.id)?
7394                    } else {
7395                        Vec::new()
7396                    };
7397                    let saves = if previous_stage == HnsSettlementStage::Prepared
7398                        && next_stage == HnsSettlementStage::Mempool
7399                    {
7400                        reservation_activation_saves(store, &config, stored.id, now_unix)?
7401                    } else {
7402                        Vec::new()
7403                    };
7404                    store.save_workflow_with_entity_batch(
7405                        stored.id,
7406                        kind,
7407                        stored.revision,
7408                        &stored.state,
7409                        !matches!(
7410                            next_stage,
7411                            HnsSettlementStage::Prepared
7412                                | HnsSettlementStage::Expired
7413                                | HnsSettlementStage::Cancelled
7414                        ),
7415                        now_unix,
7416                        EntityKind::InputReservation,
7417                        &saves,
7418                        &deletes,
7419                    )?;
7420                } else if terminal_settlement {
7421                    release_reservations(store, &config, stored.id)?;
7422                }
7423            }
7424        }
7425        Ok(pending)
7426    }
7427}
7428
7429fn map_shared_store_error(error: StoreError) -> HnsWalletError {
7430    match error {
7431        StoreError::Locked => HnsWalletError::StoreLocked,
7432        _ => HnsWalletError::Store,
7433    }
7434}
7435
7436fn prepare_hns_name_bulk_import(
7437    store: &WalletStore,
7438    selected: &HnsAccountRecord,
7439    requested: &[(Vec<u8>, [u8; 32])],
7440    maximum_persisted_names: usize,
7441) -> Result<HnsNameBulkImportPreparation, HnsWalletError> {
7442    if store.is_locked() {
7443        return Err(HnsWalletError::StoreLocked);
7444    }
7445    HnsAccountReadMode::OrdinaryNonValue.validate_config(&selected.config)?;
7446    let account_id = account_entity_id(&selected.config);
7447    let account = store
7448        .wallet_account::<HnsAccountRecord>(&account_id)?
7449        .ok_or(HnsWalletError::AccountConfigurationMismatch)?;
7450    if account.id.as_slice() != account_id.as_slice() || account.value != *selected {
7451        return Err(HnsWalletError::StaleAccountRead);
7452    }
7453    let names = store.list_entities_by_id_prefix::<KnownName>(
7454        EntityKind::KnownName,
7455        &account_entity_prefix(&selected.config),
7456        MAX_HISTORY_RESULTS,
7457    )?;
7458    let mut unique_hashes = BTreeSet::new();
7459    let mut unique_names = BTreeSet::new();
7460    for stored in &names {
7461        let actual_hash = hash_name(&stored.value.name)
7462            .map_err(|_| HnsWalletError::InvalidEvidence)?
7463            .into_bytes();
7464        if stored.id != namespaced_name_id(&selected.config, stored.value.name_hash)
7465            || stored.value.name_hash != actual_hash
7466            || !validate_name(&stored.value.name)
7467            || !unique_hashes.insert(stored.value.name_hash)
7468            || !unique_names.insert(stored.value.name.clone())
7469        {
7470            return Err(HnsWalletError::InvalidEvidence);
7471        }
7472    }
7473    let mut novel = 0_usize;
7474    for (name, name_hash) in requested {
7475        let expected_name_id = namespaced_name_id(&selected.config, *name_hash);
7476        match names
7477            .iter()
7478            .find(|stored| stored.id.as_slice() == expected_name_id.as_slice())
7479        {
7480            Some(stored) if stored.value.name.as_slice() != name.as_slice() => {
7481                return Err(HnsWalletError::InvalidEvidence);
7482            }
7483            Some(_) => {}
7484            None => novel = novel.checked_add(1).ok_or(HnsWalletError::HistoryLimit)?,
7485        }
7486    }
7487    if names
7488        .len()
7489        .checked_add(novel)
7490        .is_none_or(|count| count > maximum_persisted_names)
7491    {
7492        return Err(HnsWalletError::HistoryLimit);
7493    }
7494    Ok(HnsNameBulkImportPreparation { account, names })
7495}
7496
7497fn derive_hns_name_bulk_import_addresses(
7498    store: &WalletStore,
7499    preparation: &HnsNameBulkImportPreparation,
7500) -> Result<Vec<DerivedHnsAddress>, HnsWalletError> {
7501    if store.is_locked() {
7502        return Err(HnsWalletError::StoreLocked);
7503    }
7504    let config = &preparation.account.value.config;
7505    let account_id = account_entity_id(config);
7506    let current_account = store
7507        .wallet_account::<HnsAccountRecord>(&account_id)?
7508        .ok_or(HnsWalletError::StaleAccountRead)?;
7509    let current_names = store.list_entities_by_id_prefix::<KnownName>(
7510        EntityKind::KnownName,
7511        &account_entity_prefix(config),
7512        MAX_HISTORY_RESULTS,
7513    )?;
7514    if current_account != preparation.account || current_names != preparation.names {
7515        return Err(HnsWalletError::StaleAccountRead);
7516    }
7517    let addresses = derive_restore_addresses(store, &preparation.account.value, KeyRole::HnsCoin)?
7518        .into_iter()
7519        .filter(|address| address.derivation.change == 0)
7520        .collect::<Vec<_>>();
7521    validate_wallet_name_addresses(&addresses)?;
7522    Ok(addresses)
7523}
7524
7525fn imported_wallet_derivation(status: &NameOwnershipStatus) -> Option<DerivationReference> {
7526    match status {
7527        NameOwnershipStatus::WalletOwned { derivation } => Some(*derivation),
7528        NameOwnershipStatus::IncomingTransfer {
7529            recipient_derivation,
7530            ..
7531        } => Some(*recipient_derivation),
7532        NameOwnershipStatus::OutgoingTransfer {
7533            owner_derivation, ..
7534        } => Some(*owner_derivation),
7535        NameOwnershipStatus::WatchOnlyCanonicalStateDecoderUnavailable
7536        | NameOwnershipStatus::WatchOnlyOwnerTransactionUnavailable
7537        | NameOwnershipStatus::WalletContextUnavailable
7538        | NameOwnershipStatus::NoCurrentOwner
7539        | NameOwnershipStatus::NotWalletOwned => None,
7540    }
7541}
7542
7543fn rotate_imported_name_derivation(
7544    account: &mut HnsAccountRecord,
7545    name_addresses: &[DerivedHnsAddress],
7546    status: &NameOwnershipStatus,
7547) -> Result<(), HnsWalletError> {
7548    let Some(derivation) = imported_wallet_derivation(status) else {
7549        return Ok(());
7550    };
7551    if !is_wallet_name_control_derivation(derivation)
7552        || derivation.account != account.config.account_derivation_index
7553    {
7554        return Err(HnsWalletError::InvalidEvidence);
7555    }
7556    let mut exact = name_addresses.iter().filter(|address| {
7557        address.account_id == account.config.account_id && address.derivation == derivation
7558    });
7559    if exact.next().is_none() || exact.next().is_some() {
7560        return Err(HnsWalletError::InvalidEvidence);
7561    }
7562
7563    if derivation.role != KeyRole::HnsCoin {
7564        return Err(HnsWalletError::InvalidEvidence);
7565    }
7566    let (last_used_slot, next_index_slot, scan_end_slot) = (
7567        &mut account.last_used_external,
7568        &mut account.next_receive_index,
7569        &mut account.external_scan_end,
7570    );
7571    if derivation.index > *scan_end_slot {
7572        return Err(HnsWalletError::InvalidEvidence);
7573    }
7574    let last_used =
7575        last_used_slot.map_or(derivation.index, |current| current.max(derivation.index));
7576    ensure_trailing_gap(Some(last_used), account.config.restore_lookahead)?;
7577    let next_index = last_used
7578        .checked_add(1)
7579        .filter(|next| *next < MAX_RESTORE_LOOKAHEAD)
7580        .ok_or(HnsWalletError::ScanCapacityExhausted)?;
7581    let scan_end = required_scan_end(
7582        Some(last_used),
7583        *scan_end_slot,
7584        account.config.restore_lookahead,
7585    );
7586    checked_scan_address_count(&[scan_end])?;
7587    *last_used_slot = Some(last_used);
7588    *next_index_slot = (*next_index_slot).max(next_index);
7589    *scan_end_slot = (*scan_end_slot).max(scan_end);
7590    Ok(())
7591}
7592
7593fn commit_hns_name_bulk_import(
7594    store: &mut WalletStore,
7595    preparation: &HnsNameBulkImportPreparation,
7596    name_addresses: &[DerivedHnsAddress],
7597    imported: &[KnownName],
7598    now_unix: u64,
7599) -> Result<(), HnsWalletError> {
7600    if store.is_locked() {
7601        return Err(HnsWalletError::StoreLocked);
7602    }
7603    let mut imported_hashes = BTreeSet::new();
7604    for name in imported {
7605        if !validate_name(&name.name) {
7606            return Err(HnsWalletError::InvalidEvidence);
7607        }
7608        let imported_hash = hash_name(&name.name)
7609            .map_err(|_| HnsWalletError::InvalidEvidence)?
7610            .into_bytes();
7611        if imported_hash != name.name_hash || !imported_hashes.insert(imported_hash) {
7612            return Err(HnsWalletError::InvalidEvidence);
7613        }
7614    }
7615    let account_id = account_entity_id(&preparation.account.value.config);
7616    let current_account = store
7617        .wallet_account::<HnsAccountRecord>(&account_id)?
7618        .ok_or(HnsWalletError::StaleAccountRead)?;
7619    let current_names = store.list_entities_by_id_prefix::<KnownName>(
7620        EntityKind::KnownName,
7621        &account_entity_prefix(&preparation.account.value.config),
7622        MAX_HISTORY_RESULTS,
7623    )?;
7624    if current_account != preparation.account || current_names != preparation.names {
7625        return Err(HnsWalletError::StaleAccountRead);
7626    }
7627
7628    let mut account = preparation.account.value.clone();
7629    let mut name_saves = Vec::with_capacity(imported.len());
7630    for name in imported {
7631        rotate_imported_name_derivation(&mut account, name_addresses, &name.ownership_status)?;
7632        let name_id = namespaced_name_id(&preparation.account.value.config, name.name_hash);
7633        let expected_revision = preparation
7634            .names
7635            .iter()
7636            .find(|stored| stored.id.as_slice() == name_id.as_slice())
7637            .map_or(0, |stored| stored.revision);
7638        name_saves.push(EntityBatchSave {
7639            id: name_id.to_vec(),
7640            expected_revision,
7641            value: name.clone(),
7642            updated_at_unix: now_unix,
7643        });
7644    }
7645    let account_save = EntityBatchSave {
7646        id: preparation.account.id.clone(),
7647        expected_revision: preparation.account.revision,
7648        value: account,
7649        updated_at_unix: now_unix,
7650    };
7651    store
7652        .apply_account_and_entity_batch(&account_save, EntityKind::KnownName, &name_saves, &[])
7653        .map(|_| ())
7654        .map_err(|error| match error {
7655            StoreError::Locked => HnsWalletError::StoreLocked,
7656            StoreError::StaleRevision { .. } => HnsWalletError::StaleAccountRead,
7657            _ => HnsWalletError::Store,
7658        })
7659}
7660
7661fn prepare_hns_account_read(
7662    store: &mut WalletStore,
7663    selected: &HnsAccountRecord,
7664    mode: HnsAccountReadMode,
7665    now_unix: u64,
7666) -> Result<HnsReadPreparation, HnsWalletError> {
7667    if store.is_locked() {
7668        return Err(HnsWalletError::StoreLocked);
7669    }
7670    mode.validate_config(&selected.config)?;
7671    let account_id = account_entity_id(&selected.config);
7672    let stored = store
7673        .wallet_account::<HnsAccountRecord>(&account_id)?
7674        .ok_or(HnsWalletError::AccountConfigurationMismatch)?;
7675    if stored.id.as_slice() != account_id.as_slice() || stored.value != *selected {
7676        return Err(HnsWalletError::StaleAccountRead);
7677    }
7678
7679    // Persist the same crash-safe Shakedex discovery fence used by the full
7680    // runtime before deriving or querying any separated seller-key script.
7681    let mut fenced_account = stored.value;
7682    fenced_account.shakedex_scan_in_progress = true;
7683    let account_revision =
7684        store.save_wallet_account(&account_id, stored.revision, &fenced_account, now_unix)?;
7685    let fenced = store
7686        .wallet_account::<HnsAccountRecord>(&account_id)?
7687        .ok_or(HnsWalletError::StaleAccountRead)?;
7688    if fenced.id.as_slice() != account_id.as_slice()
7689        || fenced.revision != account_revision
7690        || fenced.value != fenced_account
7691    {
7692        return Err(HnsWalletError::StaleAccountRead);
7693    }
7694    let allocated_next = match mode {
7695        HnsAccountReadMode::OrdinaryNonValue => {
7696            shakedex_key::allocation_next_index(store, &fenced_account.config)
7697        }
7698        HnsAccountReadMode::PersistedRecoveryReadOnly => {
7699            shakedex_key::allocation_next_index_for_persisted_recovery_read(
7700                store,
7701                &fenced_account.config,
7702            )
7703        }
7704        HnsAccountReadMode::LifecycleStructural => {
7705            return Err(HnsWalletError::RuntimeIntegrationUnavailable);
7706        }
7707    }
7708    .map_err(map_shakedex_restore_error)?;
7709    let mut scan_account = fenced_account.clone();
7710    normalize_restore_scan_account(&mut scan_account, allocated_next)?;
7711    let prefix = account_entity_prefix(&fenced_account.config);
7712    let recovery_row = store
7713        .hns_recovery_state::<HnsRecoveryState>(&recovery_entity_id(&fenced_account.config))?;
7714    let recovery = recovery_row
7715        .as_ref()
7716        .map_or_else(HnsRecoveryState::default, |stored| stored.value.clone());
7717    if recovery.checkpoints.len() > MAX_RECOVERY_CHECKPOINTS
7718        || !recovery
7719            .checkpoints
7720            .windows(2)
7721            .all(|pair| pair[0].height < pair[1].height)
7722    {
7723        return Err(HnsWalletError::InvalidEvidence);
7724    }
7725    let coins = store.list_entities_by_id_prefix::<TrackedHnsCoin>(
7726        EntityKind::HnsUtxo,
7727        &prefix,
7728        MAX_WALLET_COINS,
7729    )?;
7730    for stored in &coins {
7731        let expected = namespaced_outpoint_id(&fenced_account.config, stored.value.coin.outpoint);
7732        if stored.id.as_slice() != expected.as_slice()
7733            || stored.value.derivation.account != fenced_account.config.account_derivation_index
7734            || stored.value.to_canonical_coin().is_err()
7735        {
7736            return Err(HnsWalletError::InvalidEvidence);
7737        }
7738    }
7739    let transactions = store.list_entities_by_id_prefix::<HnsTransactionRecord>(
7740        EntityKind::HnsTransaction,
7741        &prefix,
7742        MAX_HISTORY_RESULTS,
7743    )?;
7744    for stored in &transactions {
7745        let expected = namespaced_transaction_id(&fenced_account.config, stored.value.summary.txid);
7746        if stored.id.as_slice() != expected.as_slice()
7747            || stored.value.summary.module != ModuleId::Handshake
7748            || decode_transaction_for_id(&stored.value.raw, stored.value.summary.txid).is_err()
7749        {
7750            return Err(HnsWalletError::InvalidEvidence);
7751        }
7752    }
7753    let names = store.list_entities_by_id_prefix::<KnownName>(
7754        EntityKind::KnownName,
7755        &prefix,
7756        MAX_HISTORY_RESULTS,
7757    )?;
7758    for stored in &names {
7759        let expected = namespaced_name_id(&fenced_account.config, stored.value.name_hash);
7760        let actual_hash = hash_name(&stored.value.name)
7761            .map_err(|_| HnsWalletError::InvalidEvidence)?
7762            .into_bytes();
7763        if stored.id.as_slice() != expected.as_slice()
7764            || actual_hash != stored.value.name_hash
7765            || !validate_name(&stored.value.name)
7766        {
7767            return Err(HnsWalletError::InvalidEvidence);
7768        }
7769    }
7770    Ok(HnsReadPreparation {
7771        fenced_account,
7772        scan_account,
7773        account_revision,
7774        recovery,
7775        recovery_row,
7776        coins,
7777        transactions,
7778        names,
7779    })
7780}
7781
7782fn verify_hns_read_account_fence(
7783    store: &WalletStore,
7784    preparation: &HnsReadPreparation,
7785) -> Result<(), HnsWalletError> {
7786    if store.is_locked() {
7787        return Err(HnsWalletError::StoreLocked);
7788    }
7789    let account_id = account_entity_id(&preparation.fenced_account.config);
7790    let stored = store
7791        .wallet_account::<HnsAccountRecord>(&account_id)?
7792        .ok_or(HnsWalletError::StaleAccountRead)?;
7793    if stored.id.as_slice() != account_id.as_slice()
7794        || stored.revision != preparation.account_revision
7795        || stored.value != preparation.fenced_account
7796    {
7797        return Err(HnsWalletError::StaleAccountRead);
7798    }
7799    Ok(())
7800}
7801
7802fn scan_hns_account_read<B: HnsBackend>(
7803    backend: &B,
7804    store: &SharedWalletStore,
7805    preparation: &HnsReadPreparation,
7806    expected_binding: SnapshotBinding,
7807) -> Result<HnsReadScan, HnsWalletError> {
7808    scan_restore_snapshot(
7809        backend,
7810        preparation.scan_account.clone(),
7811        expected_binding.tip,
7812        Some(expected_binding),
7813        |account| {
7814            store
7815                .with_store(|store| {
7816                    Ok((|| {
7817                        verify_hns_read_account_fence(store, preparation)?;
7818                        Ok([
7819                            derive_restore_addresses(store, account, KeyRole::HnsCoin)?,
7820                            derive_restore_addresses(store, account, KeyRole::HnsShakedex)?,
7821                        ])
7822                    })())
7823                })
7824                .map_err(map_shared_store_error)?
7825        },
7826    )
7827}
7828
7829fn hns_read_common_ancestor<B: HnsBackend>(
7830    backend: &B,
7831    recovery: &HnsRecoveryState,
7832    binding: SnapshotBinding,
7833    birthday_height: u64,
7834) -> Result<Option<u64>, HnsWalletError> {
7835    if recovery.last_tip.is_none() {
7836        return Ok(None);
7837    }
7838    for checkpoint in recovery.checkpoints.iter().rev() {
7839        if checkpoint.height > binding.tip.height {
7840            continue;
7841        }
7842        let evidence = backend.get_block_hash(checkpoint.height, binding)?;
7843        if evidence.binding != binding || evidence.height != checkpoint.height {
7844            return Err(HnsWalletError::StaleNodeSnapshot);
7845        }
7846        if evidence.block_hash == Some(checkpoint.block_hash) {
7847            return Ok(Some(checkpoint.height));
7848        }
7849    }
7850    Ok(account_birthday_ancestor(birthday_height))
7851}
7852
7853fn verify_hns_read_chain_identity<B: HnsBackend>(
7854    backend: &B,
7855    network: HnsNetwork,
7856    binding: SnapshotBinding,
7857) -> Result<(), HnsWalletError> {
7858    let (_, expected_genesis_hash) = name_workflow::expected_chain_identity(network)?;
7859    let genesis = backend.get_block_hash(0, binding)?;
7860    if genesis.binding != binding || genesis.height != 0 {
7861        return Err(HnsWalletError::StaleNodeSnapshot);
7862    }
7863    if genesis.block_hash != Some(expected_genesis_hash) {
7864        return Err(HnsWalletError::InvalidEvidence);
7865    }
7866    Ok(())
7867}
7868
7869fn hns_read_checkpoints<B: HnsBackend>(
7870    backend: &B,
7871    binding: SnapshotBinding,
7872    birthday_height: u64,
7873) -> Result<Vec<HnsChainCheckpoint>, HnsWalletError> {
7874    if birthday_height > binding.tip.height {
7875        return Err(HnsWalletError::InvalidEvidence);
7876    }
7877    let start = binding
7878        .tip
7879        .height
7880        .saturating_sub((MAX_RECOVERY_CHECKPOINTS - 1) as u64)
7881        .max(birthday_height);
7882    let mut checkpoints = Vec::new();
7883    for height in start..=binding.tip.height {
7884        let block_hash = if height == binding.tip.height {
7885            Some(binding.tip.block_hash)
7886        } else {
7887            let evidence = backend.get_block_hash(height, binding)?;
7888            if evidence.binding != binding || evidence.height != height {
7889                return Err(HnsWalletError::StaleNodeSnapshot);
7890            }
7891            evidence.block_hash
7892        }
7893        .ok_or(HnsWalletError::InvalidEvidence)?;
7894        checkpoints.push(HnsChainCheckpoint { height, block_hash });
7895    }
7896    Ok(checkpoints)
7897}
7898
7899fn hns_read_receive_target(
7900    account: &HnsAccountRecord,
7901    addresses: &[DerivedHnsAddress],
7902) -> Result<ReceiveTarget, HnsWalletError> {
7903    let address = addresses
7904        .iter()
7905        .find(|address| {
7906            address.account_id == account.config.account_id
7907                && address.derivation.role == KeyRole::HnsCoin
7908                && address.derivation.account == account.config.account_derivation_index
7909                && address.derivation.change == 0
7910                && address.derivation.index == account.next_receive_index
7911        })
7912        .ok_or(HnsWalletError::InvalidEvidence)?;
7913    let target = ReceiveTarget {
7914        module: ModuleId::Handshake,
7915        account: account.config.account_id,
7916        display: address.address.clone(),
7917        derivation_index: address.derivation.index,
7918    };
7919    target
7920        .validate()
7921        .map_err(|_| HnsWalletError::InvalidEvidence)?;
7922    Ok(target)
7923}
7924
7925fn hns_read_name_receive_target(
7926    account: &HnsAccountRecord,
7927    addresses: &[DerivedHnsAddress],
7928) -> Result<HnsNameReceiveTarget, HnsWalletError> {
7929    let payment = hns_read_receive_target(account, addresses)?;
7930    hns_name_receive_target_from_payment(&payment)
7931}
7932
7933fn send_is_within_propagation_grace(
7934    stage: HnsSendStage,
7935    updated_at_unix: u64,
7936    now_unix: u64,
7937) -> bool {
7938    stage == HnsSendStage::Broadcast
7939        && now_unix.saturating_sub(updated_at_unix) < SEND_PROPAGATION_GRACE_SECONDS
7940}
7941
7942fn retain_or_insert_pending_wallet_activity_for_config(
7943    store: &WalletStore,
7944    config: &HnsRuntimeConfig,
7945    transactions: &mut Vec<HnsTransactionRecord>,
7946) -> Result<(), HnsWalletError> {
7947    let pending = store
7948        .list_workflows_complete::<HnsSendWorkflow>(WorkflowKind::HnsSend, MAX_HISTORY_RESULTS)?
7949        .into_iter()
7950        .filter(|stored| {
7951            stored.state.plan.wallet_id == config.wallet_id
7952                && stored.state.plan.account_id == config.account_id
7953                && matches!(
7954                    stored.state.stage,
7955                    HnsSendStage::Authorized
7956                        | HnsSendStage::Broadcast
7957                        | HnsSendStage::Mempool
7958                        | HnsSendStage::RequiresRebroadcast
7959                        | HnsSendStage::Abandoned
7960                )
7961        })
7962        .collect::<Vec<_>>();
7963    for stored in pending {
7964        let txid = stored
7965            .state
7966            .transaction
7967            .ok_or(HnsWalletError::InvalidWorkflow)?;
7968        if let Some(transaction) = transactions
7969            .iter_mut()
7970            .find(|transaction| transaction.summary.txid == txid)
7971        {
7972            let status = match stored.state.stage {
7973                HnsSendStage::Authorized => LocalTransactionStatus::Authorized,
7974                HnsSendStage::Broadcast => LocalTransactionStatus::Broadcast,
7975                HnsSendStage::Mempool => LocalTransactionStatus::Mempool,
7976                HnsSendStage::RequiresRebroadcast | HnsSendStage::Abandoned => {
7977                    LocalTransactionStatus::Dropped
7978                }
7979                _ => return Err(HnsWalletError::InvalidWorkflow),
7980            };
7981            if transaction.summary.status == LocalTransactionStatus::Dropped {
7982                transaction.summary.status = status;
7983            }
7984            continue;
7985        }
7986        let status = match stored.state.stage {
7987            HnsSendStage::Authorized => LocalTransactionStatus::Authorized,
7988            HnsSendStage::Broadcast => LocalTransactionStatus::Broadcast,
7989            HnsSendStage::Mempool => LocalTransactionStatus::Mempool,
7990            HnsSendStage::RequiresRebroadcast | HnsSendStage::Abandoned => {
7991                LocalTransactionStatus::Dropped
7992            }
7993            _ => return Err(HnsWalletError::InvalidWorkflow),
7994        };
7995        transactions.push(pending_send_record(&stored, status)?);
7996    }
7997    for kind in [WorkflowKind::NameTransfer, WorkflowKind::NameFinalize] {
7998        let pending = store
7999            .list_workflows_complete::<HnsNameWorkflow>(kind, MAX_HISTORY_RESULTS)?
8000            .into_iter()
8001            .filter(|stored| {
8002                stored.state.plan.wallet_id == config.wallet_id
8003                    && stored.state.plan.account_id == config.account_id
8004            });
8005        for stored in pending {
8006            let Some(status) = pending_name_transaction_status(stored.state.stage) else {
8007                continue;
8008            };
8009            let txid = stored
8010                .state
8011                .transaction
8012                .ok_or(HnsWalletError::InvalidWorkflow)?;
8013            if let Some(transaction) = transactions
8014                .iter_mut()
8015                .find(|transaction| transaction.summary.txid == txid)
8016            {
8017                if transaction.summary.status == LocalTransactionStatus::Dropped {
8018                    transaction.summary.status = status;
8019                }
8020                continue;
8021            }
8022            transactions.push(pending_name_record(&stored, status)?);
8023        }
8024    }
8025    if transactions.len() > MAX_HISTORY_RESULTS {
8026        return Err(HnsWalletError::HistoryLimit);
8027    }
8028    transactions.sort_by(|left, right| {
8029        right
8030            .summary
8031            .block_height
8032            .cmp(&left.summary.block_height)
8033            .then_with(|| {
8034                right
8035                    .summary
8036                    .first_seen_unix
8037                    .cmp(&left.summary.first_seen_unix)
8038            })
8039            .then_with(|| left.summary.txid.cmp(&right.summary.txid))
8040    });
8041    Ok(())
8042}
8043
8044fn pending_name_transaction_status(stage: NameOperationState) -> Option<LocalTransactionStatus> {
8045    match stage {
8046        NameOperationState::Authorized => Some(LocalTransactionStatus::Authorized),
8047        NameOperationState::Broadcast => Some(LocalTransactionStatus::Broadcast),
8048        NameOperationState::Mempool => Some(LocalTransactionStatus::Mempool),
8049        NameOperationState::RequiresRebroadcast | NameOperationState::ReapprovalRequired => {
8050            Some(LocalTransactionStatus::Dropped)
8051        }
8052        NameOperationState::Conflicted => Some(LocalTransactionStatus::Conflicted),
8053        NameOperationState::Prepared
8054        | NameOperationState::TransferLocked
8055        | NameOperationState::FinalizeEligible
8056        | NameOperationState::Finalized
8057        | NameOperationState::Updated
8058        | NameOperationState::TransferCancelled
8059        | NameOperationState::Expired
8060        | NameOperationState::Cancelled => None,
8061    }
8062}
8063
8064fn pending_name_record(
8065    stored: &StoredWorkflow<HnsNameWorkflow>,
8066    status: LocalTransactionStatus,
8067) -> Result<HnsTransactionRecord, HnsWalletError> {
8068    if !matches!(
8069        status,
8070        LocalTransactionStatus::Authorized
8071            | LocalTransactionStatus::Broadcast
8072            | LocalTransactionStatus::Mempool
8073            | LocalTransactionStatus::Conflicted
8074            | LocalTransactionStatus::Dropped
8075    ) {
8076        return Err(HnsWalletError::InvalidWorkflow);
8077    }
8078    let txid = stored
8079        .state
8080        .transaction
8081        .ok_or(HnsWalletError::InvalidWorkflow)?;
8082    let raw = stored
8083        .state
8084        .signed_transaction
8085        .clone()
8086        .ok_or(HnsWalletError::InvalidWorkflow)?;
8087    decode_transaction_for_id(&raw, txid)?;
8088    Ok(HnsTransactionRecord {
8089        summary: TransactionSummary {
8090            module: ModuleId::Handshake,
8091            txid,
8092            status,
8093            // The name value is preserved by TRANSFER/FINALIZE and is not an
8094            // ordinary spendable balance. Only the network fee is a wallet
8095            // value loss for this activity row.
8096            net_amount: SignedBaseUnits {
8097                negative: true,
8098                magnitude: stored.state.plan.fee,
8099            },
8100            fee: Some(stored.state.plan.fee),
8101            block_height: stored
8102                .state
8103                .last_verified_inclusion
8104                .map(|inclusion| inclusion.height),
8105            first_seen_unix: Some(stored.updated_at_unix),
8106            confirmation_count: 0,
8107        },
8108        raw,
8109        inclusion: stored.state.last_verified_inclusion,
8110    })
8111}
8112
8113fn pending_send_record(
8114    stored: &StoredWorkflow<HnsSendWorkflow>,
8115    status: LocalTransactionStatus,
8116) -> Result<HnsTransactionRecord, HnsWalletError> {
8117    if !matches!(
8118        status,
8119        LocalTransactionStatus::Authorized
8120            | LocalTransactionStatus::Broadcast
8121            | LocalTransactionStatus::Mempool
8122            | LocalTransactionStatus::Dropped
8123    ) {
8124        return Err(HnsWalletError::InvalidWorkflow);
8125    }
8126    let txid = stored
8127        .state
8128        .transaction
8129        .ok_or(HnsWalletError::InvalidWorkflow)?;
8130    let raw = stored
8131        .state
8132        .signed_transaction
8133        .clone()
8134        .ok_or(HnsWalletError::InvalidWorkflow)?;
8135    decode_transaction_for_id(&raw, txid)?;
8136    let magnitude = stored
8137        .state
8138        .plan
8139        .amount
8140        .get()
8141        .checked_add(stored.state.plan.fee.get())
8142        .ok_or(HnsWalletError::Arithmetic)?;
8143    Ok(HnsTransactionRecord {
8144        summary: TransactionSummary {
8145            module: ModuleId::Handshake,
8146            txid,
8147            status,
8148            net_amount: SignedBaseUnits {
8149                negative: true,
8150                magnitude: BaseUnits::new(magnitude),
8151            },
8152            fee: Some(stored.state.plan.fee),
8153            block_height: None,
8154            first_seen_unix: Some(stored.updated_at_unix),
8155            confirmation_count: 0,
8156        },
8157        raw,
8158        inclusion: None,
8159    })
8160}
8161
8162fn reconcile_hns_read_transactions<B: HnsBackend>(
8163    backend: &B,
8164    history: &[HistoryEntry],
8165    addresses: &[DerivedHnsAddress],
8166    binding: SnapshotBinding,
8167    mempool: MempoolSnapshotBinding,
8168    common_ancestor: Option<u64>,
8169    previous_records: &[HnsTransactionRecord],
8170) -> Result<Vec<HnsTransactionRecord>, HnsWalletError> {
8171    let mut history = coalesce_transaction_history(history)?;
8172    let observed_txids: BTreeSet<TransactionHash> =
8173        history.iter().map(|entry| entry.txid).collect();
8174    if addresses.is_empty()
8175        || addresses.len() > MAX_RESTORE_ADDRESS_RECORDS
8176        || addresses
8177            .iter()
8178            .any(|address| restore_derivation_key(address.derivation).is_err())
8179    {
8180        return Err(HnsWalletError::InvalidEvidence);
8181    }
8182    let programs: BTreeSet<Vec<u8>> = addresses
8183        .iter()
8184        .map(|address| address.program.clone())
8185        .collect();
8186    if programs.len() != addresses.len()
8187        || addresses
8188            .iter()
8189            .any(|address| validate_restore_program(address.derivation, &address.program).is_err())
8190    {
8191        return Err(HnsWalletError::InvalidEvidence);
8192    }
8193    let previous: BTreeMap<TransactionHash, TransactionSummary> = previous_records
8194        .iter()
8195        .map(|record| (record.summary.txid, record.summary.clone()))
8196        .collect();
8197    for summary in previous.values() {
8198        if !observed_txids.contains(&summary.txid) {
8199            history.push(HistoryEntry {
8200                txid: summary.txid,
8201                height: summary.block_height,
8202                block_hash: None,
8203                transaction_position: None,
8204                spent: false,
8205                first_seen_unix: summary.first_seen_unix,
8206                script_index: 0,
8207            });
8208        }
8209    }
8210    if history.len() > MAX_HISTORY_RESULTS {
8211        return Err(HnsWalletError::HistoryLimit);
8212    }
8213    let persisted_raw: BTreeMap<TransactionHash, Vec<u8>> = previous_records
8214        .iter()
8215        .map(|record| (record.summary.txid, record.raw.clone()))
8216        .collect();
8217    let mut raw_cache = BTreeMap::new();
8218    let mut records = Vec::with_capacity(history.len());
8219    for entry in &history {
8220        let evidence = backend.get_transaction_evidence(entry.txid, binding, Some(mempool))?;
8221        if evidence.binding != binding || evidence.mempool != mempool {
8222            return Err(HnsWalletError::StaleNodeSnapshot);
8223        }
8224        let raw = match evidence.raw {
8225            Some(raw) => raw,
8226            None => persisted_raw
8227                .get(&entry.txid)
8228                .cloned()
8229                .ok_or(HnsWalletError::InvalidEvidence)?,
8230        };
8231        let transaction = decode_transaction_for_id(&raw, entry.txid)?;
8232        raw_cache.insert(entry.txid, transaction.clone());
8233        let competing_spender =
8234            hns_read_has_competing_spender(backend, entry.txid, &transaction, binding)?;
8235        validate_inclusion(
8236            entry,
8237            evidence.status,
8238            evidence.inclusion,
8239            binding.tip,
8240            observed_txids.contains(&entry.txid),
8241        )?;
8242        let (net_amount, fee) = transaction_value_effect(
8243            backend,
8244            &transaction,
8245            &programs,
8246            &mut raw_cache,
8247            &persisted_raw,
8248            binding,
8249            mempool,
8250        )?;
8251        let status = if evidence.status.conflicted || competing_spender {
8252            LocalTransactionStatus::Conflicted
8253        } else if evidence.status.confirmation_count > 0 {
8254            LocalTransactionStatus::Confirmed
8255        } else if evidence.status.in_mempool {
8256            LocalTransactionStatus::Mempool
8257        } else if previous.get(&entry.txid).is_some_and(|old| {
8258            old.status == LocalTransactionStatus::Confirmed
8259                && old
8260                    .block_height
8261                    .is_some_and(|height| common_ancestor.is_none_or(|ancestor| height > ancestor))
8262        }) {
8263            LocalTransactionStatus::Reorged
8264        } else {
8265            LocalTransactionStatus::Dropped
8266        };
8267        records.push(HnsTransactionRecord {
8268            summary: TransactionSummary {
8269                module: ModuleId::Handshake,
8270                txid: entry.txid,
8271                status,
8272                net_amount,
8273                fee,
8274                block_height: evidence.inclusion.map(|inclusion| inclusion.height),
8275                first_seen_unix: entry.first_seen_unix,
8276                confirmation_count: evidence.status.confirmation_count,
8277            },
8278            raw,
8279            inclusion: evidence.inclusion,
8280        });
8281    }
8282    records.sort_by(|left, right| {
8283        right
8284            .summary
8285            .block_height
8286            .cmp(&left.summary.block_height)
8287            .then_with(|| {
8288                right
8289                    .summary
8290                    .first_seen_unix
8291                    .cmp(&left.summary.first_seen_unix)
8292            })
8293            .then_with(|| left.summary.txid.cmp(&right.summary.txid))
8294    });
8295    Ok(records)
8296}
8297
8298fn hns_read_has_competing_spender<B: HnsBackend>(
8299    backend: &B,
8300    transaction_id: TransactionHash,
8301    transaction: &Transaction,
8302    binding: SnapshotBinding,
8303) -> Result<bool, HnsWalletError> {
8304    let outpoints = transaction
8305        .inputs
8306        .iter()
8307        .filter(|input| !input.previous_output.is_null())
8308        .map(|input| HnsOutpoint {
8309            transaction: TransactionHash::new(input.previous_output.transaction_hash.into_bytes()),
8310            output_index: input.previous_output.index,
8311        })
8312        .collect::<Vec<_>>();
8313    has_competing_spender_in_batches(backend, &outpoints, binding, transaction_id)
8314}
8315
8316fn revalidate_hns_read_names<B: HnsBackend>(
8317    backend: &B,
8318    stored_names: &[StoredEntity<KnownName>],
8319    addresses: &[DerivedHnsAddress],
8320    binding: SnapshotBinding,
8321) -> Result<Vec<KnownName>, HnsWalletError> {
8322    reconcile_hns_read_names(backend, stored_names, addresses, &[], binding)
8323}
8324
8325fn reconcile_hns_read_names<B: HnsBackend>(
8326    backend: &B,
8327    stored_names: &[StoredEntity<KnownName>],
8328    addresses: &[DerivedHnsAddress],
8329    coins: &[TrackedHnsCoin],
8330    binding: SnapshotBinding,
8331) -> Result<Vec<KnownName>, HnsWalletError> {
8332    if stored_names.len() > MAX_HISTORY_RESULTS {
8333        return Err(HnsWalletError::HistoryLimit);
8334    }
8335    let wallet_name_addresses = addresses
8336        .iter()
8337        .filter(|address| is_wallet_name_control_derivation(address.derivation))
8338        .cloned()
8339        .collect::<Vec<_>>();
8340    validate_wallet_name_addresses(&wallet_name_addresses)?;
8341    let wallet_name_addresses_by_derivation = wallet_name_addresses
8342        .iter()
8343        .map(|address| (address.derivation, address))
8344        .collect::<BTreeMap<_, _>>();
8345    let mut discovered = BTreeMap::new();
8346    for coin in coins {
8347        if !is_wallet_name_control_derivation(coin.derivation) {
8348            continue;
8349        }
8350        let canonical_coin = coin.to_canonical_coin()?;
8351        if canonical_coin.covenant.kind != CovenantKind::Finalize {
8352            continue;
8353        }
8354        let address = wallet_name_addresses_by_derivation
8355            .get(&coin.derivation)
8356            .copied()
8357            .ok_or(HnsWalletError::InvalidEvidence)?;
8358        if address.program != coin.address_program
8359            || canonical_coin.address.version != 0
8360            || canonical_coin.address.hash != address.program
8361        {
8362            return Err(HnsWalletError::InvalidEvidence);
8363        }
8364        let finalize = FinalizeCovenant::try_from(&canonical_coin.covenant)
8365            .map_err(|_| HnsWalletError::InvalidEvidence)?;
8366        let name_hash = finalize.name_hash.into_bytes();
8367        let evidence = backend.get_active_name_owner_coin(name_hash, binding)?;
8368        let state = validate_active_name_owner_coin_evidence(&evidence, name_hash, binding)?;
8369        if evidence.owner_coin != canonical_coin
8370            || state.name != finalize.name
8371            || state.height != finalize.start_height
8372        {
8373            return Err(HnsWalletError::InvalidEvidence);
8374        }
8375        let current_raw_resource = state.resource_data.clone();
8376        let resource_status = if current_raw_resource.is_empty() {
8377            NameResourceStatus::Empty
8378        } else if state.resource().is_ok() {
8379            NameResourceStatus::CanonicalDecoded
8380        } else {
8381            NameResourceStatus::CanonicalOpaque
8382        };
8383        let current_owner_outpoint = HnsOutpoint {
8384            transaction: TransactionHash::new(
8385                canonical_coin.outpoint.transaction_hash.into_bytes(),
8386            ),
8387            output_index: canonical_coin.outpoint.index,
8388        };
8389        let known_name = KnownName {
8390            name: state.name.clone(),
8391            name_hash,
8392            proof_height: binding.tip.height,
8393            unbound_proof_owner_outpoint: None,
8394            unbound_current_owner_outpoint: Some(current_owner_outpoint),
8395            proof_state: None,
8396            current_state: Some(evidence.current_state),
8397            canonical_proof_state: None,
8398            canonical_current_state: Some(CanonicalNameStateSummary {
8399                owner_outpoint: Some(current_owner_outpoint),
8400                value: state.value.get(),
8401                highest: state.highest.get(),
8402                start_height: state.height.get(),
8403                renewal_height: state.renewal.get(),
8404                transfer_height: state.transfer.get(),
8405                revoked_height: state.revoked.get(),
8406                claimed_height: state.claimed.get(),
8407                renewals: state.renewals,
8408                registered: state.registered,
8409                expired: state.expired,
8410                weak: state.weak,
8411            }),
8412            current_raw_resource: Some(current_raw_resource),
8413            resource_status,
8414            ownership_status: NameOwnershipStatus::WalletOwned {
8415                derivation: coin.derivation,
8416            },
8417        };
8418        if discovered.insert(name_hash, known_name).is_some()
8419            || discovered.len() > MAX_HISTORY_RESULTS
8420        {
8421            return Err(HnsWalletError::InvalidEvidence);
8422        }
8423    }
8424
8425    let stored_hashes = stored_names
8426        .iter()
8427        .map(|stored| stored.value.name_hash)
8428        .collect::<BTreeSet<_>>();
8429    if stored_hashes.len() != stored_names.len() {
8430        return Err(HnsWalletError::InvalidEvidence);
8431    }
8432    let novel_names = discovered
8433        .keys()
8434        .filter(|name_hash| !stored_hashes.contains(*name_hash))
8435        .count();
8436    let capacity = stored_names
8437        .len()
8438        .checked_add(novel_names)
8439        .ok_or(HnsWalletError::HistoryLimit)?;
8440    if capacity > MAX_HISTORY_RESULTS {
8441        return Err(HnsWalletError::HistoryLimit);
8442    }
8443    let mut names = Vec::with_capacity(capacity);
8444    for stored in stored_names {
8445        let current = if let Some(discovered) = discovered.remove(&stored.value.name_hash) {
8446            if discovered.name != stored.value.name {
8447                return Err(HnsWalletError::InvalidEvidence);
8448            }
8449            discovered
8450        } else {
8451            validated_name_evidence(
8452                backend,
8453                &stored.value.name,
8454                binding,
8455                Some(&wallet_name_addresses),
8456            )?
8457            .known_name
8458        };
8459        if current.name_hash != stored.value.name_hash || current.proof_height != binding.tip.height
8460        {
8461            return Err(HnsWalletError::InvalidEvidence);
8462        }
8463        names.push(current);
8464    }
8465    names.extend(discovered.into_values());
8466    names.sort_by(|left, right| {
8467        left.name
8468            .cmp(&right.name)
8469            .then_with(|| left.name_hash.cmp(&right.name_hash))
8470    });
8471    Ok(names)
8472}
8473
8474fn verify_hns_read_snapshot_current<B: HnsBackend>(
8475    backend: &B,
8476    branch_scripts: &[Vec<WalletAddressKey>; 2],
8477    binding: SnapshotBinding,
8478    mempool: MempoolSnapshotBinding,
8479) -> Result<(), HnsWalletError> {
8480    for scripts in branch_scripts {
8481        if scripts.is_empty() || scripts.len() > MAX_RESTORE_SCRIPTS_PER_QUERY {
8482            return Err(HnsWalletError::InvalidEvidence);
8483        }
8484        let confirmed = backend.get_confirmed_wallet_page(ConfirmedWalletPageRequest {
8485            scripts,
8486            expected_tip: binding.tip,
8487            expected_epoch: Some(binding.chain_epoch),
8488            cursor: None,
8489            limit: 1,
8490        })?;
8491        if confirmed.binding != binding
8492            || confirmed
8493                .history
8494                .len()
8495                .saturating_add(confirmed.utxos.len())
8496                > 1
8497        {
8498            return Err(HnsWalletError::StaleNodeSnapshot);
8499        }
8500        let current_mempool = backend.get_mempool_wallet_page(MempoolWalletPageRequest {
8501            scripts,
8502            binding,
8503            expected_mempool: Some(mempool),
8504            cursor: None,
8505            limit: 1,
8506        })?;
8507        if current_mempool.binding != binding
8508            || current_mempool.mempool != mempool
8509            || current_mempool.history.len() > 1
8510        {
8511            return Err(HnsWalletError::StaleNodeSnapshot);
8512        }
8513    }
8514    Ok(())
8515}
8516
8517#[allow(clippy::too_many_arguments)]
8518fn commit_hns_account_read(
8519    store: &mut WalletStore,
8520    preparation: &HnsReadPreparation,
8521    account: &HnsAccountRecord,
8522    addresses: &[DerivedHnsAddress],
8523    coins: &[TrackedHnsCoin],
8524    transactions: &[HnsTransactionRecord],
8525    names: &[KnownName],
8526    recovery: &HnsRecoveryState,
8527    now_unix: u64,
8528) -> Result<(), HnsWalletError> {
8529    verify_hns_read_account_fence(store, preparation)?;
8530    let prefix = account_entity_prefix(&preparation.fenced_account.config);
8531    let current_coins = store.list_entities_by_id_prefix::<TrackedHnsCoin>(
8532        EntityKind::HnsUtxo,
8533        &prefix,
8534        MAX_WALLET_COINS,
8535    )?;
8536    let current_transactions = store.list_entities_by_id_prefix::<HnsTransactionRecord>(
8537        EntityKind::HnsTransaction,
8538        &prefix,
8539        MAX_HISTORY_RESULTS,
8540    )?;
8541    let current_names = store.list_entities_by_id_prefix::<KnownName>(
8542        EntityKind::KnownName,
8543        &prefix,
8544        MAX_HISTORY_RESULTS,
8545    )?;
8546    let current_recovery = store.hns_recovery_state::<HnsRecoveryState>(&recovery_entity_id(
8547        &preparation.fenced_account.config,
8548    ))?;
8549    if current_coins != preparation.coins
8550        || current_transactions != preparation.transactions
8551        || current_names != preparation.names
8552        || current_recovery != preparation.recovery_row
8553        || !same_account_identity(&account.config, &preparation.fenced_account.config)
8554        || account.config != preparation.fenced_account.config
8555        || account.shakedex_scan_in_progress
8556        || !account.shakedex_scan_complete
8557    {
8558        return Err(HnsWalletError::StaleAccountRead);
8559    }
8560
8561    // A crash before the final WalletAccount save leaves the durable discovery
8562    // fence set. A later synchronization re-authenticates every partial entity
8563    // revision and replaces it from a fresh live snapshot before clearing it.
8564    persist_derived_addresses(store, &account.config, addresses, now_unix)?;
8565    persist_reconciled_entities(store, &account.config, coins, transactions, now_unix)?;
8566    let name_revisions = preparation
8567        .names
8568        .iter()
8569        .map(|stored| (stored.value.name_hash, stored.revision))
8570        .collect::<BTreeMap<_, _>>();
8571    let reconciled_name_hashes = names
8572        .iter()
8573        .map(|name| name.name_hash)
8574        .collect::<BTreeSet<_>>();
8575    if reconciled_name_hashes.len() != names.len()
8576        || name_revisions
8577            .keys()
8578            .any(|name_hash| !reconciled_name_hashes.contains(name_hash))
8579    {
8580        return Err(HnsWalletError::StaleAccountRead);
8581    }
8582    for name in names {
8583        // A name found from a bound current FINALIZE has no prior entity and
8584        // is inserted at revision zero under the existing account/read fence.
8585        let revision = name_revisions.get(&name.name_hash).copied().unwrap_or(0);
8586        store.save_known_name(
8587            &namespaced_name_id(&account.config, name.name_hash),
8588            revision,
8589            name,
8590            now_unix,
8591        )?;
8592    }
8593    let recovery_revision = preparation
8594        .recovery_row
8595        .as_ref()
8596        .map_or(0, |stored| stored.revision);
8597    store.save_hns_recovery_state(
8598        &recovery_entity_id(&account.config),
8599        recovery_revision,
8600        recovery,
8601        now_unix,
8602    )?;
8603    store.save_wallet_account(
8604        &account_entity_id(&account.config),
8605        preparation.account_revision,
8606        account,
8607        now_unix,
8608    )?;
8609    Ok(())
8610}
8611
8612fn account_number(account: &HnsAccountRecord) -> u32 {
8613    account.config.account_derivation_index
8614}
8615
8616fn same_account_identity(left: &HnsRuntimeConfig, right: &HnsRuntimeConfig) -> bool {
8617    left.wallet_id == right.wallet_id
8618        && left.account_id == right.account_id
8619        && left.account_derivation_index == right.account_derivation_index
8620        && left.network == right.network
8621        && left.birthday_height == right.birthday_height
8622}
8623
8624fn validate_authoritative_reconcile_account(
8625    cached: &HnsAccountRecord,
8626    cached_revision: u64,
8627    authoritative: &HnsAccountRecord,
8628    authoritative_revision: u64,
8629) -> Result<(), HnsWalletError> {
8630    if !same_account_identity(&cached.config, &authoritative.config)
8631        || cached.config != authoritative.config
8632    {
8633        return Err(HnsWalletError::AccountConfigurationMismatch);
8634    }
8635    if authoritative_revision < cached_revision
8636        || (authoritative_revision == cached_revision && authoritative != cached)
8637        || authoritative.next_receive_index < cached.next_receive_index
8638        || authoritative.next_change_index < cached.next_change_index
8639        || authoritative.next_shakedex_index < cached.next_shakedex_index
8640        || (cached.shakedex_scan_complete && !authoritative.shakedex_scan_complete)
8641        || authoritative.external_scan_end < cached.external_scan_end
8642        || authoritative.internal_scan_end < cached.internal_scan_end
8643        || authoritative.shakedex_scan_end < cached.shakedex_scan_end
8644    {
8645        return Err(HnsWalletError::InvalidEvidence);
8646    }
8647    Ok(())
8648}
8649
8650fn account_birthday_ancestor(birthday_height: u64) -> Option<u64> {
8651    birthday_height.checked_sub(1)
8652}
8653
8654fn ensure_trailing_gap(last_used: Option<u32>, gap: u32) -> Result<(), HnsWalletError> {
8655    if last_used.is_some_and(|index| index.saturating_add(gap) >= MAX_RESTORE_LOOKAHEAD) {
8656        Err(HnsWalletError::ScanCapacityExhausted)
8657    } else {
8658        Ok(())
8659    }
8660}
8661
8662fn required_scan_end(last_used: Option<u32>, current: u32, gap: u32) -> u32 {
8663    last_used.map_or(current, |index| current.max(index.saturating_add(gap)))
8664}
8665
8666fn advance_next_derivation_index(current: u32, last_used: Option<u32>) -> u32 {
8667    last_used.map_or(current, |last_used| {
8668        current
8669            .max(last_used.saturating_add(1))
8670            .min(MAX_RESTORE_LOOKAHEAD - 1)
8671    })
8672}
8673
8674const HNS_COIN_DERIVATION_TAG: u8 = 0;
8675const HNS_SHAKEDEX_DERIVATION_TAG: u8 = 2;
8676
8677fn restore_derivation_key(
8678    derivation: DerivationReference,
8679) -> Result<(u8, u32, u32), HnsWalletError> {
8680    if derivation.index >= MAX_RESTORE_LOOKAHEAD {
8681        return Err(HnsWalletError::InvalidEvidence);
8682    }
8683    match (derivation.role, derivation.change) {
8684        (KeyRole::HnsCoin, change) if change <= 1 => {
8685            Ok((HNS_COIN_DERIVATION_TAG, change, derivation.index))
8686        }
8687        (KeyRole::HnsShakedex, 0) => Ok((HNS_SHAKEDEX_DERIVATION_TAG, 0, derivation.index)),
8688        _ => Err(HnsWalletError::InvalidEvidence),
8689    }
8690}
8691
8692fn validate_restore_program(
8693    derivation: DerivationReference,
8694    program: &[u8],
8695) -> Result<(), HnsWalletError> {
8696    let (tag, _, _) = restore_derivation_key(derivation)?;
8697    let expected_length = match tag {
8698        HNS_COIN_DERIVATION_TAG => 20,
8699        HNS_SHAKEDEX_DERIVATION_TAG => 32,
8700        _ => return Err(HnsWalletError::InvalidEvidence),
8701    };
8702    if program.len() != expected_length {
8703        return Err(HnsWalletError::InvalidEvidence);
8704    }
8705    Ok(())
8706}
8707
8708fn checked_scan_address_count(scan_ends: &[u32]) -> Result<usize, HnsWalletError> {
8709    if scan_ends.is_empty() {
8710        return Err(HnsWalletError::InvalidLookahead);
8711    }
8712    let count = scan_ends.iter().try_fold(0_usize, |count, scan_end| {
8713        if *scan_end >= MAX_RESTORE_LOOKAHEAD {
8714            return Err(HnsWalletError::ScanCapacityExhausted);
8715        }
8716        let branch = usize::try_from(*scan_end)
8717            .map_err(|_| HnsWalletError::ScanCapacityExhausted)?
8718            .checked_add(1)
8719            .ok_or(HnsWalletError::ScanCapacityExhausted)?;
8720        count
8721            .checked_add(branch)
8722            .ok_or(HnsWalletError::ScanCapacityExhausted)
8723    })?;
8724    if count == 0 || count > MAX_RESTORE_SCRIPTS_PER_QUERY {
8725        return Err(HnsWalletError::ScanCapacityExhausted);
8726    }
8727    Ok(count)
8728}
8729
8730fn derive_restore_addresses(
8731    store: &WalletStore,
8732    account: &HnsAccountRecord,
8733    role: KeyRole,
8734) -> Result<Vec<DerivedHnsAddress>, HnsWalletError> {
8735    let branches = match role {
8736        KeyRole::HnsCoin => vec![
8737            (0, account.external_scan_end),
8738            (1, account.internal_scan_end),
8739        ],
8740        KeyRole::HnsShakedex => vec![(0, account.shakedex_scan_end)],
8741        _ => return Err(HnsWalletError::InvalidEvidence),
8742    };
8743    let scan_ends: Vec<u32> = branches.iter().map(|(_, scan_end)| *scan_end).collect();
8744    let address_count = checked_scan_address_count(&scan_ends)?;
8745    let mut addresses = Vec::with_capacity(address_count);
8746    for (change, scan_end) in branches {
8747        for index in 0..=scan_end {
8748            let derivation = DerivationReference {
8749                role,
8750                account: account_number(account),
8751                change,
8752                index,
8753            };
8754            let id = derived_address_record_id(&account.config, derivation)?;
8755            let persisted = store.derived_address::<DerivedHnsAddress>(&id)?;
8756            let public_key = derive_hns_account_public_key(store, account, derivation)?;
8757            let program = match role {
8758                KeyRole::HnsCoin => public_key_hash(&public_key)?.to_vec(),
8759                KeyRole::HnsShakedex => lock_script_hash(&public_key).to_vec(),
8760                _ => return Err(HnsWalletError::InvalidEvidence),
8761            };
8762            let derived = DerivedHnsAddress {
8763                account_id: account.config.account_id,
8764                derivation,
8765                address: encode_v0_address(account.config.network, &program)?,
8766                program,
8767                used: persisted.as_ref().is_some_and(|address| address.value.used),
8768            };
8769            if let Some(persisted) = persisted
8770                && (persisted.id != id
8771                    || persisted.value.account_id != derived.account_id
8772                    || persisted.value.derivation != derived.derivation
8773                    || persisted.value.address != derived.address
8774                    || persisted.value.program != derived.program)
8775            {
8776                return Err(HnsWalletError::InvalidEvidence);
8777            }
8778            addresses.push(derived);
8779        }
8780    }
8781    Ok(addresses)
8782}
8783
8784/// Derive the complete public watch set required by the wallet-owned direct
8785/// HNS light client. The encrypted recovery seed remains inside `store`; this
8786/// function returns only version-zero script identifiers and already-known
8787/// name hashes, never private keys, derivation secrets, or transaction data.
8788///
8789/// A mobile or extension host must install this exact result into its local
8790/// filtered-block authority before asking direct peers to scan. It is tied to
8791/// the persisted account record rather than accepting a caller-assembled list
8792/// of scripts, so a replacement or stale account cannot redirect wallet
8793/// discovery to another authority.
8794pub fn derive_hns_light_watch_set(
8795    store: &WalletStore,
8796    config: &HnsRuntimeConfig,
8797) -> Result<HnsLightWatchSet, HnsWalletError> {
8798    derive_hns_light_watch_set_with_restore_extension(store, config, 0)
8799}
8800
8801/// Derive the public direct-wallet watch set with complete additional restore
8802/// windows. This is used only after an authenticated direct scan discovers
8803/// activity at the current trailing gap: the expanded set is installed before
8804/// the index is rewound and re-scanned, so no unscanned script can enter a
8805/// read projection.
8806///
8807/// `additional_restore_windows` is a count of the account's configured
8808/// restore gap, rather than a caller-supplied script count. The encrypted
8809/// wallet store remains the sole source of derivation material.
8810pub fn derive_hns_light_watch_set_with_restore_extension(
8811    store: &WalletStore,
8812    config: &HnsRuntimeConfig,
8813    additional_restore_windows: u32,
8814) -> Result<HnsLightWatchSet, HnsWalletError> {
8815    if store.is_locked() {
8816        return Err(HnsWalletError::StoreLocked);
8817    }
8818    config.validate_structure()?;
8819    let account_id = account_entity_id(config);
8820    let account = store
8821        .wallet_account::<HnsAccountRecord>(&account_id)?
8822        .ok_or(HnsWalletError::AccountConfigurationMismatch)?;
8823    if account.id.as_slice() != account_id.as_slice() || account.value.config != *config {
8824        return Err(HnsWalletError::AccountConfigurationMismatch);
8825    }
8826    // The direct index must cover exactly the same recovery frontier as the
8827    // authenticated read path. In particular, a durable Shakedex allocation
8828    // high-water can require one or more restoration scripts before the
8829    // account record itself is reconciled again. Deriving the light watch set
8830    // from the un-normalized record would let peers finish a filtered scan and
8831    // then reject the native snapshot for a script the local index never
8832    // watched.
8833    let mut scan_account = account.value;
8834    let allocated_next = shakedex_key::allocation_next_index_for_persisted_recovery_read(
8835        store,
8836        &scan_account.config,
8837    )
8838    .map_err(map_shakedex_restore_error)?;
8839    normalize_restore_scan_account(&mut scan_account, allocated_next)?;
8840    extend_restore_scan_account(&mut scan_account, additional_restore_windows)?;
8841    let coin_addresses = derive_restore_addresses(store, &scan_account, KeyRole::HnsCoin)?;
8842    let shakedex_addresses = derive_restore_addresses(store, &scan_account, KeyRole::HnsShakedex)?;
8843    validate_disjoint_restore_programs(&coin_addresses, &shakedex_addresses)?;
8844    let scripts = coin_addresses
8845        .iter()
8846        .chain(&shakedex_addresses)
8847        .map(|address| WalletAddressKey {
8848            version: 0,
8849            hash: address.program.clone(),
8850        })
8851        .collect::<Vec<_>>();
8852    let known_names = store.list_entities_by_id_prefix::<KnownName>(
8853        EntityKind::KnownName,
8854        &account_entity_prefix(config),
8855        MAX_HISTORY_RESULTS,
8856    )?;
8857    let mut name_hashes = Vec::with_capacity(known_names.len());
8858    for stored in known_names {
8859        let expected_id = namespaced_name_id(config, stored.value.name_hash);
8860        let actual_hash = hash_name(&stored.value.name)
8861            .map_err(|_| HnsWalletError::InvalidEvidence)?
8862            .into_bytes();
8863        if stored.id != expected_id || stored.value.name_hash != actual_hash {
8864            return Err(HnsWalletError::InvalidEvidence);
8865        }
8866        name_hashes.push(stored.value.name_hash);
8867    }
8868    HnsLightWatchSet::new(scripts, name_hashes).map_err(|_| HnsWalletError::InvalidEvidence)
8869}
8870
8871fn extend_restore_scan_account(
8872    account: &mut HnsAccountRecord,
8873    additional_restore_windows: u32,
8874) -> Result<(), HnsWalletError> {
8875    if additional_restore_windows == 0 {
8876        return Ok(());
8877    }
8878    let extension = account
8879        .config
8880        .restore_lookahead
8881        .checked_mul(additional_restore_windows)
8882        .ok_or(HnsWalletError::ScanCapacityExhausted)?;
8883    let extend = |end: u32| {
8884        end.checked_add(extension)
8885            .filter(|candidate| *candidate < MAX_RESTORE_LOOKAHEAD)
8886            .ok_or(HnsWalletError::ScanCapacityExhausted)
8887    };
8888    account.external_scan_end = extend(account.external_scan_end)?;
8889    account.internal_scan_end = extend(account.internal_scan_end)?;
8890    account.shakedex_scan_end = extend(account.shakedex_scan_end)?;
8891    checked_scan_address_count(&[account.external_scan_end, account.internal_scan_end])?;
8892    checked_scan_address_count(&[account.shakedex_scan_end])?;
8893    Ok(())
8894}
8895
8896fn validate_disjoint_restore_programs(
8897    coin_addresses: &[DerivedHnsAddress],
8898    shakedex_addresses: &[DerivedHnsAddress],
8899) -> Result<(), HnsWalletError> {
8900    let combined = coin_addresses
8901        .len()
8902        .checked_add(shakedex_addresses.len())
8903        .ok_or(HnsWalletError::ScanCapacityExhausted)?;
8904    if combined == 0 || combined > MAX_RESTORE_ADDRESS_RECORDS {
8905        return Err(HnsWalletError::ScanCapacityExhausted);
8906    }
8907    let mut programs = BTreeSet::new();
8908    for address in coin_addresses.iter().chain(shakedex_addresses) {
8909        validate_restore_program(address.derivation, &address.program)?;
8910        if !programs.insert(address.program.clone()) {
8911            return Err(HnsWalletError::InvalidEvidence);
8912        }
8913    }
8914    Ok(())
8915}
8916
8917fn validate_same_restore_snapshot(
8918    expected_binding: SnapshotBinding,
8919    expected_mempool: MempoolSnapshotBinding,
8920    actual_binding: SnapshotBinding,
8921    actual_mempool: MempoolSnapshotBinding,
8922) -> Result<(), HnsWalletError> {
8923    if actual_binding != expected_binding || actual_mempool != expected_mempool {
8924        Err(HnsWalletError::StaleNodeSnapshot)
8925    } else {
8926        Ok(())
8927    }
8928}
8929
8930/// The embedded direct backend historically used
8931/// [`HnsWalletError::RuntimeIntegrationUnavailable`] both for an intentionally
8932/// disabled value capability and for a temporarily incomplete authenticated
8933/// read projection. A persisted value read cannot use the former capability,
8934/// so retain the latter's stage in the trusted-native diagnostic without
8935/// exposing script, key, transaction, or peer data.
8936fn annotate_persisted_value_read_unavailable<T>(
8937    stage: &'static str,
8938    result: Result<T, HnsWalletError>,
8939) -> Result<T, HnsWalletError> {
8940    match result {
8941        Err(HnsWalletError::RuntimeIntegrationUnavailable) => Err(HnsWalletError::Backend(
8942            format!("direct wallet read unavailable while {stage}"),
8943        )),
8944        Err(HnsWalletError::InvalidEvidence) => Err(HnsWalletError::Backend(format!(
8945            "direct wallet evidence failed authentication while {stage}"
8946        ))),
8947        result => result,
8948    }
8949}
8950
8951fn map_shakedex_restore_error(error: HnsShakedexKeyAllocationError) -> HnsWalletError {
8952    match error {
8953        HnsShakedexKeyAllocationError::MissingRecoverySeed => HnsWalletError::MissingSeed,
8954        HnsShakedexKeyAllocationError::Store(StoreError::Locked) => HnsWalletError::StoreLocked,
8955        HnsShakedexKeyAllocationError::Store(_) => HnsWalletError::Store,
8956        HnsShakedexKeyAllocationError::Wallet(error) => error,
8957        _ => HnsWalletError::InvalidEvidence,
8958    }
8959}
8960
8961fn normalize_restore_scan_account(
8962    account: &mut HnsAccountRecord,
8963    allocated_next: u32,
8964) -> Result<(), HnsWalletError> {
8965    if allocated_next >= MAX_RESTORE_LOOKAHEAD {
8966        return Err(HnsWalletError::ScanCapacityExhausted);
8967    }
8968    account.next_shakedex_index = account.next_shakedex_index.max(allocated_next);
8969    if account.external_scan_end >= MAX_RESTORE_LOOKAHEAD
8970        || account.internal_scan_end >= MAX_RESTORE_LOOKAHEAD
8971        || account.shakedex_scan_end >= MAX_RESTORE_LOOKAHEAD
8972        || account.next_receive_index >= MAX_RESTORE_LOOKAHEAD
8973        || account.next_change_index >= MAX_RESTORE_LOOKAHEAD
8974        || account.next_shakedex_index >= MAX_RESTORE_LOOKAHEAD
8975    {
8976        return Err(HnsWalletError::InvalidLookahead);
8977    }
8978    let gap = account.config.restore_lookahead;
8979    if gap == 0 {
8980        return Err(HnsWalletError::InvalidLookahead);
8981    }
8982    let minimum_external_end = account
8983        .next_receive_index
8984        .saturating_add(gap - 1)
8985        .min(MAX_RESTORE_LOOKAHEAD - 1);
8986    let minimum_internal_end = account
8987        .next_change_index
8988        .saturating_add(gap - 1)
8989        .min(MAX_RESTORE_LOOKAHEAD - 1);
8990    let minimum_shakedex_end = account
8991        .next_shakedex_index
8992        .saturating_add(gap - 1)
8993        .min(MAX_RESTORE_LOOKAHEAD - 1);
8994    account.external_scan_end = account.external_scan_end.max(minimum_external_end);
8995    account.internal_scan_end = account.internal_scan_end.max(minimum_internal_end);
8996    account.shakedex_scan_end = account.shakedex_scan_end.max(minimum_shakedex_end);
8997    Ok(())
8998}
8999
9000/// One canonical restore scanner shared by the value runtime and the
9001/// SharedWalletStore read adapter. The address source closure is the only
9002/// persistence boundary; it must return before this function performs any
9003/// backend operation.
9004fn scan_restore_snapshot<B, F>(
9005    backend: &B,
9006    mut account: HnsAccountRecord,
9007    expected_tip: ChainTip,
9008    initial_binding: Option<SnapshotBinding>,
9009    mut derive_branches: F,
9010) -> Result<HnsReadScan, HnsWalletError>
9011where
9012    B: HnsBackend,
9013    F: FnMut(&HnsAccountRecord) -> Result<[Vec<DerivedHnsAddress>; 2], HnsWalletError>,
9014{
9015    if initial_binding.is_some_and(|binding| binding.tip != expected_tip) {
9016        return Err(HnsWalletError::StaleNodeSnapshot);
9017    }
9018    let gap = account.config.restore_lookahead;
9019    let mut expected_binding = initial_binding;
9020    let mut expected_mempool = None;
9021    loop {
9022        let [coin_addresses, shakedex_addresses] = derive_branches(&account)?;
9023        validate_disjoint_restore_programs(&coin_addresses, &shakedex_addresses)?;
9024
9025        let (coin_scripts, coin_index_remap) = sorted_restore_scripts(&coin_addresses)?;
9026        let (binding, mempool, coin_history, coin_coins) = load_wallet_snapshot(
9027            backend,
9028            &coin_scripts,
9029            &coin_index_remap,
9030            expected_tip,
9031            expected_binding,
9032            expected_mempool,
9033        )?;
9034        if expected_binding.is_some_and(|expected| expected != binding)
9035            || expected_mempool.is_some_and(|expected| expected != mempool)
9036        {
9037            return Err(HnsWalletError::StaleNodeSnapshot);
9038        }
9039
9040        // TRANSFER embeds its future recipient in the covenant rather than in
9041        // the current output script. Query the ordinary account-zero scripts
9042        // so an incoming name advances the same restoration high-water.
9043        let incoming_coin_indices =
9044            load_incoming_transfer_derivations(backend, &coin_scripts, &coin_index_remap, binding)?;
9045        let incoming_coin_derivations = incoming_coin_indices
9046            .iter()
9047            .map(|index| {
9048                let address = coin_addresses
9049                    .get(*index as usize)
9050                    .ok_or(HnsWalletError::InvalidEvidence)?;
9051                let key = restore_derivation_key(address.derivation)?;
9052                if key.0 != HNS_COIN_DERIVATION_TAG {
9053                    return Err(HnsWalletError::InvalidEvidence);
9054                }
9055                Ok(key)
9056            })
9057            .collect::<Result<BTreeSet<_>, _>>()?;
9058
9059        let (shakedex_scripts, shakedex_index_remap) = sorted_restore_scripts(&shakedex_addresses)?;
9060        let (shakedex_binding, shakedex_mempool, shakedex_history, shakedex_coins) =
9061            load_wallet_snapshot(
9062                backend,
9063                &shakedex_scripts,
9064                &shakedex_index_remap,
9065                expected_tip,
9066                Some(binding),
9067                Some(mempool),
9068            )?;
9069        validate_same_restore_snapshot(binding, mempool, shakedex_binding, shakedex_mempool)?;
9070        expected_binding = Some(binding);
9071        expected_mempool = Some(mempool);
9072
9073        let mut addresses = Vec::new();
9074        let mut history = Vec::new();
9075        let mut indexed_coins = Vec::new();
9076        append_restore_branch(
9077            &mut addresses,
9078            &mut history,
9079            &mut indexed_coins,
9080            coin_addresses,
9081            coin_history,
9082            coin_coins,
9083        )?;
9084        append_restore_branch(
9085            &mut addresses,
9086            &mut history,
9087            &mut indexed_coins,
9088            shakedex_addresses,
9089            shakedex_history,
9090            shakedex_coins,
9091        )?;
9092
9093        let mut last_external = incoming_coin_derivations
9094            .iter()
9095            .filter_map(|(_, change, index)| (*change == 0).then_some(*index))
9096            .max();
9097        let mut last_internal = incoming_coin_derivations
9098            .iter()
9099            .filter_map(|(_, change, index)| (*change == 1).then_some(*index))
9100            .max();
9101        let mut last_shakedex = None;
9102        for entry in &history {
9103            let derivation = addresses
9104                .get(entry.script_index as usize)
9105                .ok_or(HnsWalletError::InvalidEvidence)?
9106                .derivation;
9107            match restore_derivation_key(derivation)? {
9108                (HNS_COIN_DERIVATION_TAG, 0, index) => {
9109                    last_external = Some(last_external.map_or(index, |last: u32| last.max(index)))
9110                }
9111                (HNS_COIN_DERIVATION_TAG, 1, index) => {
9112                    last_internal = Some(last_internal.map_or(index, |last: u32| last.max(index)))
9113                }
9114                (HNS_SHAKEDEX_DERIVATION_TAG, 0, index) => {
9115                    last_shakedex = Some(last_shakedex.map_or(index, |last: u32| last.max(index)))
9116                }
9117                _ => return Err(HnsWalletError::InvalidEvidence),
9118            }
9119        }
9120        for indexed_coin in &indexed_coins {
9121            let derivation = addresses
9122                .get(indexed_coin.script_index as usize)
9123                .ok_or(HnsWalletError::InvalidEvidence)?
9124                .derivation;
9125            match restore_derivation_key(derivation)? {
9126                (HNS_COIN_DERIVATION_TAG, 0, index) => {
9127                    last_external = Some(last_external.map_or(index, |last: u32| last.max(index)))
9128                }
9129                (HNS_COIN_DERIVATION_TAG, 1, index) => {
9130                    last_internal = Some(last_internal.map_or(index, |last: u32| last.max(index)))
9131                }
9132                (HNS_SHAKEDEX_DERIVATION_TAG, 0, index) => {
9133                    last_shakedex = Some(last_shakedex.map_or(index, |last: u32| last.max(index)))
9134                }
9135                _ => return Err(HnsWalletError::InvalidEvidence),
9136            }
9137        }
9138        ensure_trailing_gap(last_external, gap)?;
9139        ensure_trailing_gap(last_internal, gap)?;
9140        ensure_trailing_gap(last_shakedex, gap)?;
9141        let required_external = required_scan_end(last_external, account.external_scan_end, gap);
9142        let required_internal = required_scan_end(last_internal, account.internal_scan_end, gap);
9143        let required_shakedex = required_scan_end(last_shakedex, account.shakedex_scan_end, gap);
9144        checked_scan_address_count(&[required_external, required_internal])?;
9145        checked_scan_address_count(&[required_shakedex])?;
9146        if required_external > account.external_scan_end
9147            || required_internal > account.internal_scan_end
9148            || required_shakedex > account.shakedex_scan_end
9149        {
9150            account.external_scan_end = required_external;
9151            account.internal_scan_end = required_internal;
9152            account.shakedex_scan_end = required_shakedex;
9153            continue;
9154        }
9155
9156        let mut used: BTreeSet<(u8, u32, u32)> = history
9157            .iter()
9158            .map(|entry| {
9159                let derivation = addresses
9160                    .get(entry.script_index as usize)
9161                    .ok_or(HnsWalletError::InvalidEvidence)?
9162                    .derivation;
9163                restore_derivation_key(derivation)
9164            })
9165            .collect::<Result<_, _>>()?;
9166        used.extend(
9167            indexed_coins
9168                .iter()
9169                .map(|coin| {
9170                    addresses
9171                        .get(coin.script_index as usize)
9172                        .ok_or(HnsWalletError::InvalidEvidence)
9173                        .and_then(|address| restore_derivation_key(address.derivation))
9174                })
9175                .collect::<Result<BTreeSet<_>, _>>()?,
9176        );
9177        used.extend(incoming_coin_derivations);
9178        for address in &mut addresses {
9179            address.used = used.contains(&restore_derivation_key(address.derivation)?);
9180        }
9181        account.last_used_external = used
9182            .iter()
9183            .filter(|(role, change, _)| *role == HNS_COIN_DERIVATION_TAG && *change == 0)
9184            .map(|(_, _, index)| *index)
9185            .max();
9186        account.last_used_internal = used
9187            .iter()
9188            .filter(|(role, change, _)| *role == HNS_COIN_DERIVATION_TAG && *change == 1)
9189            .map(|(_, _, index)| *index)
9190            .max();
9191        account.last_used_shakedex = used
9192            .iter()
9193            .filter(|(role, change, _)| *role == HNS_SHAKEDEX_DERIVATION_TAG && *change == 0)
9194            .map(|(_, _, index)| *index)
9195            .max();
9196        account.next_receive_index =
9197            advance_next_derivation_index(account.next_receive_index, account.last_used_external);
9198        account.next_change_index =
9199            advance_next_derivation_index(account.next_change_index, account.last_used_internal);
9200        account.next_shakedex_index =
9201            advance_next_derivation_index(account.next_shakedex_index, account.last_used_shakedex);
9202        account.shakedex_scan_complete = true;
9203        account.shakedex_scan_in_progress = false;
9204        history.sort_by_key(|entry| (entry.txid, entry.script_index));
9205        return Ok(HnsReadScan {
9206            account,
9207            binding,
9208            mempool,
9209            addresses,
9210            history,
9211            indexed_coins,
9212            branch_scripts: [coin_scripts, shakedex_scripts],
9213        });
9214    }
9215}
9216
9217fn append_restore_branch(
9218    addresses: &mut Vec<DerivedHnsAddress>,
9219    history: &mut Vec<HistoryEntry>,
9220    indexed_coins: &mut Vec<IndexedWalletCoin>,
9221    branch_addresses: Vec<DerivedHnsAddress>,
9222    mut branch_history: Vec<HistoryEntry>,
9223    mut branch_coins: Vec<IndexedWalletCoin>,
9224) -> Result<(), HnsWalletError> {
9225    if branch_addresses.is_empty()
9226        || branch_addresses.len() > MAX_RESTORE_SCRIPTS_PER_QUERY
9227        || addresses
9228            .len()
9229            .checked_add(branch_addresses.len())
9230            .is_none_or(|count| count > MAX_RESTORE_ADDRESS_RECORDS)
9231        || history
9232            .len()
9233            .checked_add(branch_history.len())
9234            .is_none_or(|count| count > MAX_HISTORY_RESULTS)
9235        || indexed_coins
9236            .len()
9237            .checked_add(branch_coins.len())
9238            .is_none_or(|count| count > MAX_WALLET_COINS)
9239    {
9240        return Err(HnsWalletError::ScanCapacityExhausted);
9241    }
9242    let offset =
9243        u32::try_from(addresses.len()).map_err(|_| HnsWalletError::ScanCapacityExhausted)?;
9244    for entry in &mut branch_history {
9245        if entry.script_index as usize >= branch_addresses.len() {
9246            return Err(HnsWalletError::InvalidEvidence);
9247        }
9248        entry.script_index = entry
9249            .script_index
9250            .checked_add(offset)
9251            .ok_or(HnsWalletError::ScanCapacityExhausted)?;
9252    }
9253    for coin in &mut branch_coins {
9254        if coin.script_index as usize >= branch_addresses.len() {
9255            return Err(HnsWalletError::InvalidEvidence);
9256        }
9257        coin.script_index = coin
9258            .script_index
9259            .checked_add(offset)
9260            .ok_or(HnsWalletError::ScanCapacityExhausted)?;
9261    }
9262    addresses.extend(branch_addresses);
9263    history.extend(branch_history);
9264    indexed_coins.extend(branch_coins);
9265    Ok(())
9266}
9267
9268fn sorted_restore_scripts(
9269    addresses: &[DerivedHnsAddress],
9270) -> Result<(Vec<WalletAddressKey>, Vec<u32>), HnsWalletError> {
9271    if addresses.is_empty() || addresses.len() > MAX_RESTORE_SCRIPTS_PER_QUERY {
9272        return Err(HnsWalletError::ScanCapacityExhausted);
9273    }
9274    let mut indexed: Vec<(WalletAddressKey, u32)> = addresses
9275        .iter()
9276        .enumerate()
9277        .map(|(index, address)| {
9278            u32::try_from(index)
9279                .map(|index| {
9280                    (
9281                        WalletAddressKey {
9282                            version: 0,
9283                            hash: address.program.clone(),
9284                        },
9285                        index,
9286                    )
9287                })
9288                .map_err(|_| HnsWalletError::ScanCapacityExhausted)
9289        })
9290        .collect::<Result<_, _>>()?;
9291    indexed.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1)));
9292    if indexed.windows(2).any(|pair| pair[0].0 == pair[1].0) {
9293        return Err(HnsWalletError::InvalidEvidence);
9294    }
9295    let scripts = indexed.iter().map(|(script, _)| script.clone()).collect();
9296    let remap = indexed.into_iter().map(|(_, index)| index).collect();
9297    Ok((scripts, remap))
9298}
9299
9300fn load_wallet_snapshot<B: HnsBackend>(
9301    backend: &B,
9302    scripts: &[WalletAddressKey],
9303    index_remap: &[u32],
9304    expected_tip: ChainTip,
9305    expected_binding: Option<SnapshotBinding>,
9306    expected_mempool: Option<MempoolSnapshotBinding>,
9307) -> Result<
9308    (
9309        SnapshotBinding,
9310        MempoolSnapshotBinding,
9311        Vec<HistoryEntry>,
9312        Vec<IndexedWalletCoin>,
9313    ),
9314    HnsWalletError,
9315> {
9316    for attempt in 0..MAX_SNAPSHOT_RESTARTS {
9317        match load_wallet_snapshot_once(
9318            backend,
9319            scripts,
9320            index_remap,
9321            expected_tip,
9322            expected_binding,
9323            expected_mempool,
9324        ) {
9325            Err(HnsWalletError::StaleNodeSnapshot) if attempt + 1 < MAX_SNAPSHOT_RESTARTS => {}
9326            result => return result,
9327        }
9328    }
9329    Err(HnsWalletError::StaleNodeSnapshot)
9330}
9331
9332fn load_wallet_snapshot_once<B: HnsBackend>(
9333    backend: &B,
9334    scripts: &[WalletAddressKey],
9335    index_remap: &[u32],
9336    expected_tip: ChainTip,
9337    expected_binding: Option<SnapshotBinding>,
9338    expected_mempool: Option<MempoolSnapshotBinding>,
9339) -> Result<
9340    (
9341        SnapshotBinding,
9342        MempoolSnapshotBinding,
9343        Vec<HistoryEntry>,
9344        Vec<IndexedWalletCoin>,
9345    ),
9346    HnsWalletError,
9347> {
9348    if scripts.is_empty()
9349        || scripts.len() != index_remap.len()
9350        || scripts.len() > MAX_RESTORE_SCRIPTS_PER_QUERY
9351        || !scripts.windows(2).all(|pair| pair[0] < pair[1])
9352        || scripts
9353            .iter()
9354            .any(|script| script.version != 0 || !matches!(script.hash.len(), 20 | 32))
9355    {
9356        return Err(HnsWalletError::InvalidEvidence);
9357    }
9358    let limit =
9359        u32::try_from(MAX_SCAN_PAGE_RESULTS).map_err(|_| HnsWalletError::ScanCapacityExhausted)?;
9360    let mut confirmed_cursor: Option<Vec<u8>> = None;
9361    let mut seen_cursors = BTreeSet::new();
9362    let mut binding = expected_binding;
9363    let mut history = Vec::new();
9364    let mut utxos = Vec::new();
9365    for _ in 0..MAX_SCAN_PAGES {
9366        let page = backend.get_confirmed_wallet_page(ConfirmedWalletPageRequest {
9367            scripts,
9368            expected_tip,
9369            expected_epoch: binding.map(|value: SnapshotBinding| value.chain_epoch),
9370            cursor: confirmed_cursor.as_deref(),
9371            limit,
9372        })?;
9373        if page.binding.tip != expected_tip
9374            || binding.is_some_and(|expected| expected != page.binding)
9375            || page.history.len().saturating_add(page.utxos.len()) > MAX_SCAN_PAGE_RESULTS
9376        {
9377            return Err(HnsWalletError::StaleNodeSnapshot);
9378        }
9379        binding = Some(page.binding);
9380        append_remapped_history(&mut history, page.history, index_remap, true)?;
9381        append_remapped_utxos(&mut utxos, page.utxos, scripts, index_remap)?;
9382        confirmed_cursor = validated_next_cursor(page.next_cursor, &mut seen_cursors)?;
9383        if confirmed_cursor.is_none() {
9384            break;
9385        }
9386    }
9387    if confirmed_cursor.is_some() {
9388        return Err(HnsWalletError::ScanCapacityExhausted);
9389    }
9390    let binding = binding.ok_or(HnsWalletError::InvalidEvidence)?;
9391
9392    let mut mempool_cursor: Option<Vec<u8>> = None;
9393    let mut mempool_binding = expected_mempool;
9394    let mempool_limit = u32::try_from(MAX_MEMPOOL_SCAN_RESULTS)
9395        .map_err(|_| HnsWalletError::ScanCapacityExhausted)?;
9396    seen_cursors.clear();
9397    for _ in 0..MAX_SCAN_PAGES {
9398        let page = backend.get_mempool_wallet_page(MempoolWalletPageRequest {
9399            scripts,
9400            binding,
9401            expected_mempool: mempool_binding,
9402            cursor: mempool_cursor.as_deref(),
9403            limit: mempool_limit,
9404        })?;
9405        if page.binding != binding
9406            || page.mempool.instance_nonce == [0; 32]
9407            || mempool_binding.is_some_and(|expected| expected != page.mempool)
9408            || page.history.len() > MAX_HISTORY_RESULTS
9409        {
9410            return Err(HnsWalletError::StaleNodeSnapshot);
9411        }
9412        mempool_binding = Some(page.mempool);
9413        append_remapped_history(&mut history, page.history, index_remap, false)?;
9414        mempool_cursor = validated_next_cursor(page.next_cursor, &mut seen_cursors)?;
9415        if mempool_cursor.is_none() {
9416            break;
9417        }
9418    }
9419    if mempool_cursor.is_some() {
9420        return Err(HnsWalletError::ScanCapacityExhausted);
9421    }
9422    let mempool_binding = mempool_binding.ok_or(HnsWalletError::InvalidEvidence)?;
9423    Ok((
9424        binding,
9425        mempool_binding,
9426        bounded_history(history, index_remap.len())?,
9427        utxos,
9428    ))
9429}
9430
9431fn load_incoming_transfer_derivations<B: HnsBackend>(
9432    backend: &B,
9433    scripts: &[WalletAddressKey],
9434    index_remap: &[u32],
9435    binding: SnapshotBinding,
9436) -> Result<BTreeSet<u32>, HnsWalletError> {
9437    if scripts.is_empty()
9438        || scripts.len() != index_remap.len()
9439        || scripts.len() > MAX_RESTORE_SCRIPTS_PER_QUERY
9440        || !scripts.windows(2).all(|pair| pair[0] < pair[1])
9441    {
9442        return Err(HnsWalletError::InvalidEvidence);
9443    }
9444    let limit =
9445        u32::try_from(MAX_SCAN_PAGE_RESULTS).map_err(|_| HnsWalletError::ScanCapacityExhausted)?;
9446    let mut cursor = None;
9447    let mut seen_cursors = BTreeSet::new();
9448    let mut outpoints = BTreeSet::new();
9449    let mut derivations = BTreeSet::new();
9450    let mut row_count = 0usize;
9451    for _ in 0..MAX_INCOMING_TRANSFER_PAGES {
9452        let page = backend.get_incoming_transfers_page(IncomingTransfersPageRequest {
9453            scripts,
9454            binding,
9455            cursor: cursor.as_deref(),
9456            limit,
9457        })?;
9458        if page.projection_version != 1
9459            || page.binding != binding
9460            || page.entries.len() > MAX_SCAN_PAGE_RESULTS
9461            || !(1..=MAX_SCAN_PAGE_RESULTS).contains(&page.script_examinations)
9462            || page.script_examinations > scripts.len()
9463        {
9464            return Err(HnsWalletError::StaleNodeSnapshot);
9465        }
9466        row_count = row_count
9467            .checked_add(page.entries.len())
9468            .ok_or(HnsWalletError::ScanCapacityExhausted)?;
9469        if row_count > MAX_HISTORY_RESULTS {
9470            return Err(HnsWalletError::ScanCapacityExhausted);
9471        }
9472        for entry in page.entries {
9473            let request_index = entry.script_index as usize;
9474            let expected_script = scripts
9475                .get(request_index)
9476                .ok_or(HnsWalletError::InvalidEvidence)?;
9477            validate_incoming_transfer_candidate(&entry, expected_script, binding)?;
9478            let outpoint = HnsOutpoint {
9479                transaction: TransactionHash::new(
9480                    entry.transfer_coin.outpoint.transaction_hash.into_bytes(),
9481                ),
9482                output_index: entry.transfer_coin.outpoint.index,
9483            };
9484            if !outpoints.insert(outpoint) {
9485                return Err(HnsWalletError::InvalidEvidence);
9486            }
9487            derivations.insert(
9488                *index_remap
9489                    .get(request_index)
9490                    .ok_or(HnsWalletError::InvalidEvidence)?,
9491            );
9492        }
9493        cursor = validated_next_cursor(page.next_cursor, &mut seen_cursors)?;
9494        if cursor.is_none() {
9495            return Ok(derivations);
9496        }
9497    }
9498    Err(HnsWalletError::ScanCapacityExhausted)
9499}
9500
9501fn validate_incoming_transfer_candidate(
9502    candidate: &IncomingTransferCandidate,
9503    expected_recipient: &WalletAddressKey,
9504    binding: SnapshotBinding,
9505) -> Result<(), HnsWalletError> {
9506    let transfer = TransferCovenant::try_from(&candidate.transfer_coin.covenant)
9507        .map_err(|_| HnsWalletError::InvalidEvidence)?;
9508    if &candidate.recipient != expected_recipient
9509        || candidate.inclusion.height > binding.tip.height
9510        || candidate.inclusion.block_hash == [0; 32]
9511        || candidate.inclusion.transaction_index.is_none()
9512        || candidate.transfer_coin.outpoint.is_null()
9513        || candidate.transfer_coin.coinbase
9514        || u64::from(candidate.transfer_coin.height.get()) != candidate.inclusion.height
9515        || candidate.source_output_count == 0
9516        || candidate.transfer_coin.outpoint.index >= candidate.source_output_count
9517        || transfer.name_hash.into_bytes() != candidate.name_hash
9518        || transfer.start_height.get() != candidate.start_height
9519        || transfer.recipient_version != candidate.recipient.version
9520        || transfer.recipient_hash != candidate.recipient.hash
9521    {
9522        return Err(HnsWalletError::InvalidEvidence);
9523    }
9524    Ok(())
9525}
9526
9527fn validated_next_cursor(
9528    cursor: Option<Vec<u8>>,
9529    seen: &mut BTreeSet<Vec<u8>>,
9530) -> Result<Option<Vec<u8>>, HnsWalletError> {
9531    match cursor {
9532        Some(cursor)
9533            if cursor.is_empty()
9534                || cursor.len() > MAX_SCAN_CURSOR_BYTES
9535                || !seen.insert(cursor.clone()) =>
9536        {
9537            Err(HnsWalletError::StaleNodeSnapshot)
9538        }
9539        value => Ok(value),
9540    }
9541}
9542
9543fn append_remapped_history(
9544    output: &mut Vec<HistoryEntry>,
9545    entries: Vec<HistoryEntry>,
9546    index_remap: &[u32],
9547    confirmed: bool,
9548) -> Result<(), HnsWalletError> {
9549    if output.len().saturating_add(entries.len()) > MAX_HISTORY_RESULTS {
9550        return Err(HnsWalletError::HistoryLimit);
9551    }
9552    for mut entry in entries {
9553        if confirmed
9554            != (entry.height.is_some()
9555                && entry.block_hash.is_some()
9556                && entry.transaction_position.is_some())
9557            || (!confirmed
9558                && (entry.height.is_some()
9559                    || entry.block_hash.is_some()
9560                    || entry.transaction_position.is_some()
9561                    || entry.first_seen_unix.is_none()))
9562        {
9563            return Err(HnsWalletError::InvalidEvidence);
9564        }
9565        entry.script_index = *index_remap
9566            .get(entry.script_index as usize)
9567            .ok_or(HnsWalletError::InvalidEvidence)?;
9568        output.push(entry);
9569    }
9570    Ok(())
9571}
9572
9573fn append_remapped_utxos(
9574    output: &mut Vec<IndexedWalletCoin>,
9575    entries: Vec<IndexedWalletCoin>,
9576    scripts: &[WalletAddressKey],
9577    index_remap: &[u32],
9578) -> Result<(), HnsWalletError> {
9579    if output.len().saturating_add(entries.len()) > MAX_WALLET_COINS {
9580        return Err(HnsWalletError::InvalidAmount);
9581    }
9582    for mut entry in entries {
9583        let expected_script = scripts
9584            .get(entry.script_index as usize)
9585            .ok_or(HnsWalletError::InvalidEvidence)?;
9586        if &entry.output_address != expected_script {
9587            return Err(HnsWalletError::InvalidEvidence);
9588        }
9589        entry.script_index = *index_remap
9590            .get(entry.script_index as usize)
9591            .ok_or(HnsWalletError::InvalidEvidence)?;
9592        output.push(entry);
9593    }
9594    Ok(())
9595}
9596
9597fn validate_spend_evidence(
9598    evidence: &OutpointSpendEvidence,
9599    binding: SnapshotBinding,
9600    expected_outpoints: &[HnsOutpoint],
9601) -> Result<(), HnsWalletError> {
9602    if evidence.binding != binding || evidence.entries.len() != expected_outpoints.len() {
9603        return Err(HnsWalletError::StaleNodeSnapshot);
9604    }
9605    for (entry, expected) in evidence.entries.iter().zip(expected_outpoints) {
9606        if entry.outpoint != *expected
9607            || entry.spending.is_some_and(|spending| {
9608                spending.height > binding.tip.height || spending.block_hash == [0; 32]
9609            })
9610        {
9611            return Err(HnsWalletError::InvalidEvidence);
9612        }
9613    }
9614    Ok(())
9615}
9616
9617fn has_competing_spender_in_batches<B: HnsBackend>(
9618    backend: &B,
9619    outpoints: &[HnsOutpoint],
9620    binding: SnapshotBinding,
9621    expected_spender: TransactionHash,
9622) -> Result<bool, HnsWalletError> {
9623    let mut competing = false;
9624    for batch in outpoints.chunks(MAX_OUTPOINT_SPEND_BATCH) {
9625        let evidence = backend.get_outpoint_spend_evidence(batch, binding)?;
9626        validate_spend_evidence(&evidence, binding, batch)?;
9627        competing |= evidence.entries.iter().any(|entry| {
9628            entry
9629                .spending
9630                .is_some_and(|spending| spending.transaction != expected_spender)
9631        });
9632    }
9633    Ok(competing)
9634}
9635
9636fn public_key_hash(public_key: &[u8; 33]) -> Result<[u8; 20], HnsWalletError> {
9637    let mut hasher = Blake2bVar::new(20).map_err(|_| HnsWalletError::KeyDerivation)?;
9638    blake2::digest::Update::update(&mut hasher, public_key);
9639    let mut output = [0_u8; 20];
9640    hasher
9641        .finalize_variable(&mut output)
9642        .map_err(|_| HnsWalletError::KeyDerivation)?;
9643    Ok(output)
9644}
9645
9646fn bounded_history(
9647    history: Vec<HistoryEntry>,
9648    script_count: usize,
9649) -> Result<Vec<HistoryEntry>, HnsWalletError> {
9650    if history.len() > MAX_HISTORY_RESULTS {
9651        return Err(HnsWalletError::HistoryLimit);
9652    }
9653    let mut unique = BTreeMap::new();
9654    for entry in history {
9655        if entry.script_index as usize >= script_count {
9656            return Err(HnsWalletError::InvalidEvidence);
9657        }
9658        let key = (entry.txid, entry.script_index);
9659        if let Some(previous) = unique.insert(key, entry)
9660            && previous != entry
9661        {
9662            return Err(HnsWalletError::InvalidEvidence);
9663        }
9664    }
9665    Ok(unique.into_values().collect())
9666}
9667
9668fn coalesce_transaction_history(
9669    history: &[HistoryEntry],
9670) -> Result<Vec<HistoryEntry>, HnsWalletError> {
9671    let mut transactions: BTreeMap<TransactionHash, HistoryEntry> = BTreeMap::new();
9672    for entry in history {
9673        match transactions.get_mut(&entry.txid) {
9674            Some(previous) => {
9675                if previous.height != entry.height
9676                    || previous.block_hash != entry.block_hash
9677                    || previous.transaction_position != entry.transaction_position
9678                    || previous.first_seen_unix != entry.first_seen_unix
9679                {
9680                    return Err(HnsWalletError::InvalidEvidence);
9681                }
9682                previous.spent |= entry.spent;
9683                previous.script_index = previous.script_index.min(entry.script_index);
9684            }
9685            None => {
9686                transactions.insert(entry.txid, *entry);
9687            }
9688        }
9689    }
9690    Ok(transactions.into_values().collect())
9691}
9692
9693fn reconcile_coins(
9694    indexed: Vec<IndexedWalletCoin>,
9695    addresses: &[DerivedHnsAddress],
9696    tip_height: u64,
9697) -> Result<Vec<TrackedHnsCoin>, HnsWalletError> {
9698    if indexed.len() > MAX_WALLET_COINS {
9699        return Err(HnsWalletError::InvalidAmount);
9700    }
9701    let mut outpoints = BTreeSet::new();
9702    let mut coins = Vec::with_capacity(indexed.len());
9703    for indexed_coin in indexed {
9704        if !outpoints.insert(indexed_coin.coin.outpoint) {
9705            return Err(HnsWalletError::InvalidEvidence);
9706        }
9707        let address = addresses
9708            .get(indexed_coin.script_index as usize)
9709            .ok_or(HnsWalletError::InvalidEvidence)?;
9710        let confirmed_height = indexed_coin
9711            .coin
9712            .confirmed_height
9713            .ok_or(HnsWalletError::InvalidEvidence)?;
9714        let confirmed_height = u64::from(confirmed_height);
9715        let expected_confirmations = tip_height
9716            .checked_sub(confirmed_height)
9717            .and_then(|depth| depth.checked_add(1))
9718            .and_then(|depth| u32::try_from(depth).ok())
9719            .ok_or(HnsWalletError::InvalidEvidence)?;
9720        if indexed_coin.coin.confirmation_count != expected_confirmations
9721            || indexed_coin.output_address.version != 0
9722            || indexed_coin.output_address.hash.as_slice() != address.program.as_slice()
9723            || restore_derivation_key(address.derivation).is_err()
9724        {
9725            return Err(HnsWalletError::InvalidEvidence);
9726        }
9727        let tracked = TrackedHnsCoin {
9728            coin: indexed_coin.coin,
9729            derivation: address.derivation,
9730            address_program: address.program.clone(),
9731        };
9732        tracked.to_canonical_coin()?;
9733        coins.push(tracked);
9734    }
9735    coins.sort_by_key(|coin| coin.coin.outpoint);
9736    Ok(coins)
9737}
9738
9739/// Both account-zero P2PKH branches are controlled by this wallet.
9740/// Name-locked outputs and every Shakedex/settlement branch remain excluded.
9741const fn is_ordinary_hns_derivation(derivation: DerivationReference) -> bool {
9742    matches!(derivation.role, KeyRole::HnsCoin)
9743}
9744
9745fn is_ordinary_hns_spend_candidate(coin: &TrackedHnsCoin) -> bool {
9746    is_ordinary_hns_derivation(coin.derivation) && !coin.coin.name_locked && !coin.coin.coinbase
9747}
9748
9749fn is_confirmed_ordinary_hns_spend_candidate(coin: &TrackedHnsCoin) -> bool {
9750    is_ordinary_hns_spend_candidate(coin) && coin.coin.confirmation_count > 0
9751}
9752
9753fn ordinary_hns_input_roles(inputs: &[TrackedHnsCoin]) -> Result<Vec<KeyRole>, HnsWalletError> {
9754    inputs
9755        .iter()
9756        .map(|coin| {
9757            if is_ordinary_hns_derivation(coin.derivation) {
9758                Ok(coin.derivation.role)
9759            } else {
9760                Err(HnsWalletError::InvalidPreparedArtifact)
9761            }
9762        })
9763        .collect()
9764}
9765
9766fn decode_transaction_for_id(
9767    raw: &[u8],
9768    expected: TransactionHash,
9769) -> Result<Transaction, HnsWalletError> {
9770    let transaction = Transaction::decode(raw).map_err(|_| HnsWalletError::InvalidEvidence)?;
9771    let actual = transaction
9772        .transaction_hash()
9773        .map_err(|_| HnsWalletError::InvalidEvidence)?;
9774    if actual.as_bytes() != expected.as_bytes() {
9775        return Err(HnsWalletError::InvalidEvidence);
9776    }
9777    Ok(transaction)
9778}
9779
9780fn validate_inclusion(
9781    entry: &HistoryEntry,
9782    status: TransactionStatus,
9783    inclusion: Option<TransactionInclusion>,
9784    tip: ChainTip,
9785    observed_in_current_history: bool,
9786) -> Result<(), HnsWalletError> {
9787    if status.conflicted && (status.in_mempool || status.confirmation_count > 0) {
9788        return Err(HnsWalletError::InvalidEvidence);
9789    }
9790    match inclusion {
9791        Some(inclusion) => {
9792            if inclusion.height > tip.height
9793                || (observed_in_current_history && entry.height != Some(inclusion.height))
9794                || (observed_in_current_history && entry.block_hash != Some(inclusion.block_hash))
9795                || (observed_in_current_history
9796                    && inclusion.transaction_index.is_some()
9797                    && entry.transaction_position != inclusion.transaction_index)
9798                || status.confirmation_count == 0
9799            {
9800                return Err(HnsWalletError::InvalidEvidence);
9801            }
9802            let expected_confirmations = tip.height - inclusion.height + 1;
9803            if u64::from(status.confirmation_count) != expected_confirmations {
9804                return Err(HnsWalletError::InvalidEvidence);
9805            }
9806        }
9807        None => {
9808            if (observed_in_current_history && entry.height.is_some())
9809                || status.confirmation_count > 0
9810            {
9811                return Err(HnsWalletError::InvalidEvidence);
9812            }
9813        }
9814    }
9815    Ok(())
9816}
9817
9818fn transaction_value_effect<B: HnsBackend>(
9819    backend: &B,
9820    transaction: &Transaction,
9821    programs: &BTreeSet<Vec<u8>>,
9822    raw_cache: &mut BTreeMap<TransactionHash, Transaction>,
9823    persisted_raw: &BTreeMap<TransactionHash, Vec<u8>>,
9824    binding: SnapshotBinding,
9825    mempool_binding: MempoolSnapshotBinding,
9826) -> Result<(SignedBaseUnits, Option<BaseUnits>), HnsWalletError> {
9827    if transaction.inputs.len() > MAX_TRANSACTION_INPUTS {
9828        return Err(HnsWalletError::InvalidEvidence);
9829    }
9830    let mut received = 0_u128;
9831    let mut sent = 0_u128;
9832    let mut total_inputs = 0_u128;
9833    let mut all_inputs_known = true;
9834    for output in &transaction.outputs {
9835        if output.address.version == 0 && programs.contains(&output.address.hash) {
9836            received = received
9837                .checked_add(u128::from(output.value.get()))
9838                .ok_or(HnsWalletError::Arithmetic)?;
9839        }
9840    }
9841    for input in &transaction.inputs {
9842        if input.previous_output.is_null() {
9843            all_inputs_known = false;
9844            continue;
9845        }
9846        let parent_id = TransactionHash::new(input.previous_output.transaction_hash.into_bytes());
9847        if let Entry::Vacant(entry) = raw_cache.entry(parent_id) {
9848            let evidence =
9849                backend.get_transaction_evidence(parent_id, binding, Some(mempool_binding))?;
9850            if evidence.binding != binding || evidence.mempool != mempool_binding {
9851                return Err(HnsWalletError::StaleNodeSnapshot);
9852            }
9853            let raw = match evidence.raw {
9854                Some(raw) => raw,
9855                None => match persisted_raw.get(&parent_id) {
9856                    Some(raw) => raw.clone(),
9857                    None => {
9858                        all_inputs_known = false;
9859                        continue;
9860                    }
9861                },
9862            };
9863            let parent = decode_transaction_for_id(&raw, parent_id)?;
9864            entry.insert(parent);
9865        }
9866        let parent = raw_cache
9867            .get(&parent_id)
9868            .ok_or(HnsWalletError::InvalidEvidence)?;
9869        let Some(previous_output) = parent.outputs.get(input.previous_output.index as usize) else {
9870            return Err(HnsWalletError::InvalidEvidence);
9871        };
9872        total_inputs = total_inputs
9873            .checked_add(u128::from(previous_output.value.get()))
9874            .ok_or(HnsWalletError::Arithmetic)?;
9875        if previous_output.address.version == 0 && programs.contains(&previous_output.address.hash)
9876        {
9877            sent = sent
9878                .checked_add(u128::from(previous_output.value.get()))
9879                .ok_or(HnsWalletError::Arithmetic)?;
9880        }
9881    }
9882    let (negative, magnitude) = if sent > received {
9883        (true, sent - received)
9884    } else {
9885        (false, received - sent)
9886    };
9887    let total_outputs = transaction
9888        .outputs
9889        .iter()
9890        .try_fold(0_u128, |total, output| {
9891            total
9892                .checked_add(u128::from(output.value.get()))
9893                .ok_or(HnsWalletError::Arithmetic)
9894        })?;
9895    let fee = if all_inputs_known && total_inputs >= total_outputs {
9896        Some(BaseUnits::new(total_inputs - total_outputs))
9897    } else {
9898        None
9899    };
9900    Ok((
9901        SignedBaseUnits {
9902            negative,
9903            magnitude: BaseUnits::new(magnitude),
9904        },
9905        fee,
9906    ))
9907}
9908
9909fn persist_reconciled_entities(
9910    store: &mut WalletStore,
9911    config: &HnsRuntimeConfig,
9912    coins: &[TrackedHnsCoin],
9913    transactions: &[HnsTransactionRecord],
9914    now_unix: u64,
9915) -> Result<(), HnsWalletError> {
9916    let entity_prefix = account_entity_prefix(config);
9917    let existing_coins = store.list_entities_by_id_prefix::<TrackedHnsCoin>(
9918        EntityKind::HnsUtxo,
9919        &entity_prefix,
9920        MAX_WALLET_COINS,
9921    )?;
9922    let mut revisions: BTreeMap<Vec<u8>, u64> = existing_coins
9923        .iter()
9924        .map(|entity| (entity.id.clone(), entity.revision))
9925        .collect();
9926    for coin in coins {
9927        let id = namespaced_outpoint_id(config, coin.coin.outpoint);
9928        let revision = revisions.remove(id.as_slice()).unwrap_or(0);
9929        store.save_hns_utxo(&id, revision, coin, now_unix)?;
9930    }
9931    for (id, revision) in revisions {
9932        store.delete_hns_utxo(&id, revision)?;
9933    }
9934
9935    let existing_transactions = store.list_entities_by_id_prefix::<HnsTransactionRecord>(
9936        EntityKind::HnsTransaction,
9937        &entity_prefix,
9938        MAX_HISTORY_RESULTS,
9939    )?;
9940    let mut revisions: BTreeMap<Vec<u8>, u64> = existing_transactions
9941        .iter()
9942        .map(|entity| (entity.id.clone(), entity.revision))
9943        .collect();
9944    for transaction in transactions {
9945        let id = namespaced_transaction_id(config, transaction.summary.txid);
9946        let revision = revisions.remove(id.as_slice()).unwrap_or(0);
9947        store.save_hns_transaction(&id, revision, transaction, now_unix)?;
9948    }
9949    for (id, revision) in revisions {
9950        store.delete_hns_transaction(&id, revision)?;
9951    }
9952    Ok(())
9953}
9954
9955fn account_entity_prefix(config: &HnsRuntimeConfig) -> [u8; 32] {
9956    let mut prefix = [0_u8; 32];
9957    prefix[..16].copy_from_slice(config.wallet_id.as_bytes());
9958    prefix[16..].copy_from_slice(config.account_id.as_bytes());
9959    prefix
9960}
9961
9962/// Public namespace for this exact account's authenticated transaction history.
9963pub fn hns_account_transaction_history_prefix(config: &HnsRuntimeConfig) -> [u8; 32] {
9964    account_entity_prefix(config)
9965}
9966
9967fn account_entity_id(config: &HnsRuntimeConfig) -> [u8; 32] {
9968    account_entity_prefix(config)
9969}
9970
9971fn recovery_entity_id(config: &HnsRuntimeConfig) -> [u8; 33] {
9972    let mut id = [0_u8; 33];
9973    id[..32].copy_from_slice(&account_entity_prefix(config));
9974    id[32] = 1;
9975    id
9976}
9977
9978fn derived_address_id(config: &HnsRuntimeConfig, change: u32, index: u32) -> [u8; 40] {
9979    let mut id = [0_u8; 40];
9980    id[..32].copy_from_slice(&account_entity_prefix(config));
9981    id[32..36].copy_from_slice(&change.to_be_bytes());
9982    id[36..].copy_from_slice(&index.to_be_bytes());
9983    id
9984}
9985
9986fn shakedex_derived_address_id(config: &HnsRuntimeConfig, change: u32, index: u32) -> [u8; 41] {
9987    let mut id = [0_u8; 41];
9988    id[..32].copy_from_slice(&account_entity_prefix(config));
9989    id[32] = HNS_SHAKEDEX_DERIVATION_TAG;
9990    id[33..37].copy_from_slice(&change.to_be_bytes());
9991    id[37..].copy_from_slice(&index.to_be_bytes());
9992    id
9993}
9994
9995fn derived_address_record_id(
9996    config: &HnsRuntimeConfig,
9997    derivation: DerivationReference,
9998) -> Result<Vec<u8>, HnsWalletError> {
9999    if derivation.account != config.account_derivation_index {
10000        return Err(HnsWalletError::InvalidEvidence);
10001    }
10002    match restore_derivation_key(derivation)? {
10003        (HNS_COIN_DERIVATION_TAG, change, index) => {
10004            Ok(derived_address_id(config, change, index).to_vec())
10005        }
10006        (HNS_SHAKEDEX_DERIVATION_TAG, change, index) => {
10007            Ok(shakedex_derived_address_id(config, change, index).to_vec())
10008        }
10009        _ => Err(HnsWalletError::InvalidEvidence),
10010    }
10011}
10012
10013fn namespaced_outpoint_id(config: &HnsRuntimeConfig, outpoint: HnsOutpoint) -> [u8; 68] {
10014    let mut id = [0_u8; 68];
10015    id[..32].copy_from_slice(&account_entity_prefix(config));
10016    id[32..64].copy_from_slice(outpoint.transaction.as_bytes());
10017    id[64..].copy_from_slice(&outpoint.output_index.to_le_bytes());
10018    id
10019}
10020
10021fn namespaced_transaction_id(config: &HnsRuntimeConfig, transaction: TransactionHash) -> [u8; 64] {
10022    let mut id = [0_u8; 64];
10023    id[..32].copy_from_slice(&account_entity_prefix(config));
10024    id[32..].copy_from_slice(transaction.as_bytes());
10025    id
10026}
10027
10028fn namespaced_name_id(config: &HnsRuntimeConfig, name_hash: [u8; 32]) -> [u8; 64] {
10029    let mut id = [0_u8; 64];
10030    id[..32].copy_from_slice(&account_entity_prefix(config));
10031    id[32..].copy_from_slice(&name_hash);
10032    id
10033}
10034
10035fn persisted_name_addresses(
10036    store: &WalletStore,
10037    config: &HnsRuntimeConfig,
10038) -> Result<Vec<DerivedHnsAddress>, HnsWalletError> {
10039    let mut addresses = Vec::new();
10040    for stored in store.list_entities_by_id_prefix::<DerivedHnsAddress>(
10041        EntityKind::DerivedAddress,
10042        &account_entity_prefix(config),
10043        MAX_RESTORE_SCRIPTS_PER_QUERY,
10044    )? {
10045        let expected_id = derived_address_record_id(config, stored.value.derivation)?;
10046        if stored.id != expected_id
10047            || stored.value.account_id != config.account_id
10048            || stored.value.derivation.account != config.account_derivation_index
10049        {
10050            return Err(HnsWalletError::InvalidEvidence);
10051        }
10052        if is_wallet_name_control_derivation(stored.value.derivation) {
10053            addresses.push(stored.value);
10054        }
10055    }
10056    addresses.sort_by_key(|address| address.derivation.index);
10057    validate_wallet_name_addresses(&addresses)?;
10058    Ok(addresses)
10059}
10060
10061fn persist_derived_addresses(
10062    store: &mut WalletStore,
10063    config: &HnsRuntimeConfig,
10064    addresses: &[DerivedHnsAddress],
10065    now_unix: u64,
10066) -> Result<(), HnsWalletError> {
10067    if addresses.is_empty() || addresses.len() > MAX_RESTORE_ADDRESS_RECORDS {
10068        return Err(HnsWalletError::ScanCapacityExhausted);
10069    }
10070    let mut ids = BTreeSet::new();
10071    let mut programs = BTreeSet::new();
10072    for address in addresses {
10073        if address.account_id != config.account_id
10074            || validate_restore_program(address.derivation, &address.program).is_err()
10075            || !programs.insert(address.program.clone())
10076        {
10077            return Err(HnsWalletError::InvalidEvidence);
10078        }
10079        let id = derived_address_record_id(config, address.derivation)?;
10080        if !ids.insert(id.clone()) {
10081            return Err(HnsWalletError::InvalidEvidence);
10082        }
10083        let existing = store.derived_address::<DerivedHnsAddress>(&id)?;
10084        if existing.as_ref().is_some_and(|stored| {
10085            stored.id != id
10086                || stored.value.account_id != address.account_id
10087                || stored.value.derivation != address.derivation
10088                || stored.value.address != address.address
10089                || stored.value.program != address.program
10090        }) {
10091            return Err(HnsWalletError::InvalidEvidence);
10092        }
10093        let revision = existing.map_or(0, |stored| stored.revision);
10094        store.save_derived_address(&id, revision, address, now_unix)?;
10095    }
10096    Ok(())
10097}
10098
10099fn account_input_reservations(
10100    store: &WalletStore,
10101    config: &HnsRuntimeConfig,
10102) -> Result<Vec<StoredEntity<HnsInputReservation>>, HnsWalletError> {
10103    let reservations = store.list_entities_by_id_prefix::<HnsInputReservation>(
10104        EntityKind::InputReservation,
10105        &account_entity_prefix(config),
10106        MAX_WALLET_COINS,
10107    )?;
10108    for stored in &reservations {
10109        let expected_id = namespaced_outpoint_id(config, stored.value.outpoint);
10110        if stored.value.wallet_id != config.wallet_id
10111            || stored.value.account_id != config.account_id
10112            || stored.id.as_slice() != expected_id.as_slice()
10113        {
10114            return Err(HnsWalletError::InvalidEvidence);
10115        }
10116    }
10117    Ok(reservations)
10118}
10119
10120fn active_input_reservation_outpoints(
10121    store: &WalletStore,
10122    config: &HnsRuntimeConfig,
10123    now_unix: u64,
10124) -> Result<BTreeSet<HnsOutpoint>, HnsWalletError> {
10125    Ok(account_input_reservations(store, config)?
10126        .into_iter()
10127        .filter(|stored| {
10128            stored.value.kind.is_protected_shakedex()
10129                || stored
10130                    .value
10131                    .expires_at_unix
10132                    .is_none_or(|expiry| expiry > now_unix)
10133        })
10134        .map(|stored| stored.value.outpoint)
10135        .collect())
10136}
10137
10138fn available_unreserved_coins(
10139    store: &mut WalletStore,
10140    config: &HnsRuntimeConfig,
10141    coins: Vec<TrackedHnsCoin>,
10142    now_unix: u64,
10143) -> Result<Vec<TrackedHnsCoin>, HnsWalletError> {
10144    let reservations = account_input_reservations(store, config)?;
10145    let mut reserved = BTreeSet::new();
10146    let mut expired = Vec::new();
10147    for stored in reservations {
10148        if stored
10149            .value
10150            .expires_at_unix
10151            .is_some_and(|expiry| expiry <= now_unix)
10152            && !stored.value.kind.is_protected_shakedex()
10153        {
10154            expired.push(EntityBatchDelete {
10155                id: stored.id,
10156                expected_revision: stored.revision,
10157            });
10158        } else {
10159            reserved.insert(stored.value.outpoint);
10160        }
10161    }
10162    if !expired.is_empty() {
10163        store.apply_entity_batch::<HnsInputReservation>(
10164            EntityKind::InputReservation,
10165            &[],
10166            &expired,
10167        )?;
10168    }
10169    Ok(coins
10170        .into_iter()
10171        .filter(|coin| {
10172            is_ordinary_hns_derivation(coin.derivation) && !reserved.contains(&coin.coin.outpoint)
10173        })
10174        .collect())
10175}
10176
10177fn reservation_saves(
10178    config: &HnsRuntimeConfig,
10179    workflow_id: WorkflowId,
10180    inputs: &[TrackedHnsCoin],
10181    expires_at_unix: u64,
10182    now_unix: u64,
10183) -> Result<Vec<EntityBatchSave<HnsInputReservation>>, HnsWalletError> {
10184    let mut saves = Vec::with_capacity(inputs.len());
10185    for input in inputs {
10186        if !is_ordinary_hns_derivation(input.derivation) {
10187            return Err(HnsWalletError::InvalidWorkflow);
10188        }
10189        let reservation = HnsInputReservation {
10190            wallet_id: config.wallet_id,
10191            account_id: config.account_id,
10192            outpoint: input.coin.outpoint,
10193            workflow_id,
10194            expires_at_unix: Some(expires_at_unix),
10195            kind: HnsInputReservationKind::Ordinary,
10196        };
10197        saves.push(EntityBatchSave {
10198            id: namespaced_outpoint_id(config, input.coin.outpoint).to_vec(),
10199            expected_revision: 0,
10200            value: reservation,
10201            updated_at_unix: now_unix,
10202        });
10203    }
10204    Ok(saves)
10205}
10206
10207fn validate_prepared_reservations(
10208    store: &WalletStore,
10209    config: &HnsRuntimeConfig,
10210    workflow_id: WorkflowId,
10211    outpoints: &[HnsOutpoint],
10212    expires_at_unix: u64,
10213) -> Result<(), HnsWalletError> {
10214    if outpoints.is_empty() || outpoints.len() > MAX_WALLET_COINS {
10215        return Err(HnsWalletError::InvalidWorkflow);
10216    }
10217    let expected: BTreeSet<HnsOutpoint> = outpoints.iter().copied().collect();
10218    if expected.len() != outpoints.len() {
10219        return Err(HnsWalletError::InvalidWorkflow);
10220    }
10221    let reservations = account_input_reservations(store, config)?;
10222    let matching: Vec<_> = reservations
10223        .into_iter()
10224        .filter(|stored| stored.value.workflow_id == workflow_id)
10225        .collect();
10226    if matching.len() != expected.len() {
10227        return Err(HnsWalletError::InvalidWorkflow);
10228    }
10229    for stored in matching {
10230        let expected_id = namespaced_outpoint_id(config, stored.value.outpoint);
10231        if !expected.contains(&stored.value.outpoint)
10232            || stored.id.as_slice() != expected_id.as_slice()
10233            || stored.value.expires_at_unix != Some(expires_at_unix)
10234            || stored.value.kind != HnsInputReservationKind::Ordinary
10235        {
10236            return Err(HnsWalletError::InvalidWorkflow);
10237        }
10238    }
10239    Ok(())
10240}
10241
10242fn reservation_activation_saves(
10243    store: &WalletStore,
10244    config: &HnsRuntimeConfig,
10245    workflow_id: WorkflowId,
10246    now_unix: u64,
10247) -> Result<Vec<EntityBatchSave<HnsInputReservation>>, HnsWalletError> {
10248    let reservations = account_input_reservations(store, config)?;
10249    let mut saves = Vec::new();
10250    for stored in reservations {
10251        if stored.value.workflow_id != workflow_id {
10252            continue;
10253        }
10254        if stored.value.kind.is_protected_shakedex() {
10255            return Err(HnsWalletError::InvalidWorkflow);
10256        }
10257        let mut reservation = stored.value;
10258        reservation.expires_at_unix = None;
10259        saves.push(EntityBatchSave {
10260            id: stored.id,
10261            expected_revision: stored.revision,
10262            value: reservation,
10263            updated_at_unix: now_unix,
10264        });
10265    }
10266    Ok(saves)
10267}
10268
10269fn reservation_deletes(
10270    store: &WalletStore,
10271    config: &HnsRuntimeConfig,
10272    workflow_id: WorkflowId,
10273) -> Result<Vec<EntityBatchDelete>, HnsWalletError> {
10274    let reservations = account_input_reservations(store, config)?;
10275    let mut deletes = Vec::new();
10276    for stored in reservations {
10277        if stored.value.workflow_id == workflow_id {
10278            if stored.value.kind.is_protected_shakedex() {
10279                return Err(HnsWalletError::InvalidWorkflow);
10280            }
10281            deletes.push(EntityBatchDelete {
10282                id: stored.id,
10283                expected_revision: stored.revision,
10284            });
10285        }
10286    }
10287    Ok(deletes)
10288}
10289
10290fn persist_observed_send_stage(
10291    store: &mut WalletStore,
10292    config: &HnsRuntimeConfig,
10293    expected: &StoredWorkflow<HnsSendWorkflow>,
10294    next_stage: HnsSendStage,
10295    now_unix: u64,
10296) -> Result<(), HnsWalletError> {
10297    if !matches!(
10298        next_stage,
10299        HnsSendStage::Mempool | HnsSendStage::Confirmed | HnsSendStage::Conflicted
10300    ) || expected.state.plan.wallet_id != config.wallet_id
10301        || expected.state.plan.account_id != config.account_id
10302        || expected.state.plan.workflow_id != expected.id
10303        || !matches!(
10304            expected.state.stage,
10305            HnsSendStage::Authorized
10306                | HnsSendStage::Broadcast
10307                | HnsSendStage::Mempool
10308                | HnsSendStage::RequiresRebroadcast
10309        )
10310        || expected.state.transaction.is_none()
10311        || expected.state.signed_transaction.is_none()
10312    {
10313        return Err(HnsWalletError::InvalidWorkflow);
10314    }
10315    if expected.state.stage == next_stage {
10316        return Ok(());
10317    }
10318    let current = store
10319        .load_workflow::<HnsSendWorkflow>(expected.id)?
10320        .ok_or(HnsWalletError::InvalidWorkflow)?;
10321    if current.revision != expected.revision || current.state != expected.state {
10322        return Err(HnsWalletError::InvalidWorkflow);
10323    }
10324    let mut state = current.state;
10325    state.stage = next_stage;
10326    let deletes = if matches!(
10327        next_stage,
10328        HnsSendStage::Confirmed | HnsSendStage::Conflicted
10329    ) {
10330        reservation_deletes(store, config, expected.id)?
10331    } else {
10332        Vec::new()
10333    };
10334    store.save_workflow_with_entity_batch::<_, HnsInputReservation>(
10335        expected.id,
10336        WorkflowKind::HnsSend,
10337        current.revision,
10338        &state,
10339        true,
10340        now_unix,
10341        EntityKind::InputReservation,
10342        &[],
10343        &deletes,
10344    )?;
10345    Ok(())
10346}
10347
10348fn abandon_obsolete_dropped_send(
10349    store: &mut WalletStore,
10350    config: &HnsRuntimeConfig,
10351    workflow_id: WorkflowId,
10352    dropped: &BTreeSet<TransactionHash>,
10353    now_unix: u64,
10354) -> Result<(), HnsWalletError> {
10355    let stored = store
10356        .load_workflow::<HnsSendWorkflow>(workflow_id)?
10357        .ok_or(HnsWalletError::InvalidWorkflow)?;
10358    let transaction = stored
10359        .state
10360        .transaction
10361        .ok_or(HnsWalletError::InvalidWorkflow)?;
10362    if stored.state.plan.wallet_id != config.wallet_id
10363        || stored.state.plan.account_id != config.account_id
10364        || stored.state.plan.workflow_id != workflow_id
10365        || !matches!(
10366            stored.state.stage,
10367            HnsSendStage::Authorized
10368                | HnsSendStage::Broadcast
10369                | HnsSendStage::Mempool
10370                | HnsSendStage::RequiresRebroadcast
10371        )
10372        || !dropped.contains(&transaction)
10373        || stored.state.signed_transaction.is_none()
10374        || stored.state.fee_quote.is_none()
10375    {
10376        return Err(HnsWalletError::InvalidWorkflow);
10377    }
10378
10379    let expected = stored
10380        .state
10381        .plan
10382        .inputs
10383        .iter()
10384        .map(|input| input.coin.outpoint)
10385        .collect::<BTreeSet<_>>();
10386    let matching = account_input_reservations(store, config)?
10387        .into_iter()
10388        .filter(|reservation| reservation.value.workflow_id == workflow_id)
10389        .collect::<Vec<_>>();
10390    if expected.is_empty()
10391        || expected.len() != stored.state.plan.inputs.len()
10392        || matching.len() != expected.len()
10393        || matching.iter().any(|reservation| {
10394            !expected.contains(&reservation.value.outpoint)
10395                || reservation.value.expires_at_unix.is_some()
10396                || reservation.value.kind != HnsInputReservationKind::Ordinary
10397        })
10398    {
10399        return Err(HnsWalletError::InvalidWorkflow);
10400    }
10401
10402    let mut state = stored.state;
10403    state.stage = HnsSendStage::Abandoned;
10404    let deletes = reservation_deletes(store, config, workflow_id)?;
10405    store.save_workflow_with_entity_batch::<_, HnsInputReservation>(
10406        workflow_id,
10407        WorkflowKind::HnsSend,
10408        stored.revision,
10409        &state,
10410        true,
10411        now_unix,
10412        EntityKind::InputReservation,
10413        &[],
10414        &deletes,
10415    )?;
10416    Ok(())
10417}
10418
10419fn release_reservations(
10420    store: &mut WalletStore,
10421    config: &HnsRuntimeConfig,
10422    workflow_id: WorkflowId,
10423) -> Result<(), HnsWalletError> {
10424    let deletes = reservation_deletes(store, config, workflow_id)?;
10425    if !deletes.is_empty() {
10426        store.apply_entity_batch::<HnsInputReservation>(
10427            EntityKind::InputReservation,
10428            &[],
10429            &deletes,
10430        )?;
10431    }
10432    Ok(())
10433}
10434
10435impl<B: HnsBackend, C: HnsClock> ChainModule for HnsWalletRuntime<B, C> {
10436    fn module_id(&self) -> ModuleId {
10437        ModuleId::Handshake
10438    }
10439
10440    fn capabilities(&self) -> ChainCapabilities {
10441        let config = self
10442            .cache_read()
10443            .map(|cache| cache.account.config.clone())
10444            .ok();
10445        ChainCapabilities {
10446            receive: true,
10447            send: config.as_ref().is_some_and(|config| {
10448                HNS_VALUE_RUNTIME_RELEASE_QUALIFIED
10449                    && HNS_FEE_QUOTE_ALGEBRA_RELEASE_QUALIFIED
10450                    && config.value_operations_enabled
10451            }),
10452            history: true,
10453            atomic_settlement: config.as_ref().is_some_and(|config| {
10454                HNS_VALUE_RUNTIME_RELEASE_QUALIFIED
10455                    && HNS_FEE_QUOTE_ALGEBRA_RELEASE_QUALIFIED
10456                    && config.settlement_enabled
10457            }),
10458            hash_algorithm: HashAlgorithm::Sha256,
10459            locktime_model: LocktimeModel::BlockHeight,
10460            finality_model: FinalityModel::ProofOfWorkConfirmations,
10461            fee_model: FeeModel::WeightRate,
10462        }
10463    }
10464
10465    fn sync_status(&self) -> SyncStatus {
10466        self.cache_read().map_or(
10467            SyncStatus {
10468                phase: SyncPhase::Degraded,
10469                validated_height: 0,
10470                scanned_height: 0,
10471                target_height: None,
10472                last_error: Some("wallet runtime lock is unavailable".to_owned()),
10473            },
10474            |cache| cache.sync.clone(),
10475        )
10476    }
10477
10478    fn balance(&self) -> Result<Amount, ChainError> {
10479        let (config, coins) = {
10480            let cache = self.cache_read().map_err(map_chain_error)?;
10481            ensure_ready(&cache)?;
10482            (cache.account.config.clone(), cache.coins.clone())
10483        };
10484        let now = self.clock.now_unix().map_err(map_chain_error)?;
10485        let store = self.store_lock().map_err(map_chain_error)?;
10486        let reserved =
10487            active_input_reservation_outpoints(&store, &config, now).map_err(map_chain_error)?;
10488        let total = coins.iter().try_fold(BaseUnits::ZERO, |total, coin| {
10489            if !is_confirmed_ordinary_hns_spend_candidate(coin)
10490                || reserved.contains(&coin.coin.outpoint)
10491            {
10492                Ok(total)
10493            } else {
10494                total
10495                    .checked_add(coin.coin.value)
10496                    .map_err(|_| ChainError::Overflow)
10497            }
10498        })?;
10499        Ok(Amount {
10500            asset: WalletAsset::Hns,
10501            base_units: total,
10502        })
10503    }
10504
10505    fn transaction_history(&self) -> Result<Vec<TransactionSummary>, ChainError> {
10506        let cache = self.cache_read().map_err(map_chain_error)?;
10507        ensure_ready(&cache)?;
10508        Ok(cache
10509            .transactions
10510            .iter()
10511            .map(|record| record.summary.clone())
10512            .collect())
10513    }
10514
10515    fn receive_target(&self) -> Result<ReceiveTarget, ChainError> {
10516        let cache = self.cache_read().map_err(map_chain_error)?;
10517        ensure_ready(&cache)?;
10518        drop(cache);
10519        self.local_receive_target().map_err(map_chain_error)
10520    }
10521
10522    fn prepare_send(&self, request: SendRequest) -> Result<PreparedSend, ChainError> {
10523        request.validate()?;
10524        if request.request_nonce == 0
10525            || request.amount.asset != WalletAsset::Hns
10526            || request.maximum_fee.is_zero()
10527        {
10528            return Err(ChainError::InvalidRequest("invalid Handshake send terms"));
10529        }
10530        let now = self.clock.now_unix().map_err(map_chain_error)?;
10531        let cache = self.cache_read().map_err(map_chain_error)?;
10532        ensure_ready(&cache)?;
10533        if !cache.account.config.value_operations_enabled {
10534            return Err(ChainError::Disabled);
10535        }
10536        if request.account != cache.account.config.account_id {
10537            return Err(ChainError::InvalidRequest("account does not match runtime"));
10538        }
10539        let account = cache.account.clone();
10540        let account_revision = cache.account_revision;
10541        let coins = cache.coins.clone();
10542        drop(cache);
10543        let workflow_id = send_workflow_id(&account.config, request.request_nonce);
10544        let mut store = self.store_lock().map_err(map_chain_error)?;
10545        if let Some(stored) = store
10546            .load_workflow::<HnsSendWorkflow>(workflow_id)
10547            .map_err(map_chain_error)?
10548        {
10549            let prepared =
10550                Self::recover_prepared_send(&stored, &request, &account.config, workflow_id, now)?;
10551            let outpoints: Vec<HnsOutpoint> = stored
10552                .state
10553                .plan
10554                .inputs
10555                .iter()
10556                .map(|input| input.coin.outpoint)
10557                .collect();
10558            validate_prepared_reservations(
10559                &store,
10560                &account.config,
10561                workflow_id,
10562                &outpoints,
10563                stored.state.plan.expires_at_unix,
10564            )
10565            .map_err(map_chain_error)?;
10566            let committed_account = store
10567                .wallet_account::<HnsAccountRecord>(&account_entity_id(&account.config))
10568                .map_err(map_chain_error)?
10569                .ok_or(ChainError::InvalidEvidence)?;
10570            self.install_loaded_account(committed_account)
10571                .map_err(map_chain_error)?;
10572            return Ok(prepared);
10573        }
10574        let coins = available_unreserved_coins(&mut store, &account.config, coins, now)
10575            .map_err(map_chain_error)?;
10576        let destination = decode_hns_address(account.config.network, &request.destination)
10577            .map_err(map_chain_error)?;
10578        let change_derivation = DerivationReference {
10579            role: KeyRole::HnsCoin,
10580            account: account_number(&account),
10581            change: 1,
10582            index: account.next_change_index,
10583        };
10584        let change_public = derive_hns_account_public_key(&store, &account, change_derivation)
10585            .map_err(map_chain_error)?;
10586        let change = Address::new(
10587            0,
10588            public_key_hash(&change_public)
10589                .map_err(map_chain_error)?
10590                .to_vec(),
10591        )
10592        .map_err(|_| ChainError::InvalidRequest("invalid change address"))?;
10593        let fee_rate = self.backend.estimate_fee_rate(6).map_err(map_chain_error)?;
10594        let (transaction, selected, fee) = build_unsigned_payment(
10595            coins,
10596            destination,
10597            change,
10598            request.amount.base_units,
10599            fee_rate,
10600            request.maximum_fee,
10601            account.config.dust_threshold,
10602        )
10603        .map_err(map_chain_error)?;
10604        let expires_at_unix = now
10605            .checked_add(PREPARED_ARTIFACT_LIFETIME_SECONDS)
10606            .ok_or(ChainError::Overflow)?;
10607        let plan = HnsSpendPlan {
10608            wallet_id: account.config.wallet_id,
10609            account_id: account.config.account_id,
10610            workflow_id,
10611            request_nonce: request.request_nonce,
10612            unsigned_transaction: transaction
10613                .encode()
10614                .map_err(|_| ChainError::InvalidTransactionSize)?,
10615            inputs: selected,
10616            amount: request.amount.base_units,
10617            fee,
10618            maximum_fee: request.maximum_fee,
10619            destination: request.destination.clone(),
10620            expires_at_unix,
10621        };
10622        let workflow = HnsSendWorkflow {
10623            plan: plan.clone(),
10624            stage: HnsSendStage::Prepared,
10625            transaction: None,
10626            signed_transaction: None,
10627            fee_quote: None,
10628        };
10629        let reservation_saves = reservation_saves(
10630            &account.config,
10631            workflow_id,
10632            &workflow.plan.inputs,
10633            expires_at_unix,
10634            now,
10635        )
10636        .map_err(map_chain_error)?;
10637        let account_save =
10638            Self::change_account_save(&account, account_revision, change_derivation.index, now)
10639                .map_err(map_chain_error)?;
10640        let prepared = Self::prepared_send_from_plan(&plan)?;
10641        let (_, next_account_revision) = store
10642            .save_workflow_with_account_and_entity_batch(
10643                workflow_id,
10644                WorkflowKind::HnsSend,
10645                0,
10646                &workflow,
10647                false,
10648                now,
10649                &account_save,
10650                EntityKind::InputReservation,
10651                &reservation_saves,
10652                &[],
10653            )
10654            .map_err(map_chain_error)?;
10655        drop(store);
10656        self.install_committed_account(
10657            account_revision,
10658            next_account_revision,
10659            account_save.value,
10660            now,
10661        )
10662        .map_err(map_chain_error)?;
10663        Ok(prepared)
10664    }
10665
10666    fn authorize_send(&self, request: AuthorizeSend) -> Result<AuthorizedSend, ChainError> {
10667        let now = self.clock.now_unix().map_err(map_chain_error)?;
10668        if request.prepared.module != ModuleId::Handshake
10669            || now > request.prepared.expires_at_unix
10670            || request.approved_at_unix > now
10671        {
10672            return Err(ChainError::ApprovalRequired);
10673        }
10674        let plan: HnsSpendPlan =
10675            serde_json::from_slice(request.prepared.authorization_commitment())
10676                .map_err(|_| ChainError::InvalidRequest("invalid prepared Handshake send"))?;
10677        if plan.expires_at_unix != request.prepared.expires_at_unix
10678            || plan.amount != request.prepared.amount.base_units
10679            || plan.fee != request.prepared.fee
10680            || plan.destination != request.prepared.destination
10681        {
10682            return Err(ChainError::InvalidRequest("prepared send mismatch"));
10683        }
10684        let account = self.cache_read().map_err(map_chain_error)?.account.clone();
10685        if plan.wallet_id != account.config.wallet_id
10686            || plan.account_id != account.config.account_id
10687        {
10688            return Err(ChainError::InvalidEvidence);
10689        }
10690        let (pending_approval, signed, txid) = {
10691            let store = self.store_lock().map_err(map_chain_error)?;
10692            let pending_approval = store
10693                .get_pending_approval(request.approval_id, now)
10694                .map_err(map_chain_error)?
10695                .ok_or(ChainError::ApprovalRequired)?;
10696            let approved: HnsSendApproval = serde_json::from_slice(&pending_approval.request_json)
10697                .map_err(|_| ChainError::ApprovalRequired)?;
10698            let commitment: [u8; 32] =
10699                Sha256::digest(request.prepared.authorization_commitment()).into();
10700            if approved.workflow_id != plan.workflow_id || approved.commitment != commitment {
10701                return Err(ChainError::ApprovalRequired);
10702            }
10703            let stored = store
10704                .load_workflow::<HnsSendWorkflow>(plan.workflow_id)
10705                .map_err(map_chain_error)?
10706                .ok_or(ChainError::InvalidEvidence)?;
10707            if stored.state.plan != plan
10708                || stored.state.stage != HnsSendStage::Prepared
10709                || stored.state.transaction.is_some()
10710                || stored.state.signed_transaction.is_some()
10711                || stored.state.fee_quote.is_some()
10712            {
10713                return Err(ChainError::InvalidEvidence);
10714            }
10715            let signed = sign_payment_plan(&store, &account, &plan).map_err(map_chain_error)?;
10716            let transaction =
10717                validate_signed_payment_plan(&plan, &signed).map_err(map_chain_error)?;
10718            let input_coins = canonical_input_coins(&plan.inputs).map_err(map_chain_error)?;
10719            validate_standard_input_authorizations(&transaction, &input_coins)
10720                .map_err(map_chain_error)?;
10721            let txid = wallet_transaction_hash(&transaction).map_err(map_chain_error)?;
10722            (pending_approval, signed, txid)
10723        };
10724        let input_coins = canonical_input_coins(&plan.inputs).map_err(map_chain_error)?;
10725        let quote = self
10726            .quote_final_transaction(&signed, &input_coins, plan.fee, plan.maximum_fee)
10727            .map_err(map_chain_error)?;
10728        let commit_now = self.clock.now_unix().map_err(map_chain_error)?;
10729        if commit_now >= plan.expires_at_unix {
10730            return Err(ChainError::ApprovalRequired);
10731        }
10732        let mut store = self.store_lock().map_err(map_chain_error)?;
10733        let stored = store
10734            .load_workflow::<HnsSendWorkflow>(plan.workflow_id)
10735            .map_err(map_chain_error)?
10736            .ok_or(ChainError::InvalidEvidence)?;
10737        if stored.state.plan != plan
10738            || stored.state.stage != HnsSendStage::Prepared
10739            || stored.state.transaction.is_some()
10740            || stored.state.signed_transaction.is_some()
10741            || stored.state.fee_quote.is_some()
10742        {
10743            return Err(ChainError::InvalidEvidence);
10744        }
10745        let workflow = HnsSendWorkflow {
10746            plan,
10747            stage: HnsSendStage::Authorized,
10748            transaction: Some(txid),
10749            signed_transaction: Some(signed.clone()),
10750            fee_quote: Some(quote),
10751        };
10752        let reservation_saves = reservation_activation_saves(
10753            &store,
10754            &account.config,
10755            workflow.plan.workflow_id,
10756            commit_now,
10757        )
10758        .map_err(map_chain_error)?;
10759        let committed = store
10760            .consume_approval_and_save_workflow_with_entity_batch(
10761                &pending_approval,
10762                commit_now,
10763                workflow.plan.workflow_id,
10764                WorkflowKind::HnsSend,
10765                stored.revision,
10766                &workflow,
10767                true,
10768                EntityKind::InputReservation,
10769                &reservation_saves,
10770                &[],
10771            )
10772            .map_err(map_chain_error)?;
10773        if committed.is_none() {
10774            return Err(ChainError::ApprovalRequired);
10775        }
10776        AuthorizedSend::new(ModuleId::Handshake, request.approval_id, signed)
10777    }
10778
10779    fn broadcast_send(&self, request: BroadcastSend) -> Result<BroadcastReceipt, ChainError> {
10780        let raw = request.into_transaction();
10781        let transaction =
10782            Transaction::decode(&raw).map_err(|_| ChainError::InvalidTransactionSize)?;
10783        let txid = wallet_transaction_hash(&transaction).map_err(map_chain_error)?;
10784        let config = self
10785            .cache_read()
10786            .map_err(map_chain_error)?
10787            .account
10788            .config
10789            .clone();
10790        let stored = {
10791            let store = self.store_lock().map_err(map_chain_error)?;
10792            let workflows = store
10793                .list_workflows_complete::<HnsSendWorkflow>(
10794                    WorkflowKind::HnsSend,
10795                    MAX_HISTORY_RESULTS,
10796                )
10797                .map_err(map_chain_error)?;
10798            let stored = workflows
10799                .into_iter()
10800                .find(|workflow| {
10801                    workflow.state.plan.wallet_id == config.wallet_id
10802                        && workflow.state.plan.account_id == config.account_id
10803                        && workflow.state.transaction == Some(txid)
10804                        && workflow.state.signed_transaction.as_deref() == Some(raw.as_slice())
10805                })
10806                .ok_or(ChainError::InvalidEvidence)?;
10807            if stored.state.stage != HnsSendStage::Authorized {
10808                return Err(ChainError::InvalidEvidence);
10809            }
10810            let prior_quote = stored
10811                .state
10812                .fee_quote
10813                .as_ref()
10814                .ok_or(ChainError::InvalidEvidence)?;
10815            let input_coins =
10816                canonical_input_coins(&stored.state.plan.inputs).map_err(map_chain_error)?;
10817            let signed =
10818                validate_signed_payment_plan(&stored.state.plan, &raw).map_err(map_chain_error)?;
10819            validate_standard_input_authorizations(&signed, &input_coins)
10820                .map_err(map_chain_error)?;
10821            validate_final_fee_quote(
10822                &raw,
10823                &input_coins,
10824                prior_quote,
10825                prior_quote.binding,
10826                prior_quote.mempool,
10827                stored.state.plan.fee,
10828                stored.state.plan.maximum_fee,
10829            )
10830            .map_err(map_chain_error)?;
10831            stored
10832        };
10833        let raw = stored
10834            .state
10835            .signed_transaction
10836            .clone()
10837            .ok_or(ChainError::InvalidEvidence)?;
10838        let input_coins =
10839            canonical_input_coins(&stored.state.plan.inputs).map_err(map_chain_error)?;
10840        let quote = self
10841            .quote_final_transaction(
10842                &raw,
10843                &input_coins,
10844                stored.state.plan.fee,
10845                stored.state.plan.maximum_fee,
10846            )
10847            .map_err(map_chain_error)?;
10848        let submission_started_at = self.clock.now_unix().map_err(map_chain_error)?;
10849        let (submission_revision, submission_state) = {
10850            let mut store = self.store_lock().map_err(map_chain_error)?;
10851            let current = store
10852                .load_workflow::<HnsSendWorkflow>(stored.id)
10853                .map_err(map_chain_error)?
10854                .ok_or(ChainError::InvalidEvidence)?;
10855            if current.revision != stored.revision || current.state != stored.state {
10856                return Err(ChainError::InvalidEvidence);
10857            }
10858            let mut state = current.state;
10859            state.stage = HnsSendStage::RequiresRebroadcast;
10860            state.fee_quote = Some(quote);
10861            let revision = store
10862                .save_workflow(
10863                    stored.id,
10864                    WorkflowKind::HnsSend,
10865                    current.revision,
10866                    &state,
10867                    true,
10868                    submission_started_at,
10869                )
10870                .map_err(map_chain_error)?;
10871            (revision, state)
10872        };
10873        let accepted = self
10874            .backend
10875            .broadcast_transaction(&raw)
10876            .map_err(map_chain_error)?;
10877        if accepted != txid {
10878            return Err(ChainError::InvalidEvidence);
10879        }
10880        let accepted_at = self.clock.now_unix().map_err(map_chain_error)?;
10881        let mut store = self.store_lock().map_err(map_chain_error)?;
10882        let current = store
10883            .load_workflow::<HnsSendWorkflow>(stored.id)
10884            .map_err(map_chain_error)?
10885            .ok_or(ChainError::InvalidEvidence)?;
10886        if current.revision != submission_revision || current.state != submission_state {
10887            return Err(ChainError::InvalidEvidence);
10888        }
10889        let mut state = current.state;
10890        state.stage = HnsSendStage::Broadcast;
10891        store
10892            .save_workflow(
10893                stored.id,
10894                WorkflowKind::HnsSend,
10895                current.revision,
10896                &state,
10897                true,
10898                accepted_at,
10899            )
10900            .map_err(map_chain_error)?;
10901        Ok(BroadcastReceipt {
10902            module: ModuleId::Handshake,
10903            txid,
10904            accepted_at_unix: accepted_at,
10905        })
10906    }
10907}
10908
10909impl<B: HnsBackend, C: HnsClock> UtxoChainModule for HnsWalletRuntime<B, C> {
10910    fn list_utxos(&self) -> Result<Vec<Utxo>, ChainError> {
10911        let cache = self.cache_read().map_err(map_chain_error)?;
10912        ensure_ready(&cache)?;
10913        Ok(cache
10914            .coins
10915            .iter()
10916            .map(|coin| Utxo {
10917                txid: coin.coin.outpoint.transaction,
10918                output_index: coin.coin.outpoint.output_index,
10919                value: Amount {
10920                    asset: WalletAsset::Hns,
10921                    base_units: coin.coin.value,
10922                },
10923                confirmation_count: coin.coin.confirmation_count,
10924                spendable: is_confirmed_ordinary_hns_spend_candidate(coin),
10925            })
10926            .collect())
10927    }
10928
10929    fn fee_policy(&self) -> Result<UtxoFeePolicy, ChainError> {
10930        let rate = self.backend.estimate_fee_rate(6).map_err(map_chain_error)?;
10931        let dust = self
10932            .cache_read()
10933            .map_err(map_chain_error)?
10934            .account
10935            .config
10936            .dust_threshold;
10937        Ok(UtxoFeePolicy {
10938            base_units_per_kweight: rate,
10939            minimum_relay: rate,
10940            dust_threshold: dust,
10941        })
10942    }
10943
10944    fn prepare_htlc_lock(&self, request: HtlcLockRequest) -> Result<PreparedHtlcLock, ChainError> {
10945        self.prepare_lock(SettlementLockRequest {
10946            session_id: request.session_id,
10947            module: ModuleId::Handshake,
10948            amount: request.amount,
10949            hashlock: request.hashlock,
10950            receiver: hex::encode(request.receiver_key),
10951            refund_target: hex::encode(request.refund_key),
10952            absolute_timelock: request.absolute_timelock,
10953            maximum_fee: request.maximum_fee,
10954        })
10955        .map(|prepared| PreparedHtlcLock(prepared.0))
10956    }
10957
10958    fn verify_htlc_lock(
10959        &self,
10960        request: VerifyHtlcLockRequest,
10961    ) -> Result<VerifiedHtlcLock, ChainError> {
10962        self.verify_lock(VerifySettlementLockRequest {
10963            expected: request.expected,
10964            transaction_or_receipt: request.funding_transaction,
10965            confirmation_count: request.confirmation_count,
10966        })
10967        .map(|verified| VerifiedHtlcLock(verified.0))
10968    }
10969
10970    fn prepare_htlc_redeem(
10971        &self,
10972        request: HtlcRedeemRequest,
10973    ) -> Result<PreparedHtlcRedeem, ChainError> {
10974        self.prepare_redeem(SettlementRedeemRequest {
10975            session_id: request.session_id,
10976            lock: request.lock,
10977            preimage: request.preimage,
10978            maximum_fee: request.maximum_fee,
10979        })
10980        .map(|prepared| PreparedHtlcRedeem(prepared.0))
10981    }
10982
10983    fn prepare_htlc_refund(
10984        &self,
10985        request: HtlcRefundRequest,
10986    ) -> Result<PreparedHtlcRefund, ChainError> {
10987        self.prepare_refund(SettlementRefundRequest {
10988            session_id: request.session_id,
10989            lock: request.lock,
10990            current_chain_time: request.current_chain_time,
10991            maximum_fee: request.maximum_fee,
10992        })
10993        .map(|prepared| PreparedHtlcRefund(prepared.0))
10994    }
10995
10996    fn observe_preimage(
10997        &self,
10998        request: ObservePreimageRequest,
10999    ) -> Result<Option<Preimage>, ChainError> {
11000        self.observe_secret(request)
11001    }
11002}
11003
11004impl<B: HnsBackend, C: HnsClock> HnsWalletRuntime<B, C> {
11005    fn prepare_lock_with_publication(
11006        &self,
11007        request: SettlementLockRequest,
11008        publication: Option<hns_wallet_chain_api::SwapRecoveryPublication>,
11009    ) -> Result<PreparedSettlementLock, ChainError> {
11010        validate_settlement_request(&request)?;
11011        let now = self.clock.now_unix().map_err(map_chain_error)?;
11012        let cache = self.cache_read().map_err(map_chain_error)?;
11013        ensure_settlement_ready(&cache)?;
11014        let account = cache.account.clone();
11015        let coins = cache.coins.clone();
11016        drop(cache);
11017        let workflow_id = settlement_workflow_id(
11018            &account.config,
11019            request.session_id,
11020            HnsSettlementAction::Lock,
11021        );
11022        let mut store = self.store_lock().map_err(map_chain_error)?;
11023        if let Some(mut stored) = store
11024            .load_workflow::<HnsPreparedSettlement>(workflow_id)
11025            .map_err(map_chain_error)?
11026        {
11027            recovery_publication::validate_prepared_publication(&stored.state)
11028                .map_err(map_chain_error)?;
11029            match (&publication, &stored.state.recovery_publication) {
11030                (None, None) => {}
11031                (Some(expected), Some(package)) => {
11032                    let raws = package
11033                        .ancestors
11034                        .iter()
11035                        .map(|ancestor| ancestor.raw.clone())
11036                        .collect::<Vec<_>>();
11037                    let recovered = recover_hns_contract_from_ancestors(
11038                        expected.terms().network,
11039                        &stored.state.signed_transaction,
11040                        &raws,
11041                    )
11042                    .map_err(map_chain_error)?;
11043                    if recovered.terms != *expected.terms() || recovered.side != expected.side() {
11044                        return Err(ChainError::InvalidEvidence);
11045                    }
11046                }
11047                _ => return Err(ChainError::InvalidEvidence),
11048            }
11049            let expected_terms = HnsSettlementTerms::Lock {
11050                request: request.clone(),
11051            };
11052            if stored.kind != settlement_workflow_kind(HnsSettlementAction::Lock)
11053                || stored.state.wallet_id != account.config.wallet_id
11054                || stored.state.account_id != account.config.account_id
11055                || stored.state.workflow_id != workflow_id
11056                || stored.state.session_id != request.session_id
11057                || stored.state.action != HnsSettlementAction::Lock
11058                || stored.state.terms != expected_terms
11059            {
11060                return Err(ChainError::InvalidRequest(
11061                    "persisted Handshake settlement does not match retry",
11062                ));
11063            }
11064            let active_retry = stored.state.stage == HnsSettlementStage::Prepared
11065                && stored.state.expires_at_unix > now;
11066            if !active_retry {
11067                if !settlement_lock_workflow_may_be_reprepared(
11068                    stored.state.stage,
11069                    stored.state.expires_at_unix,
11070                    stored.irreversible_broadcast_prepared,
11071                    now,
11072                ) {
11073                    return Err(ChainError::InvalidRequest(
11074                        "persisted Handshake settlement does not match retry",
11075                    ));
11076                }
11077                if stored.state.stage == HnsSettlementStage::Prepared {
11078                    stored.state.stage = HnsSettlementStage::Expired;
11079                    let deletes = reservation_deletes(&store, &account.config, workflow_id)
11080                        .map_err(map_chain_error)?;
11081                    store
11082                        .save_workflow_with_entity_batch::<_, HnsInputReservation>(
11083                            workflow_id,
11084                            stored.kind,
11085                            stored.revision,
11086                            &stored.state,
11087                            false,
11088                            now,
11089                            EntityKind::InputReservation,
11090                            &[],
11091                            &deletes,
11092                        )
11093                        .map_err(map_chain_error)?;
11094                } else {
11095                    release_reservations(&mut store, &account.config, workflow_id)
11096                        .map_err(map_chain_error)?;
11097                }
11098            } else {
11099                if stored.state.maximum_fee != request.maximum_fee
11100                    || stored.state.fee > stored.state.maximum_fee
11101                {
11102                    return Err(ChainError::InvalidRequest(
11103                        "persisted Handshake settlement does not match retry",
11104                    ));
11105                }
11106                let prior_quote = stored
11107                    .state
11108                    .fee_quote
11109                    .as_ref()
11110                    .ok_or(ChainError::InvalidEvidence)?;
11111                let input_coins = stored
11112                    .state
11113                    .canonical_input_coins()
11114                    .map_err(map_chain_error)?;
11115                validate_final_fee_quote(
11116                    &stored.state.signed_transaction,
11117                    &input_coins,
11118                    prior_quote,
11119                    prior_quote.binding,
11120                    prior_quote.mempool,
11121                    stored.state.fee,
11122                    stored.state.maximum_fee,
11123                )
11124                .map_err(map_chain_error)?;
11125                let artifact =
11126                    Self::prepared_settlement_artifact(&stored.state).map_err(map_chain_error)?;
11127                let reserved_inputs = stored
11128                    .state
11129                    .recovery_publication
11130                    .as_ref()
11131                    .and_then(|package| package.ancestors.first())
11132                    .map_or(&stored.state.input_coins, |ancestor| &ancestor.inputs);
11133                let outpoints = reserved_inputs
11134                    .iter()
11135                    .map(|coin| coin.outpoint)
11136                    .collect::<Vec<_>>();
11137                validate_prepared_reservations(
11138                    &store,
11139                    &account.config,
11140                    workflow_id,
11141                    &outpoints,
11142                    stored.state.expires_at_unix,
11143                )
11144                .map_err(map_chain_error)?;
11145                let committed_account = store
11146                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&account.config))
11147                    .map_err(map_chain_error)?
11148                    .ok_or(ChainError::InvalidEvidence)?;
11149                self.install_loaded_account(committed_account)
11150                    .map_err(map_chain_error)?;
11151                return Ok(PreparedSettlementLock(artifact));
11152            }
11153        }
11154        let receiver = decode_compressed_key(&request.receiver)?;
11155        let refund = decode_compressed_key(&request.refund_target)?;
11156        let script = hns_htlc_script(
11157            request.hashlock,
11158            &receiver,
11159            &refund,
11160            request.absolute_timelock,
11161        )?;
11162        let lock_address = Address::new(0, Sha3_256::digest(&script).to_vec())
11163            .map_err(|_| ChainError::InvalidRequest("invalid Handshake HTLC address"))?;
11164        let change_derivation = DerivationReference {
11165            role: KeyRole::HnsCoin,
11166            account: account_number(&account),
11167            change: 1,
11168            index: account.next_change_index,
11169        };
11170        let coins = available_unreserved_coins(&mut store, &account.config, coins, now)
11171            .map_err(map_chain_error)?;
11172        let change_public = derive_hns_account_public_key(&store, &account, change_derivation)
11173            .map_err(map_chain_error)?;
11174        let change = Address::new(
11175            0,
11176            public_key_hash(&change_public)
11177                .map_err(map_chain_error)?
11178                .to_vec(),
11179        )
11180        .map_err(|_| ChainError::InvalidRequest("invalid change address"))?;
11181        let fee_rate = self.backend.estimate_fee_rate(6).map_err(map_chain_error)?;
11182        let (signed, selected, policy_input_evidence, input_coins, fee, recovery_package) =
11183            if let Some(publication) = &publication {
11184                let package = recovery_publication::prepare_hns_recoverable_funding(
11185                    &store,
11186                    &account,
11187                    coins,
11188                    publication,
11189                    fee_rate,
11190                    request.maximum_fee,
11191                )
11192                .map_err(map_chain_error)?;
11193                let input_coins = recovery_publication::canonical_package_inputs(&package.inputs)
11194                    .map_err(map_chain_error)?;
11195                (
11196                    package.raw,
11197                    package.initial_inputs,
11198                    package.inputs,
11199                    input_coins,
11200                    package.fee,
11201                    Some(recovery_publication::HnsRecoveryPackage {
11202                        network_encoding: publication
11203                            .terms()
11204                            .network
11205                            .encode()
11206                            .map_err(|_| ChainError::InvalidEvidence)?,
11207                        ancestors: package.ancestors,
11208                        final_submission_started_at_unix: None,
11209                        funding_submission_before_unix: None,
11210                    }),
11211                )
11212            } else {
11213                let (transaction, selected, fee) = build_unsigned_payment(
11214                    coins,
11215                    lock_address,
11216                    change,
11217                    request.amount.base_units,
11218                    fee_rate,
11219                    request.maximum_fee,
11220                    account.config.dust_threshold,
11221                )
11222                .map_err(map_chain_error)?;
11223                let policy_input_evidence =
11224                    input_coin_evidence(&selected).map_err(map_chain_error)?;
11225                let plan = HnsSpendPlan {
11226                    wallet_id: account.config.wallet_id,
11227                    account_id: account.config.account_id,
11228                    workflow_id,
11229                    request_nonce: 0,
11230                    unsigned_transaction: transaction
11231                        .encode()
11232                        .map_err(|_| ChainError::InvalidTransactionSize)?,
11233                    inputs: selected,
11234                    amount: request.amount.base_units,
11235                    fee,
11236                    maximum_fee: request.maximum_fee,
11237                    destination: hex::encode(Sha3_256::digest(&script)),
11238                    expires_at_unix: now
11239                        .checked_add(PREPARED_ARTIFACT_LIFETIME_SECONDS)
11240                        .ok_or(ChainError::Overflow)?,
11241                };
11242                let signed = sign_payment_plan(&store, &account, &plan).map_err(map_chain_error)?;
11243                let input_coins = canonical_input_coins(&plan.inputs).map_err(map_chain_error)?;
11244                let transaction =
11245                    validate_signed_payment_plan(&plan, &signed).map_err(map_chain_error)?;
11246                validate_standard_input_authorizations(&transaction, &input_coins)
11247                    .map_err(map_chain_error)?;
11248                (
11249                    signed,
11250                    plan.inputs,
11251                    policy_input_evidence,
11252                    input_coins,
11253                    fee,
11254                    None,
11255                )
11256            };
11257        let reservation_saves = reservation_saves(
11258            &account.config,
11259            workflow_id,
11260            &selected,
11261            now.checked_add(PREPARED_ARTIFACT_LIFETIME_SECONDS)
11262                .ok_or(ChainError::Overflow)?,
11263            now,
11264        )
11265        .map_err(map_chain_error)?;
11266        drop(store);
11267        let quote = self
11268            .quote_final_transaction(&signed, &input_coins, fee, request.maximum_fee)
11269            .map_err(map_chain_error)?;
11270        let cache = self.cache_read().map_err(map_chain_error)?;
11271        if cache.account != account {
11272            return Err(ChainError::InvalidEvidence);
11273        }
11274        let account_revision = cache.account_revision;
11275        drop(cache);
11276        let account_save =
11277            Self::change_account_save(&account, account_revision, change_derivation.index, now)
11278                .map_err(map_chain_error)?;
11279        let artifact = self
11280            .persist_prepared_settlement(
11281                request.session_id,
11282                HnsSettlementAction::Lock,
11283                signed,
11284                policy_input_evidence,
11285                fee,
11286                request.maximum_fee,
11287                quote,
11288                HnsSettlementTerms::Lock {
11289                    request: request.clone(),
11290                },
11291                recovery_package,
11292                None,
11293                &reservation_saves,
11294                Some(&account_save),
11295                now,
11296            )
11297            .map_err(map_chain_error)?;
11298        Ok(PreparedSettlementLock(artifact))
11299    }
11300}
11301
11302impl<B: HnsBackend, C: HnsClock> AtomicSettlement for HnsWalletRuntime<B, C> {
11303    fn settlement_capabilities(&self) -> SettlementCapabilities {
11304        let enabled = self.cache_read().is_ok_and(|cache| {
11305            HNS_VALUE_RUNTIME_RELEASE_QUALIFIED
11306                && HNS_FEE_QUOTE_ALGEBRA_RELEASE_QUALIFIED
11307                && cache.account.config.settlement_enabled
11308        });
11309        let minimum_confirmations = self
11310            .cache_read()
11311            .map_or(0, |cache| cache.account.config.minimum_confirmations);
11312        SettlementCapabilities {
11313            module: ModuleId::Handshake,
11314            supported: enabled,
11315            minimum_confirmations,
11316            maximum_lock_bytes: 256,
11317        }
11318    }
11319
11320    fn prepare_lock(
11321        &self,
11322        request: SettlementLockRequest,
11323    ) -> Result<PreparedSettlementLock, ChainError> {
11324        self.prepare_lock_with_publication(request, None)
11325    }
11326
11327    fn verify_lock(
11328        &self,
11329        request: VerifySettlementLockRequest,
11330    ) -> Result<VerifiedSettlementLock, ChainError> {
11331        let cache = self.cache_read().map_err(map_chain_error)?;
11332        ensure_settlement_ready(&cache)?;
11333        let configured_minimum = cache.account.config.minimum_confirmations;
11334        let binding = cache.binding.ok_or(ChainError::NotSynchronized)?;
11335        let mempool_binding = cache.mempool_binding.ok_or(ChainError::NotSynchronized)?;
11336        let config = cache.account.config.clone();
11337        drop(cache);
11338        if request.expected.module != ModuleId::Handshake
11339            || request.expected.amount.asset != WalletAsset::Hns
11340            || request.expected.absolute_timelock == 0
11341            || !hns_locktime_is_valid(request.expected.absolute_timelock)
11342            || request.expected.minimum_confirmations < configured_minimum
11343            || request.confirmation_count < request.expected.minimum_confirmations
11344            || request.confirmation_count < configured_minimum
11345        {
11346            return Err(ChainError::InvalidEvidence);
11347        }
11348        let receiver = decode_compressed_key(&request.expected.receiver)?;
11349        let refund = decode_compressed_key(&request.expected.refund_target)?;
11350        let script = hns_htlc_script(
11351            request.expected.hashlock,
11352            &receiver,
11353            &refund,
11354            request.expected.absolute_timelock,
11355        )?;
11356        let program = Sha3_256::digest(&script).to_vec();
11357        let transaction = Transaction::decode(&request.transaction_or_receipt)
11358            .map_err(|_| ChainError::InvalidEvidence)?;
11359        if transaction.is_coinbase() {
11360            return Err(ChainError::InvalidEvidence);
11361        }
11362        let txid = wallet_transaction_hash(&transaction).map_err(map_chain_error)?;
11363        let evidence = self
11364            .backend
11365            .get_transaction_evidence(txid, binding, Some(mempool_binding))
11366            .map_err(map_chain_error)?;
11367        if evidence.binding != binding
11368            || evidence.mempool != mempool_binding
11369            || evidence.raw.as_deref() != Some(request.transaction_or_receipt.as_slice())
11370        {
11371            return Err(ChainError::InvalidEvidence);
11372        }
11373        let status = evidence.status;
11374        if status.conflicted || status.confirmation_count != request.confirmation_count {
11375            return Err(ChainError::InvalidEvidence);
11376        }
11377        let inclusion = evidence.inclusion.ok_or(ChainError::InvalidEvidence)?;
11378        if inclusion.height > binding.tip.height
11379            || u64::from(status.confirmation_count) != binding.tip.height - inclusion.height + 1
11380        {
11381            return Err(ChainError::InvalidEvidence);
11382        }
11383        let amount = u64::try_from(request.expected.amount.base_units.get())
11384            .map_err(|_| ChainError::InvalidEvidence)?;
11385        let matches: Vec<usize> = transaction
11386            .outputs
11387            .iter()
11388            .enumerate()
11389            .filter(|(_, output)| {
11390                output.value.get() == amount
11391                    && output.address.version == 0
11392                    && output.address.hash == program
11393                    && output.covenant == Covenant::default()
11394            })
11395            .map(|(index, _)| index)
11396            .collect();
11397        if matches.len() != 1 {
11398            return Err(ChainError::InvalidEvidence);
11399        }
11400        let output_index = u32::try_from(matches[0]).map_err(|_| ChainError::InvalidEvidence)?;
11401        let funding_output = &transaction.outputs[matches[0]];
11402        let funding_coin = HnsInputCoinEvidence::from_canonical_coin(&Coin {
11403            outpoint: Outpoint {
11404                transaction_hash: CanonicalTransactionHash::new(txid.into_bytes()),
11405                index: output_index,
11406            },
11407            value: funding_output.value,
11408            height: Height::new(
11409                u32::try_from(inclusion.height).map_err(|_| ChainError::InvalidEvidence)?,
11410            ),
11411            coinbase: false,
11412            address: funding_output.address.clone(),
11413            covenant: funding_output.covenant.clone(),
11414        })
11415        .map_err(map_chain_error)?;
11416        let terms =
11417            serde_json::to_vec(&request.expected).map_err(|_| ChainError::InvalidEvidence)?;
11418        let mut evidence_hasher = Sha256::new();
11419        evidence_hasher.update(b"hns-wallet-rs/hns-verified-lock/v1");
11420        evidence_hasher.update(&request.transaction_or_receipt);
11421        evidence_hasher.update(inclusion.block_hash);
11422        evidence_hasher.update(inclusion.height.to_be_bytes());
11423        evidence_hasher.update(output_index.to_be_bytes());
11424        evidence_hasher.update(
11425            u64::try_from(terms.len())
11426                .map_err(|_| ChainError::InvalidEvidence)?
11427                .to_be_bytes(),
11428        );
11429        evidence_hasher.update(&terms);
11430        evidence_hasher.update(&script);
11431        let evidence_hash: [u8; 32] = evidence_hasher.finalize().into();
11432        let verified = VerifiedLock {
11433            module: ModuleId::Handshake,
11434            session_id: request.expected.session_id,
11435            funding_id: txid,
11436            amount: request.expected.amount,
11437            hashlock: request.expected.hashlock,
11438            absolute_timelock: request.expected.absolute_timelock,
11439            confirmation_count: request.confirmation_count,
11440            evidence_hash: ObjectHash::new(evidence_hash),
11441        };
11442        let record = HnsVerifiedSettlementRecord {
11443            expected: request.expected,
11444            verified: verified.clone(),
11445            output_index,
11446            script,
11447            funding_coin: Some(funding_coin),
11448        };
11449        let now = self.clock.now_unix().map_err(map_chain_error)?;
11450        let mut store = self.store_lock().map_err(map_chain_error)?;
11451        let id = settlement_entity_id(&config, record.expected.session_id);
11452        match store
11453            .hns_verified_settlement::<HnsVerifiedSettlementRecord>(&id)
11454            .map_err(map_chain_error)?
11455        {
11456            Some(stored) if stored.value == record => {
11457                return Ok(VerifiedSettlementLock(stored.value.verified));
11458            }
11459            Some(stored)
11460                if same_verified_settlement_binding(&stored.value, &record)
11461                    && record.verified.confirmation_count
11462                        >= stored.value.verified.confirmation_count =>
11463            {
11464                store
11465                    .save_hns_verified_settlement(&id, stored.revision, &record, now)
11466                    .map_err(map_chain_error)?;
11467            }
11468            Some(_) => return Err(ChainError::InvalidEvidence),
11469            None => {
11470                store
11471                    .save_hns_verified_settlement(&id, 0, &record, now)
11472                    .map_err(map_chain_error)?;
11473            }
11474        }
11475        Ok(VerifiedSettlementLock(verified))
11476    }
11477
11478    fn prepare_redeem(
11479        &self,
11480        request: SettlementRedeemRequest,
11481    ) -> Result<PreparedSettlementRedeem, ChainError> {
11482        let expected_hash: [u8; 32] =
11483            Sha256::digest(request.preimage.expose_for_settlement()).into();
11484        if expected_hash != *request.lock.hashlock.as_bytes() {
11485            return Err(ChainError::InvalidEvidence);
11486        }
11487        self.prepare_settlement_spend(
11488            request.session_id,
11489            request.lock,
11490            Some(request.preimage),
11491            request.maximum_fee,
11492            None,
11493            HnsSettlementAction::Redeem,
11494            None,
11495            None,
11496        )
11497        .map(PreparedSettlementRedeem)
11498    }
11499
11500    fn prepare_refund(
11501        &self,
11502        request: SettlementRefundRequest,
11503    ) -> Result<PreparedSettlementRefund, ChainError> {
11504        if !hns_refund_locktime_mature(request.lock.absolute_timelock, request.current_chain_time)
11505            .map_err(|_| ChainError::InvalidRequest("refund timelock is invalid or not mature"))?
11506        {
11507            return Err(ChainError::InvalidRequest("refund timelock is not mature"));
11508        }
11509        self.prepare_settlement_spend(
11510            request.session_id,
11511            request.lock,
11512            None,
11513            request.maximum_fee,
11514            Some(request.current_chain_time),
11515            HnsSettlementAction::Refund,
11516            None,
11517            None,
11518        )
11519        .map(PreparedSettlementRefund)
11520    }
11521
11522    fn observe_secret(
11523        &self,
11524        request: ObserveSecretRequest,
11525    ) -> Result<Option<Preimage>, ChainError> {
11526        let cache = self.cache_read().map_err(map_chain_error)?;
11527        ensure_settlement_ready(&cache)?;
11528        let binding = cache.binding.ok_or(ChainError::NotSynchronized)?;
11529        let mempool_binding = cache.mempool_binding.ok_or(ChainError::NotSynchronized)?;
11530        let config = cache.account.config.clone();
11531        drop(cache);
11532        let record = self
11533            .store_lock()
11534            .map_err(map_chain_error)?
11535            .hns_verified_settlement::<HnsVerifiedSettlementRecord>(&settlement_entity_id(
11536                &config,
11537                request.session_id,
11538            ))
11539            .map_err(map_chain_error)?
11540            .ok_or(ChainError::InvalidEvidence)?
11541            .value;
11542        if record.expected.session_id != request.session_id
11543            || record.expected.hashlock != request.hashlock
11544        {
11545            return Err(ChainError::InvalidEvidence);
11546        }
11547        let evidence = self
11548            .backend
11549            .get_transaction_evidence(request.spending_transaction, binding, Some(mempool_binding))
11550            .map_err(map_chain_error)?;
11551        if evidence.binding != binding || evidence.mempool != mempool_binding {
11552            return Err(ChainError::InvalidEvidence);
11553        }
11554        let status = evidence.status;
11555        if status.conflicted || (!status.in_mempool && status.confirmation_count == 0) {
11556            return Ok(None);
11557        }
11558        let raw = evidence.raw.ok_or(ChainError::InvalidEvidence)?;
11559        let transaction = decode_transaction_for_id(&raw, request.spending_transaction)
11560            .map_err(map_chain_error)?;
11561        let expected_outpoint = Outpoint {
11562            transaction_hash: CanonicalTransactionHash::new(
11563                record.verified.funding_id.into_bytes(),
11564            ),
11565            index: record.output_index,
11566        };
11567        let mut matching_input = None;
11568        for input in &transaction.inputs {
11569            if input.previous_output != expected_outpoint {
11570                continue;
11571            }
11572            if matching_input.replace(input).is_some() {
11573                return Err(ChainError::InvalidEvidence);
11574            }
11575        }
11576        let Some(input) = matching_input else {
11577            return Err(ChainError::InvalidEvidence);
11578        };
11579        if input.witness.items.len() != 4
11580            || input.witness.items[0].len() != 65
11581            || input.witness.items[1].len() != Preimage::LENGTH
11582            || input.witness.items[2].is_empty()
11583            || input.witness.items[3] != record.script
11584        {
11585            return Err(ChainError::InvalidEvidence);
11586        }
11587        let digest: [u8; 32] = Sha256::digest(&input.witness.items[1]).into();
11588        if digest != *record.expected.hashlock.as_bytes() {
11589            return Err(ChainError::InvalidEvidence);
11590        }
11591        let bytes: [u8; 32] = input.witness.items[1]
11592            .as_slice()
11593            .try_into()
11594            .map_err(|_| ChainError::InvalidEvidence)?;
11595        Ok(Some(Preimage::new(bytes)))
11596    }
11597}
11598
11599fn ensure_ready(cache: &HnsRuntimeCache) -> Result<(), ChainError> {
11600    if cache.sync.phase == SyncPhase::Ready
11601        && cache.sync.validated_height == cache.sync.scanned_height
11602    {
11603        Ok(())
11604    } else {
11605        Err(ChainError::NotSynchronized)
11606    }
11607}
11608
11609fn authoritative_unchanged_account_revision(
11610    prepared_account: &HnsAccountRecord,
11611    current_account: &HnsAccountRecord,
11612    current_revision: u64,
11613) -> Result<u64, ChainError> {
11614    if prepared_account != current_account {
11615        return Err(ChainError::InvalidEvidence);
11616    }
11617    Ok(current_revision)
11618}
11619
11620fn evidence_error_context(error: ChainError, context: &'static str) -> ChainError {
11621    match error {
11622        ChainError::InvalidEvidence => ChainError::InvalidEvidenceContext(context),
11623        other => other,
11624    }
11625}
11626
11627fn refreshed_verified_settlement_lock(
11628    stored: &VerifiedLock,
11629    candidate: &VerifiedLock,
11630) -> Result<VerifiedLock, ChainError> {
11631    if stored.module != candidate.module
11632        || stored.session_id != candidate.session_id
11633        || stored.funding_id != candidate.funding_id
11634        || stored.amount != candidate.amount
11635        || stored.hashlock != candidate.hashlock
11636        || stored.absolute_timelock != candidate.absolute_timelock
11637        || stored.evidence_hash != candidate.evidence_hash
11638    {
11639        return Err(ChainError::InvalidEvidenceContext(
11640            "verified HNS lock binding",
11641        ));
11642    }
11643    Ok(
11644        if stored.confirmation_count >= candidate.confirmation_count {
11645            stored.clone()
11646        } else {
11647            candidate.clone()
11648        },
11649    )
11650}
11651
11652fn map_chain_error<E>(error: E) -> ChainError
11653where
11654    HnsWalletError: From<E>,
11655{
11656    let error = HnsWalletError::from(error);
11657    match error {
11658        HnsWalletError::StoreLocked | HnsWalletError::MissingSeed => ChainError::Locked,
11659        HnsWalletError::MainnetDisabled | HnsWalletError::RuntimeIntegrationUnavailable => {
11660            ChainError::Disabled
11661        }
11662        HnsWalletError::InvalidAmount
11663        | HnsWalletError::InvalidAddress
11664        | HnsWalletError::InvalidPreparedArtifact
11665        | HnsWalletError::PreparedArtifactExpired
11666        | HnsWalletError::InvalidRuntimeConfiguration => {
11667            ChainError::InvalidRequest("invalid Handshake wallet request")
11668        }
11669        HnsWalletError::Arithmetic => ChainError::Overflow,
11670        HnsWalletError::FeeLimit => ChainError::FeeLimit,
11671        HnsWalletError::InsufficientFunds => {
11672            ChainError::InvalidRequest("insufficient Handshake funds")
11673        }
11674        HnsWalletError::InvalidEvidence
11675        | HnsWalletError::NameNotOwned
11676        | HnsWalletError::StaleNodeSnapshot
11677        | HnsWalletError::FeeQuoteInputUnavailable
11678        | HnsWalletError::InvalidFeeQuoteTransaction
11679        | HnsWalletError::InvalidFeeQuote => ChainError::InvalidEvidence,
11680        HnsWalletError::Store => ChainError::Backend("wallet store failed".to_owned()),
11681        // Keep these descriptions deliberately static: callers need an
11682        // actionable failure category, while backend strings, filesystem
11683        // paths, peer addresses, and key material must not cross the wallet
11684        // service boundary.
11685        HnsWalletError::Randomness => {
11686            ChainError::Backend("operating-system randomness is unavailable".to_owned())
11687        }
11688        HnsWalletError::WrongKeyRole | HnsWalletError::KeyDerivation | HnsWalletError::Address => {
11689            ChainError::Backend("Handshake wallet key derivation failed".to_owned())
11690        }
11691        HnsWalletError::StoreAuthorityMismatch
11692        | HnsWalletError::AccountConfigurationMismatch
11693        | HnsWalletError::DuplicateAccountDerivation => {
11694            ChainError::Backend("Handshake wallet account authority is inconsistent".to_owned())
11695        }
11696        HnsWalletError::StaleAccountRead | HnsWalletError::StaleAddressReservation => {
11697            ChainError::Backend("Handshake wallet state changed during preparation".to_owned())
11698        }
11699        HnsWalletError::RuntimePoisoned => {
11700            ChainError::Backend("Handshake wallet runtime lock is unavailable".to_owned())
11701        }
11702        HnsWalletError::Clock => {
11703            ChainError::Backend("Handshake wallet clock is unavailable".to_owned())
11704        }
11705        HnsWalletError::InvalidLookahead | HnsWalletError::ScanCapacityExhausted => {
11706            ChainError::Backend("Handshake wallet scan state is invalid".to_owned())
11707        }
11708        HnsWalletError::InvalidWorkflow => {
11709            ChainError::Backend("Handshake wallet workflow state is invalid".to_owned())
11710        }
11711        HnsWalletError::Signing => {
11712            ChainError::Backend("Handshake transaction signing failed".to_owned())
11713        }
11714        HnsWalletError::Encoding => {
11715            ChainError::Backend("Handshake wallet state encoding failed".to_owned())
11716        }
11717        HnsWalletError::HistoryLimit => {
11718            ChainError::Backend("Handshake wallet history exceeded its bound".to_owned())
11719        }
11720        HnsWalletError::NameExpired | HnsWalletError::NameFinalizeNotMature { .. } => {
11721            ChainError::Backend("Handshake name state cannot fund this value action".to_owned())
11722        }
11723        HnsWalletError::HeaderRoundInsufficientPeers
11724        | HnsWalletError::HeaderRoundInsufficientResponses
11725        | HnsWalletError::HeaderRoundInsufficientAgreement => {
11726            ChainError::Backend("Handshake header verification is incomplete".to_owned())
11727        }
11728        HnsWalletError::Backend(_) => {
11729            ChainError::Backend("Handshake backend request failed".to_owned())
11730        }
11731        // Variants classified above as protocol errors are exhaustive today;
11732        // retain a non-sensitive fail-closed category if another one is added.
11733        _ => ChainError::Backend("Handshake wallet runtime failed".to_owned()),
11734    }
11735}
11736
11737#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11738struct HnsLocalFeePolicyEvidence {
11739    transaction_weight: usize,
11740    transaction_sigops: u32,
11741    policy_virtual_size: usize,
11742    minimum_fee: BaseUnits,
11743}
11744
11745fn local_fee_policy_evidence(
11746    transaction: &Transaction,
11747    input_coins: &[Coin],
11748    rate_atomic_units_per_1000_policy_vbytes: BaseUnits,
11749) -> Result<HnsLocalFeePolicyEvidence, HnsWalletError> {
11750    if transaction.inputs.is_empty()
11751        || transaction.is_coinbase()
11752        || transaction.inputs.len() != input_coins.len()
11753        || rate_atomic_units_per_1000_policy_vbytes.is_zero()
11754    {
11755        return Err(HnsWalletError::InvalidEvidence);
11756    }
11757    let transaction_weight = transaction
11758        .weight()
11759        .map_err(|_| HnsWalletError::InvalidPreparedArtifact)?;
11760    let transaction_weight_u32 = u32::try_from(transaction_weight)
11761        .map_err(|_| HnsWalletError::InvalidFeeQuoteTransaction)?;
11762    let transaction_sigops = transaction_sigops(transaction, input_coins)
11763        .map_err(|_| HnsWalletError::InvalidEvidence)?;
11764    if transaction_weight_u32 > MAX_POLICY_TRANSACTION_WEIGHT.get()
11765        || transaction_sigops > MAX_POLICY_TRANSACTION_SIGOPS.get()
11766    {
11767        return Err(HnsWalletError::InvalidFeeQuoteTransaction);
11768    }
11769    let policy_virtual_size = transaction_policy_virtual_size(transaction, input_coins)
11770        .map_err(|_| HnsWalletError::InvalidEvidence)?;
11771    let rate = u32::try_from(rate_atomic_units_per_1000_policy_vbytes.get())
11772        .map_err(|_| HnsWalletError::InvalidFeeQuote)?;
11773    let minimum_fee = minimum_policy_fee(policy_virtual_size, FeeRate::new(rate))
11774        .map_err(|_| HnsWalletError::Arithmetic)?;
11775    let policy_virtual_size = usize::try_from(policy_virtual_size.get())
11776        .map_err(|_| HnsWalletError::InvalidFeeQuoteTransaction)?;
11777    Ok(HnsLocalFeePolicyEvidence {
11778        transaction_weight,
11779        transaction_sigops,
11780        policy_virtual_size,
11781        minimum_fee: BaseUnits::new(u128::from(minimum_fee.get())),
11782    })
11783}
11784
11785fn actual_transaction_fee(
11786    transaction: &Transaction,
11787    input_coins: &[Coin],
11788) -> Result<BaseUnits, HnsWalletError> {
11789    if transaction.inputs.len() != input_coins.len()
11790        || transaction
11791            .inputs
11792            .iter()
11793            .zip(input_coins)
11794            .any(|(input, coin)| input.previous_output != coin.outpoint)
11795    {
11796        return Err(HnsWalletError::InvalidEvidence);
11797    }
11798    let inputs = input_coins.iter().try_fold(0_u128, |total, coin| {
11799        total
11800            .checked_add(u128::from(coin.value.get()))
11801            .ok_or(HnsWalletError::Arithmetic)
11802    })?;
11803    let outputs = transaction
11804        .outputs
11805        .iter()
11806        .try_fold(0_u128, |total, output| {
11807            total
11808                .checked_add(u128::from(output.value.get()))
11809                .ok_or(HnsWalletError::Arithmetic)
11810        })?;
11811    let fee = inputs
11812        .checked_sub(outputs)
11813        .ok_or(HnsWalletError::InvalidEvidence)?;
11814    Ok(BaseUnits::new(fee))
11815}
11816
11817pub(crate) fn validate_local_fee_quote_evidence(
11818    transaction: &Transaction,
11819    input_coins: &[Coin],
11820    quote: &HnsTransactionFeeQuote,
11821) -> Result<(), HnsWalletError> {
11822    let local = local_fee_policy_evidence(
11823        transaction,
11824        input_coins,
11825        BaseUnits::new(u128::from(quote.rate_atomic_units_per_1000_policy_vbytes)),
11826    )?;
11827    let actual_fee = actual_transaction_fee(transaction, input_coins)?;
11828    let shortfall = local.minimum_fee.get().saturating_sub(actual_fee.get());
11829    if quote.transaction_weight != local.transaction_weight
11830        || quote.transaction_sigops != local.transaction_sigops
11831        || quote.sigop_adjusted_policy_vbytes != local.policy_virtual_size
11832        || quote.minimum_policy_fee != local.minimum_fee
11833        || quote.actual_fee != actual_fee
11834        || quote.meets_minimum_policy_fee != (actual_fee >= local.minimum_fee)
11835        || quote.minimum_policy_fee_shortfall.get() != shortfall
11836    {
11837        return Err(HnsWalletError::InvalidFeeQuote);
11838    }
11839    Ok(())
11840}
11841
11842fn validate_final_fee_quote(
11843    raw: &[u8],
11844    input_coins: &[Coin],
11845    quote: &HnsTransactionFeeQuote,
11846    binding: SnapshotBinding,
11847    mempool: MempoolSnapshotBinding,
11848    expected_fee: BaseUnits,
11849    maximum_fee: BaseUnits,
11850) -> Result<(), HnsWalletError> {
11851    validate_final_fee_quote_evidence(
11852        raw,
11853        input_coins,
11854        quote,
11855        binding,
11856        mempool,
11857        expected_fee,
11858        maximum_fee,
11859    )?;
11860    if !HNS_FEE_QUOTE_ALGEBRA_RELEASE_QUALIFIED {
11861        return Err(HnsWalletError::RuntimeIntegrationUnavailable);
11862    }
11863    Ok(())
11864}
11865
11866fn validate_final_fee_quote_evidence(
11867    raw: &[u8],
11868    input_coins: &[Coin],
11869    quote: &HnsTransactionFeeQuote,
11870    binding: SnapshotBinding,
11871    mempool: MempoolSnapshotBinding,
11872    expected_fee: BaseUnits,
11873    maximum_fee: BaseUnits,
11874) -> Result<(), HnsWalletError> {
11875    let transaction =
11876        Transaction::decode(raw).map_err(|_| HnsWalletError::InvalidPreparedArtifact)?;
11877    if transaction
11878        .encode()
11879        .map_err(|_| HnsWalletError::InvalidPreparedArtifact)?
11880        != raw
11881    {
11882        return Err(HnsWalletError::InvalidPreparedArtifact);
11883    }
11884    let txid = wallet_transaction_hash(&transaction)?;
11885    validate_local_fee_quote_evidence(&transaction, input_coins, quote)?;
11886    if maximum_fee.is_zero()
11887        || expected_fee > maximum_fee
11888        || quote.txid != txid
11889        || quote.binding != binding
11890        || quote.mempool != mempool
11891        || quote.target_blocks != DEFAULT_FEE_TARGET_BLOCKS
11892        || quote.transaction_weight == 0
11893        || quote.sigop_adjusted_policy_vbytes == 0
11894        || quote.rate_atomic_units_per_1000_policy_vbytes == 0
11895        || quote.actual_fee != expected_fee
11896        || quote.minimum_policy_fee > quote.actual_fee
11897        || !quote.meets_minimum_policy_fee
11898        || !quote.minimum_policy_fee_shortfall.is_zero()
11899    {
11900        return Err(HnsWalletError::InvalidFeeQuote);
11901    }
11902    match quote.rate_source {
11903        HnsFeeRateSource::MinimumRelay | HnsFeeRateSource::NetworkDefault
11904            if quote.rate_sample_count == 0 => {}
11905        HnsFeeRateSource::Mempool | HnsFeeRateSource::PeerRelay if quote.rate_sample_count > 0 => {}
11906        _ => return Err(HnsWalletError::InvalidFeeQuote),
11907    }
11908    Ok(())
11909}
11910
11911fn validate_witness_only_change(
11912    unsigned: &Transaction,
11913    signed_raw: &[u8],
11914) -> Result<Transaction, HnsWalletError> {
11915    let signed =
11916        Transaction::decode(signed_raw).map_err(|_| HnsWalletError::InvalidPreparedArtifact)?;
11917    if signed
11918        .encode()
11919        .map_err(|_| HnsWalletError::InvalidPreparedArtifact)?
11920        != signed_raw
11921        || unsigned.version != signed.version
11922        || unsigned.outputs != signed.outputs
11923        || unsigned.locktime != signed.locktime
11924        || unsigned.inputs.len() != signed.inputs.len()
11925        || unsigned
11926            .inputs
11927            .iter()
11928            .zip(&signed.inputs)
11929            .any(|(left, right)| {
11930                left.previous_output != right.previous_output || left.sequence != right.sequence
11931            })
11932    {
11933        return Err(HnsWalletError::InvalidPreparedArtifact);
11934    }
11935    Ok(signed)
11936}
11937
11938fn validate_signed_payment_plan(
11939    plan: &HnsSpendPlan,
11940    signed_raw: &[u8],
11941) -> Result<Transaction, HnsWalletError> {
11942    let unsigned = Transaction::decode(&plan.unsigned_transaction)
11943        .map_err(|_| HnsWalletError::InvalidPreparedArtifact)?;
11944    validate_witness_only_change(&unsigned, signed_raw)
11945}
11946
11947/// Execute every signed input under the same standard witness-program flags
11948/// used by a Handshake relay node before any signed bytes are persisted or
11949/// submitted. A successful socket write is not mempool admission, so this
11950/// local check prevents an invalid authorization from being misreported as a
11951/// peer-accepted transaction and makes durable rebroadcast fail closed.
11952fn validate_standard_input_authorizations(
11953    transaction: &Transaction,
11954    input_coins: &[Coin],
11955) -> Result<(), HnsWalletError> {
11956    if transaction.inputs.is_empty() || transaction.inputs.len() != input_coins.len() {
11957        return Err(HnsWalletError::InvalidPreparedArtifact);
11958    }
11959    for (index, coin) in input_coins.iter().enumerate() {
11960        verify_witness_program(
11961            transaction,
11962            index,
11963            coin,
11964            ScriptFlags::STANDARD,
11965            &K256SignatureVerifier,
11966        )
11967        .map_err(|_| HnsWalletError::Signing)?;
11968    }
11969    Ok(())
11970}
11971
11972fn decode_hns_address(network: HnsNetwork, value: &str) -> Result<Address, HnsWalletError> {
11973    let (hrp, version, program) =
11974        segwit::decode(value).map_err(|_| HnsWalletError::InvalidAddress)?;
11975    let expected = Hrp::parse(network.hrp()).map_err(|_| HnsWalletError::InvalidAddress)?;
11976    if hrp != expected {
11977        return Err(HnsWalletError::InvalidAddress);
11978    }
11979    Address::new(version.to_u8(), program).map_err(|_| HnsWalletError::InvalidAddress)
11980}
11981
11982fn build_unsigned_payment(
11983    mut coins: Vec<TrackedHnsCoin>,
11984    destination: Address,
11985    change: Address,
11986    amount: BaseUnits,
11987    fee_rate: BaseUnits,
11988    maximum_fee: BaseUnits,
11989    dust_threshold: BaseUnits,
11990) -> Result<(Transaction, Vec<TrackedHnsCoin>, BaseUnits), HnsWalletError> {
11991    let amount = u64::try_from(amount.get()).map_err(|_| HnsWalletError::InvalidAmount)?;
11992    if amount == 0 || fee_rate.is_zero() || maximum_fee.is_zero() {
11993        return Err(HnsWalletError::InvalidAmount);
11994    }
11995    coins.retain(is_confirmed_ordinary_hns_spend_candidate);
11996    coins.sort_by(|left, right| {
11997        left.coin
11998            .value
11999            .cmp(&right.coin.value)
12000            .then_with(|| left.coin.outpoint.cmp(&right.coin.outpoint))
12001    });
12002    let mut selected = Vec::new();
12003    let mut total = 0_u128;
12004    for coin in coins {
12005        total = total
12006            .checked_add(coin.coin.value.get())
12007            .ok_or(HnsWalletError::Arithmetic)?;
12008        selected.push(coin);
12009        let provisional = unsigned_payment_transaction(
12010            &selected,
12011            destination.clone(),
12012            Some((change.clone(), 1)),
12013            amount,
12014        )?;
12015        let input_coins = canonical_input_coins(&selected)?;
12016        let change_fee = canonical_policy_minimum_fee(&provisional, &input_coins, fee_rate)?;
12017        let required = u128::from(amount)
12018            .checked_add(change_fee.get())
12019            .ok_or(HnsWalletError::Arithmetic)?;
12020        if total < required {
12021            continue;
12022        }
12023        let change_value = total - required;
12024        if change_value >= dust_threshold.get() {
12025            if change_fee > maximum_fee {
12026                return Err(HnsWalletError::FeeLimit);
12027            }
12028            let change_value =
12029                u64::try_from(change_value).map_err(|_| HnsWalletError::InvalidAmount)?;
12030            let transaction = unsigned_payment_transaction(
12031                &selected,
12032                destination.clone(),
12033                Some((change.clone(), change_value)),
12034                amount,
12035            )?;
12036            return Ok((transaction, selected, change_fee));
12037        }
12038
12039        let no_change = unsigned_payment_transaction(&selected, destination.clone(), None, amount)?;
12040        let minimum_fee = canonical_policy_minimum_fee(&no_change, &input_coins, fee_rate)?;
12041        let actual_fee = BaseUnits::new(total - u128::from(amount));
12042        if actual_fee >= minimum_fee && actual_fee <= maximum_fee {
12043            return Ok((no_change, selected, actual_fee));
12044        }
12045    }
12046    Err(HnsWalletError::InsufficientFunds)
12047}
12048
12049fn unsigned_payment_transaction(
12050    selected: &[TrackedHnsCoin],
12051    destination: Address,
12052    change: Option<(Address, u64)>,
12053    amount: u64,
12054) -> Result<Transaction, HnsWalletError> {
12055    let inputs = selected
12056        .iter()
12057        .map(|coin| Input {
12058            previous_output: Outpoint {
12059                transaction_hash: CanonicalTransactionHash::new(
12060                    coin.coin.outpoint.transaction.into_bytes(),
12061                ),
12062                index: coin.coin.outpoint.output_index,
12063            },
12064            sequence: u32::MAX,
12065            witness: Witness {
12066                items: vec![vec![0; 65], vec![0; 33]],
12067            },
12068        })
12069        .collect();
12070    let mut outputs = vec![Output {
12071        value: Dollarydoos::new(amount),
12072        address: destination,
12073        covenant: Covenant::default(),
12074    }];
12075    if let Some((address, value)) = change {
12076        outputs.push(Output {
12077            value: Dollarydoos::new(value),
12078            address,
12079            covenant: Covenant::default(),
12080        });
12081    }
12082    Ok(Transaction {
12083        version: 0,
12084        inputs,
12085        outputs,
12086        locktime: 0,
12087    })
12088}
12089
12090fn canonical_policy_minimum_fee(
12091    transaction: &Transaction,
12092    input_coins: &[Coin],
12093    unqualified_node_rate_per_policy_kvb: BaseUnits,
12094) -> Result<BaseUnits, HnsWalletError> {
12095    local_fee_policy_evidence(
12096        transaction,
12097        input_coins,
12098        unqualified_node_rate_per_policy_kvb,
12099    )
12100    .map(|evidence| evidence.minimum_fee)
12101}
12102
12103fn sign_payment_plan(
12104    store: &WalletStore,
12105    account: &HnsAccountRecord,
12106    plan: &HnsSpendPlan,
12107) -> Result<Vec<u8>, HnsWalletError> {
12108    let transaction = Transaction::decode(&plan.unsigned_transaction)
12109        .map_err(|_| HnsWalletError::InvalidPreparedArtifact)?;
12110    let expected_roles = ordinary_hns_input_roles(&plan.inputs)?;
12111    sign_ordered_p2pkh_inputs(store, account, transaction, &plan.inputs, &expected_roles)
12112}
12113
12114fn sign_ordered_p2pkh_inputs(
12115    store: &WalletStore,
12116    account: &HnsAccountRecord,
12117    transaction: Transaction,
12118    inputs: &[TrackedHnsCoin],
12119    expected_roles: &[KeyRole],
12120) -> Result<Vec<u8>, HnsWalletError> {
12121    sign_ordered_p2pkh_inputs_from(store, account, transaction, 0, inputs, expected_roles)
12122}
12123
12124fn sign_ordered_p2pkh_inputs_from(
12125    store: &WalletStore,
12126    account: &HnsAccountRecord,
12127    mut transaction: Transaction,
12128    input_offset: usize,
12129    inputs: &[TrackedHnsCoin],
12130    expected_roles: &[KeyRole],
12131) -> Result<Vec<u8>, HnsWalletError> {
12132    if inputs.is_empty()
12133        || input_offset >= transaction.inputs.len()
12134        || transaction.inputs.len() - input_offset != inputs.len()
12135        || inputs.len() != expected_roles.len()
12136        || transaction.inputs.len() > MAX_TRANSACTION_INPUTS
12137        || inputs.len() > MAX_TRANSACTION_INPUTS
12138    {
12139        return Err(HnsWalletError::InvalidPreparedArtifact);
12140    }
12141    let seed = store
12142        .get_secret(
12143            account.config.wallet_id.as_bytes(),
12144            SecretKind::RecoverySeed,
12145        )?
12146        .ok_or(HnsWalletError::MissingSeed)?;
12147    for (offset, (coin, expected_role)) in inputs.iter().zip(expected_roles).enumerate() {
12148        let index = input_offset
12149            .checked_add(offset)
12150            .ok_or(HnsWalletError::Arithmetic)?;
12151        if *expected_role != KeyRole::HnsCoin {
12152            return Err(HnsWalletError::InvalidPreparedArtifact);
12153        }
12154        let (actual_tag, _, _) = restore_derivation_key(coin.derivation)?;
12155        if coin.derivation.role != *expected_role
12156            || coin.derivation.account != account_number(account)
12157            || actual_tag != HNS_COIN_DERIVATION_TAG
12158        {
12159            return Err(HnsWalletError::InvalidPreparedArtifact);
12160        }
12161        let canonical = coin.to_canonical_coin()?;
12162        if transaction.inputs[index].previous_output != canonical.outpoint
12163            || canonical.address.version != 0
12164            || canonical.address.hash != coin.address_program
12165        {
12166            return Err(HnsWalletError::InvalidPreparedArtifact);
12167        }
12168        let secret = derive_account_secret(&seed, account.config.network, coin.derivation)?;
12169        let signing =
12170            SigningKey::from_slice(secret.as_slice()).map_err(|_| HnsWalletError::KeyDerivation)?;
12171        let public = signing.verifying_key().to_sec1_point(true);
12172        let public_bytes: [u8; 33] = public
12173            .as_bytes()
12174            .try_into()
12175            .map_err(|_| HnsWalletError::KeyDerivation)?;
12176        if public_key_hash(&public_bytes)?.as_slice() != coin.address_program {
12177            return Err(HnsWalletError::InvalidPreparedArtifact);
12178        }
12179        let previous_value = canonical.value.get();
12180        let script = p2pkh_script(&coin.address_program)?;
12181        let digest = signature_hash(&transaction, index, &script, previous_value, SIGHASH_ALL)
12182            .map_err(|_| HnsWalletError::Signing)?;
12183        let signature: Signature = signing
12184            .sign_prehash(&digest)
12185            .map_err(|_| HnsWalletError::Signing)?;
12186        let signature = signature.normalize_s();
12187        let mut encoded = signature.to_bytes().to_vec();
12188        encoded.push(SIGHASH_ALL as u8);
12189        transaction.inputs[index].witness = Witness {
12190            items: vec![encoded, public.as_bytes().to_vec()],
12191        };
12192    }
12193    transaction
12194        .encode()
12195        .map_err(|_| HnsWalletError::InvalidPreparedArtifact)
12196}
12197
12198fn p2pkh_script(program: &[u8]) -> Result<Vec<u8>, HnsWalletError> {
12199    if program.len() != 20 {
12200        return Err(HnsWalletError::InvalidPreparedArtifact);
12201    }
12202    let mut script = Vec::with_capacity(25);
12203    script.extend_from_slice(&[OP_DUP, OP_BLAKE160, 20]);
12204    script.extend_from_slice(program);
12205    script.extend_from_slice(&[OP_EQUALVERIFY, OP_CHECKSIG]);
12206    Ok(script)
12207}
12208
12209fn wallet_transaction_hash(transaction: &Transaction) -> Result<TransactionHash, HnsWalletError> {
12210    transaction
12211        .transaction_hash()
12212        .map(|hash| TransactionHash::new(hash.into_bytes()))
12213        .map_err(|_| HnsWalletError::InvalidPreparedArtifact)
12214}
12215
12216fn send_workflow_id(config: &HnsRuntimeConfig, request_nonce: u64) -> WorkflowId {
12217    let mut hasher = Sha256::new();
12218    hasher.update(b"hns-wallet-rs/hns-send-workflow/v1");
12219    hasher.update(account_entity_prefix(config));
12220    hasher.update(request_nonce.to_be_bytes());
12221    let digest: [u8; 32] = hasher.finalize().into();
12222    let mut id = [0_u8; 16];
12223    id.copy_from_slice(&digest[..16]);
12224    WorkflowId::new(id)
12225}
12226
12227fn ensure_settlement_ready(cache: &HnsRuntimeCache) -> Result<(), ChainError> {
12228    ensure_ready(cache)?;
12229    if cache.account.config.settlement_enabled {
12230        Ok(())
12231    } else {
12232        Err(ChainError::Disabled)
12233    }
12234}
12235
12236fn validate_settlement_request(request: &SettlementLockRequest) -> Result<(), ChainError> {
12237    if request.module != ModuleId::Handshake
12238        || request.amount.asset != WalletAsset::Hns
12239        || request.amount.base_units.is_zero()
12240        || request.maximum_fee.is_zero()
12241        || !hns_locktime_is_valid(request.absolute_timelock)
12242    {
12243        return Err(ChainError::InvalidRequest(
12244            "invalid Handshake settlement terms",
12245        ));
12246    }
12247    Ok(())
12248}
12249
12250/// Return whether an HNS absolute locktime is the consensus median-time
12251/// encoding rather than a block height.  HNS time locktimes carry the high
12252/// bit and express the masked value in 512-second units.
12253fn hns_locktime_is_time(locktime: u64) -> Result<bool, ChainError> {
12254    let encoded = u32::try_from(locktime)
12255        .map_err(|_| ChainError::InvalidRequest("Handshake timelock exceeds u32"))?;
12256    Ok(encoded & LOCKTIME_FLAG != 0)
12257}
12258
12259fn hns_locktime_is_valid(locktime: u64) -> bool {
12260    u32::try_from(locktime).is_ok_and(|encoded| encoded & LOCKTIME_MASK != 0)
12261}
12262
12263/// Check the exact consensus domain used by the transaction's CLTV branch.
12264/// Height locks become usable at their height.  Time locks use the wallet's
12265/// validated parent median time, strictly after the represented 512-second
12266/// threshold, matching HSD's absolute-lock semantics.
12267fn hns_refund_locktime_mature(locktime: u64, local_current: u64) -> Result<bool, ChainError> {
12268    let encoded = u32::try_from(locktime)
12269        .map_err(|_| ChainError::InvalidRequest("Handshake timelock exceeds u32"))?;
12270    let value = u64::from(encoded & LOCKTIME_MASK);
12271    if value == 0 {
12272        return Err(ChainError::InvalidRequest("Handshake timelock is zero"));
12273    }
12274    if encoded & LOCKTIME_FLAG == 0 {
12275        return Ok(local_current >= value);
12276    }
12277    let threshold = value
12278        .checked_mul(u64::from(LOCKTIME_MULTIPLIER))
12279        .ok_or(ChainError::Overflow)?;
12280    Ok(local_current > threshold)
12281}
12282
12283/// Confirm that the generic persisted verification record is an exact view of
12284/// the protocol descriptor.  This keeps the convenience APIs from ever
12285/// spending a same-session lock whose amount, hashlock, participants, or HNS
12286/// encoded locktime differs from the signed swap session.
12287fn validate_native_htlc_lock(
12288    descriptor: &HnsHtlc,
12289    session_id: SessionId,
12290    lock: &VerifiedLock,
12291) -> Result<(), ChainError> {
12292    descriptor
12293        .validate()
12294        .map_err(|_| ChainError::InvalidRequest("invalid native Handshake HTLC descriptor"))?;
12295    if lock.module != ModuleId::Handshake
12296        || lock.session_id != session_id
12297        || lock.amount.asset != WalletAsset::Hns
12298        || lock.amount.base_units.get() != u128::from(descriptor.value.get())
12299        || lock.hashlock.as_bytes() != &descriptor.hashlock
12300        || lock.absolute_timelock != u64::from(descriptor.refund_locktime)
12301    {
12302        return Err(ChainError::InvalidEvidence);
12303    }
12304    Ok(())
12305}
12306
12307fn decode_compressed_key(value: &str) -> Result<[u8; 33], ChainError> {
12308    let mut key = [0_u8; 33];
12309    hex::decode_to_slice(value, &mut key)
12310        .map_err(|_| ChainError::InvalidRequest("invalid compressed settlement key"))?;
12311    VerifyingKey::from_sec1_bytes(&key)
12312        .map_err(|_| ChainError::InvalidRequest("invalid compressed settlement key"))?;
12313    Ok(key)
12314}
12315
12316fn hns_htlc_script(
12317    hashlock: ObjectHash,
12318    receiver: &[u8; 33],
12319    refund: &[u8; 33],
12320    absolute_timelock: u64,
12321) -> Result<Vec<u8>, ChainError> {
12322    let timelock = u32::try_from(absolute_timelock)
12323        .map_err(|_| ChainError::InvalidRequest("Handshake timelock exceeds u32"))?;
12324    let encoded_timelock = encode_script_number(u64::from(timelock));
12325    let mut script = Vec::with_capacity(114);
12326    script.extend_from_slice(&[OP_IF, OP_SHA256, 32]);
12327    script.extend_from_slice(hashlock.as_bytes());
12328    script.extend_from_slice(&[OP_EQUALVERIFY, 33]);
12329    script.extend_from_slice(receiver);
12330    script.extend_from_slice(&[OP_ELSE, encoded_timelock.len() as u8]);
12331    script.extend_from_slice(&encoded_timelock);
12332    script.extend_from_slice(&[OP_CHECKLOCKTIMEVERIFY, OP_DROP, 33]);
12333    script.extend_from_slice(refund);
12334    script.extend_from_slice(&[OP_ENDIF, OP_CHECKSIG]);
12335    Ok(script)
12336}
12337
12338fn encode_script_number(mut value: u64) -> Vec<u8> {
12339    if value == 0 {
12340        return Vec::new();
12341    }
12342    let mut encoded = Vec::new();
12343    while value > 0 {
12344        encoded.push(value as u8);
12345        value >>= 8;
12346    }
12347    if encoded.last().is_some_and(|byte| byte & 0x80 != 0) {
12348        encoded.push(0);
12349    }
12350    encoded
12351}
12352
12353fn derive_settlement_secret(
12354    seed: &[u8],
12355    account: &HnsAccountRecord,
12356    session_id: SessionId,
12357    refund: bool,
12358) -> Result<Zeroizing<[u8; 32]>, HnsWalletError> {
12359    let mut context = Sha256::new();
12360    context.update(HNS_SETTLEMENT_KEY_DOMAIN);
12361    context.update(account_number(account).to_be_bytes());
12362    context.update(session_id.as_bytes());
12363    context.update([u8::from(refund)]);
12364    let context: [u8; 32] = context.finalize().into();
12365    for counter in 0_u8..=u8::MAX {
12366        let mut info = Vec::with_capacity(context.len() + 1);
12367        info.extend_from_slice(&context);
12368        info.push(counter);
12369        let hkdf = Hkdf::<Sha256>::new(Some(b"Handshake atomic settlement role"), seed);
12370        let mut candidate = Zeroizing::new([0_u8; 32]);
12371        hkdf.expand(&info, candidate.as_mut())
12372            .map_err(|_| HnsWalletError::KeyDerivation)?;
12373        if SigningKey::from_slice(candidate.as_slice()).is_ok() {
12374            return Ok(candidate);
12375        }
12376    }
12377    Err(HnsWalletError::KeyDerivation)
12378}
12379
12380fn derive_settlement_public_key(
12381    store: &WalletStore,
12382    account: &HnsAccountRecord,
12383    session_id: SessionId,
12384    refund: bool,
12385) -> Result<[u8; 33], HnsWalletError> {
12386    let seed = store
12387        .get_secret(
12388            account.config.wallet_id.as_bytes(),
12389            SecretKind::RecoverySeed,
12390        )?
12391        .ok_or(HnsWalletError::MissingSeed)?;
12392    let secret = derive_settlement_secret(&seed, account, session_id, refund)?;
12393    let signing =
12394        SigningKey::from_slice(secret.as_slice()).map_err(|_| HnsWalletError::KeyDerivation)?;
12395    signing
12396        .verifying_key()
12397        .to_sec1_point(true)
12398        .as_bytes()
12399        .try_into()
12400        .map_err(|_| HnsWalletError::KeyDerivation)
12401}
12402
12403fn settlement_workflow_id(
12404    config: &HnsRuntimeConfig,
12405    session_id: SessionId,
12406    action: HnsSettlementAction,
12407) -> WorkflowId {
12408    let mut hasher = Sha256::new();
12409    hasher.update(b"hns-wallet-rs/hns-settlement-workflow/v1");
12410    hasher.update(account_entity_prefix(config));
12411    hasher.update(session_id.as_bytes());
12412    hasher.update([match action {
12413        HnsSettlementAction::Lock => 0,
12414        HnsSettlementAction::Redeem => 1,
12415        HnsSettlementAction::Refund => 2,
12416    }]);
12417    let digest: [u8; 32] = hasher.finalize().into();
12418    let mut id = [0_u8; 16];
12419    id.copy_from_slice(&digest[..16]);
12420    WorkflowId::new(id)
12421}
12422
12423/// `AtomicSwap` is a broad store kind shared with the market coordinator.
12424/// Decode only rows carrying the native-HNS signed-transaction discriminator,
12425/// then validate their embedded identity. A malformed HNS settlement still
12426/// fails closed, while another authenticated protocol schema is left to its
12427/// own recovery registry.
12428fn list_hns_prepared_settlement_workflows(
12429    store: &WalletStore,
12430    kind: WorkflowKind,
12431) -> Result<Vec<StoredWorkflow<HnsPreparedSettlement>>, HnsWalletError> {
12432    let mut settlements = Vec::new();
12433    for stored in store.list_workflows_complete::<serde_json::Value>(kind, MAX_HISTORY_RESULTS)? {
12434        let is_hns_settlement = stored
12435            .state
12436            .as_object()
12437            .is_some_and(|object| object.contains_key("signed_transaction"));
12438        if !is_hns_settlement {
12439            continue;
12440        }
12441        let state: HnsPreparedSettlement = serde_json::from_value(stored.state)?;
12442        if state.workflow_id != stored.id || settlement_workflow_kind(state.action) != stored.kind {
12443            return Err(HnsWalletError::InvalidWorkflow);
12444        }
12445        settlements.push(StoredWorkflow {
12446            id: stored.id,
12447            kind: stored.kind,
12448            revision: stored.revision,
12449            state,
12450            irreversible_broadcast_prepared: stored.irreversible_broadcast_prepared,
12451            updated_at_unix: stored.updated_at_unix,
12452        });
12453    }
12454    Ok(settlements)
12455}
12456
12457fn settlement_workflow_kind(action: HnsSettlementAction) -> WorkflowKind {
12458    if action == HnsSettlementAction::Refund {
12459        WorkflowKind::Refund
12460    } else {
12461        WorkflowKind::AtomicSwap
12462    }
12463}
12464
12465fn settlement_requires_chain_observation(
12466    stage: HnsSettlementStage,
12467    irreversible_broadcast_prepared: bool,
12468) -> bool {
12469    stage == HnsSettlementStage::Prepared
12470        || matches!(
12471            stage,
12472            HnsSettlementStage::Broadcast
12473                | HnsSettlementStage::Mempool
12474                | HnsSettlementStage::RequiresRebroadcast
12475        )
12476        || (irreversible_broadcast_prepared
12477            && !matches!(
12478                stage,
12479                HnsSettlementStage::Confirmed | HnsSettlementStage::Conflicted
12480            ))
12481}
12482
12483fn unobserved_settlement_stage(
12484    stage: HnsSettlementStage,
12485    irreversible_broadcast_prepared: bool,
12486    expires_at_unix: u64,
12487    now_unix: u64,
12488) -> (HnsSettlementStage, bool) {
12489    let irreversible = matches!(
12490        stage,
12491        HnsSettlementStage::Broadcast
12492            | HnsSettlementStage::Mempool
12493            | HnsSettlementStage::RequiresRebroadcast
12494    ) || (irreversible_broadcast_prepared
12495        && !matches!(
12496            stage,
12497            HnsSettlementStage::Prepared
12498                | HnsSettlementStage::Confirmed
12499                | HnsSettlementStage::Conflicted
12500        ));
12501    if irreversible {
12502        (HnsSettlementStage::RequiresRebroadcast, true)
12503    } else if stage == HnsSettlementStage::Prepared && expires_at_unix <= now_unix {
12504        (HnsSettlementStage::Expired, false)
12505    } else {
12506        (stage, false)
12507    }
12508}
12509
12510fn settlement_lock_workflow_may_be_reprepared(
12511    stage: HnsSettlementStage,
12512    expires_at_unix: u64,
12513    irreversible_broadcast_prepared: bool,
12514    now_unix: u64,
12515) -> bool {
12516    (stage == HnsSettlementStage::Prepared && expires_at_unix <= now_unix)
12517        || (matches!(
12518            stage,
12519            HnsSettlementStage::Expired | HnsSettlementStage::Cancelled
12520        ) && !irreversible_broadcast_prepared)
12521}
12522
12523fn recovery_funding_submission_limit(prepared: &HnsPreparedSettlement) -> u64 {
12524    let limit = prepared
12525        .recovery_publication
12526        .as_ref()
12527        .and_then(|package| package.funding_submission_before_unix)
12528        .map_or(prepared.expires_at_unix, |limit| {
12529            limit.min(prepared.expires_at_unix)
12530        });
12531    match prepared.broadcast_guard.as_ref().map(|guard| guard.purpose) {
12532        Some(HnsSettlementBroadcastGuardPurpose::SecondFunding {
12533            expires_at_unix, ..
12534        }) => limit.min(expires_at_unix),
12535        _ => limit,
12536    }
12537}
12538
12539fn same_prepared_settlement(
12540    stored: &HnsPreparedSettlement,
12541    artifact: &HnsPreparedSettlement,
12542) -> bool {
12543    stored.wallet_id == artifact.wallet_id
12544        && stored.account_id == artifact.account_id
12545        && stored.workflow_id == artifact.workflow_id
12546        && stored.session_id == artifact.session_id
12547        && stored.action == artifact.action
12548        && artifact.stage == HnsSettlementStage::Prepared
12549        && stored.transaction == artifact.transaction
12550        && stored.signed_transaction == artifact.signed_transaction
12551        && stored.input_coins == artifact.input_coins
12552        && stored.fee == artifact.fee
12553        && stored.maximum_fee == artifact.maximum_fee
12554        && stored.expires_at_unix == artifact.expires_at_unix
12555        && match (&stored.recovery_publication, &artifact.recovery_publication) {
12556            (None, None) => true,
12557            (Some(a), Some(b)) => a.same_approved_terms(b),
12558            _ => false,
12559        }
12560        && stored.terms == artifact.terms
12561        && stored.broadcast_guard == artifact.broadcast_guard
12562}
12563
12564fn same_prepared_settlement_except_guard(
12565    stored: &HnsPreparedSettlement,
12566    artifact: &HnsPreparedSettlement,
12567) -> bool {
12568    stored.wallet_id == artifact.wallet_id
12569        && stored.account_id == artifact.account_id
12570        && stored.workflow_id == artifact.workflow_id
12571        && stored.session_id == artifact.session_id
12572        && stored.action == artifact.action
12573        && stored.stage == HnsSettlementStage::Prepared
12574        && artifact.stage == HnsSettlementStage::Prepared
12575        && stored.transaction == artifact.transaction
12576        && stored.signed_transaction == artifact.signed_transaction
12577        && stored.input_coins == artifact.input_coins
12578        && stored.fee == artifact.fee
12579        && stored.maximum_fee == artifact.maximum_fee
12580        && stored.fee_quote == artifact.fee_quote
12581        && stored.expires_at_unix == artifact.expires_at_unix
12582        && match (&stored.recovery_publication, &artifact.recovery_publication) {
12583            (None, None) => true,
12584            (Some(a), Some(b)) => a.same_approved_terms(b),
12585            _ => false,
12586        }
12587        && stored.terms == artifact.terms
12588}
12589
12590fn settlement_terms_are_retry_compatible(
12591    stored: &HnsSettlementTerms,
12592    candidate: &HnsSettlementTerms,
12593) -> bool {
12594    match (stored, candidate) {
12595        (
12596            HnsSettlementTerms::Lock { request: stored },
12597            HnsSettlementTerms::Lock { request: candidate },
12598        ) => {
12599            stored.session_id == candidate.session_id
12600                && stored.module == candidate.module
12601                && stored.amount == candidate.amount
12602                && stored.hashlock == candidate.hashlock
12603                && stored.receiver == candidate.receiver
12604                && stored.refund_target == candidate.refund_target
12605                && stored.absolute_timelock == candidate.absolute_timelock
12606        }
12607        (
12608            HnsSettlementTerms::Redeem { lock: stored },
12609            HnsSettlementTerms::Redeem { lock: candidate },
12610        )
12611        | (
12612            HnsSettlementTerms::Refund { lock: stored },
12613            HnsSettlementTerms::Refund { lock: candidate },
12614        ) => {
12615            stored.module == candidate.module
12616                && stored.session_id == candidate.session_id
12617                && stored.funding_id == candidate.funding_id
12618                && stored.amount == candidate.amount
12619                && stored.hashlock == candidate.hashlock
12620                && stored.absolute_timelock == candidate.absolute_timelock
12621                && stored.evidence_hash == candidate.evidence_hash
12622                && candidate.confirmation_count >= stored.confirmation_count
12623        }
12624        _ => false,
12625    }
12626}
12627
12628fn same_verified_settlement_binding(
12629    stored: &HnsVerifiedSettlementRecord,
12630    candidate: &HnsVerifiedSettlementRecord,
12631) -> bool {
12632    stored.expected == candidate.expected
12633        && stored.output_index == candidate.output_index
12634        && stored.script == candidate.script
12635        && stored.funding_coin == candidate.funding_coin
12636        && stored.verified.module == candidate.verified.module
12637        && stored.verified.session_id == candidate.verified.session_id
12638        && stored.verified.funding_id == candidate.verified.funding_id
12639        && stored.verified.amount == candidate.verified.amount
12640        && stored.verified.hashlock == candidate.verified.hashlock
12641        && stored.verified.absolute_timelock == candidate.verified.absolute_timelock
12642        && stored.verified.evidence_hash == candidate.verified.evidence_hash
12643}
12644
12645fn settlement_entity_id(config: &HnsRuntimeConfig, session_id: SessionId) -> [u8; 64] {
12646    let mut id = [0_u8; 64];
12647    id[..32].copy_from_slice(&account_entity_prefix(config));
12648    id[32..].copy_from_slice(session_id.as_bytes());
12649    id
12650}
12651
12652#[allow(clippy::too_many_arguments)]
12653fn unsigned_sponsored_htlc_spend(
12654    lock: &VerifiedLock,
12655    funding_output_index: u32,
12656    script: &[u8],
12657    previous_value: u64,
12658    sponsors: &[TrackedHnsCoin],
12659    destination: Address,
12660    htlc_sequence: u32,
12661    locktime: u32,
12662    refund: bool,
12663) -> Result<Transaction, HnsWalletError> {
12664    if sponsors.len() >= MAX_TRANSACTION_INPUTS {
12665        return Err(HnsWalletError::InvalidAmount);
12666    }
12667    let mut inputs = Vec::with_capacity(1 + sponsors.len());
12668    inputs.push(Input {
12669        previous_output: Outpoint {
12670            transaction_hash: CanonicalTransactionHash::new(lock.funding_id.into_bytes()),
12671            index: funding_output_index,
12672        },
12673        sequence: htlc_sequence,
12674        witness: Witness {
12675            items: if refund {
12676                vec![vec![0; 65], Vec::new(), script.to_vec()]
12677            } else {
12678                vec![
12679                    vec![0; 65],
12680                    vec![0; Preimage::LENGTH],
12681                    vec![1],
12682                    script.to_vec(),
12683                ]
12684            },
12685        },
12686    });
12687    inputs.extend(sponsors.iter().map(|coin| Input {
12688        previous_output: Outpoint {
12689            transaction_hash: CanonicalTransactionHash::new(
12690                coin.coin.outpoint.transaction.into_bytes(),
12691            ),
12692            index: coin.coin.outpoint.output_index,
12693        },
12694        sequence: u32::MAX,
12695        witness: Witness {
12696            items: vec![vec![0; 65], vec![0; 33]],
12697        },
12698    }));
12699    Ok(Transaction {
12700        version: 0,
12701        inputs,
12702        outputs: vec![Output {
12703            value: Dollarydoos::new(previous_value),
12704            address: destination,
12705            covenant: Covenant::default(),
12706        }],
12707        locktime,
12708    })
12709}
12710
12711// All parameters contribute directly to the signed HTLC witness and remain
12712// explicit so callers cannot accidentally reuse a partially bound context.
12713#[allow(clippy::too_many_arguments)]
12714fn sign_htlc_spend(
12715    store: &WalletStore,
12716    account: &HnsAccountRecord,
12717    mut transaction: Transaction,
12718    session_id: SessionId,
12719    script: &[u8],
12720    previous_value: u64,
12721    preimage: Option<&Preimage>,
12722    refund: bool,
12723) -> Result<Vec<u8>, HnsWalletError> {
12724    let seed = store
12725        .get_secret(
12726            account.config.wallet_id.as_bytes(),
12727            SecretKind::RecoverySeed,
12728        )?
12729        .ok_or(HnsWalletError::MissingSeed)?;
12730    let secret = derive_settlement_secret(&seed, account, session_id, refund)?;
12731    let signing =
12732        SigningKey::from_slice(secret.as_slice()).map_err(|_| HnsWalletError::KeyDerivation)?;
12733    let digest = signature_hash(&transaction, 0, script, previous_value, SIGHASH_ALL)
12734        .map_err(|_| HnsWalletError::Signing)?;
12735    let signature: Signature = signing
12736        .sign_prehash(&digest)
12737        .map_err(|_| HnsWalletError::Signing)?;
12738    let signature = signature.normalize_s();
12739    let mut encoded = signature.to_bytes().to_vec();
12740    encoded.push(SIGHASH_ALL as u8);
12741    transaction.inputs[0].witness = if refund {
12742        Witness {
12743            items: vec![encoded, Vec::new(), script.to_vec()],
12744        }
12745    } else {
12746        let preimage = preimage.ok_or(HnsWalletError::InvalidPreparedArtifact)?;
12747        Witness {
12748            items: vec![
12749                encoded,
12750                preimage.expose_for_settlement().to_vec(),
12751                vec![1],
12752                script.to_vec(),
12753            ],
12754        }
12755    };
12756    transaction
12757        .encode()
12758        .map_err(|_| HnsWalletError::InvalidPreparedArtifact)
12759}
12760
12761fn sign_htlc_spend_with_settlement_signer(
12762    mut transaction: Transaction,
12763    script: &[u8],
12764    previous_value: u64,
12765    preimage: Option<&Preimage>,
12766    refund: bool,
12767    signer: &dyn SettlementSigner,
12768) -> Result<Vec<u8>, HnsWalletError> {
12769    let digest = signature_hash(&transaction, 0, script, previous_value, SIGHASH_ALL)
12770        .map_err(|_| HnsWalletError::Signing)?;
12771    let signature = signer
12772        .sign_digest(digest)
12773        .map_err(|_| HnsWalletError::Signing)?;
12774    let signature = Signature::from_slice(&signature).map_err(|_| HnsWalletError::Signing)?;
12775    if signature != signature.normalize_s() {
12776        return Err(HnsWalletError::Signing);
12777    }
12778    let verifying = VerifyingKey::from_sec1_bytes(&signer.compressed_public_key())
12779        .map_err(|_| HnsWalletError::Signing)?;
12780    verifying
12781        .verify_prehash(&digest, &signature)
12782        .map_err(|_| HnsWalletError::Signing)?;
12783    let mut encoded = signature.to_bytes().to_vec();
12784    encoded.push(SIGHASH_ALL as u8);
12785    transaction.inputs[0].witness = if refund {
12786        Witness {
12787            items: vec![encoded, Vec::new(), script.to_vec()],
12788        }
12789    } else {
12790        let preimage = preimage.ok_or(HnsWalletError::InvalidPreparedArtifact)?;
12791        Witness {
12792            items: vec![
12793                encoded,
12794                preimage.expose_for_settlement().to_vec(),
12795                vec![1],
12796                script.to_vec(),
12797            ],
12798        }
12799    };
12800    transaction
12801        .encode()
12802        .map_err(|_| HnsWalletError::InvalidPreparedArtifact)
12803}
12804
12805#[derive(Debug, Error)]
12806pub enum HnsWalletError {
12807    #[error("wallet store failed")]
12808    Store,
12809    #[error("operating-system randomness is unavailable")]
12810    Randomness,
12811    #[error("invalid recovery phrase")]
12812    InvalidRecoveryPhrase,
12813    #[error("wallet recovery seed is unavailable")]
12814    MissingSeed,
12815    #[error("key role does not belong to Handshake")]
12816    WrongKeyRole,
12817    #[error("deterministic key derivation failed")]
12818    KeyDerivation,
12819    #[error("Handshake address encoding failed")]
12820    Address,
12821    #[error("invalid Handshake address or network")]
12822    InvalidAddress,
12823    #[error("amount or coin count is invalid")]
12824    InvalidAmount,
12825    #[error("checked arithmetic failed")]
12826    Arithmetic,
12827    #[error("insufficient spendable funds")]
12828    InsufficientFunds,
12829    #[error("fee exceeds the approved maximum")]
12830    FeeLimit,
12831    #[error("invalid Handshake name")]
12832    InvalidName,
12833    #[error("name proof or ownership evidence is invalid")]
12834    InvalidEvidence,
12835    #[error("invalid persisted name workflow")]
12836    InvalidWorkflow,
12837    #[error("wallet store must be unlocked")]
12838    StoreLocked,
12839    #[error("wallet read runtime does not share the selected store authority")]
12840    StoreAuthorityMismatch,
12841    #[error("persisted account configuration does not match")]
12842    AccountConfigurationMismatch,
12843    #[error("the selected account or durable read fence changed during synchronization")]
12844    StaleAccountRead,
12845    #[error("the HD account component is already assigned in this wallet")]
12846    DuplicateAccountDerivation,
12847    #[error("runtime synchronization lock is unavailable")]
12848    RuntimePoisoned,
12849    #[error("system clock is unavailable")]
12850    Clock,
12851    #[error("restore lookahead or persisted scan progress is invalid")]
12852    InvalidLookahead,
12853    #[error("the bounded restore scan cannot preserve a complete trailing gap")]
12854    ScanCapacityExhausted,
12855    #[error("the node snapshot, cursor, or mempool generation changed")]
12856    StaleNodeSnapshot,
12857    #[error("a fee-quote input is unavailable in the bound node snapshot")]
12858    FeeQuoteInputUnavailable,
12859    #[error("the node rejected the transaction as ineligible for a fee quote")]
12860    InvalidFeeQuoteTransaction,
12861    #[error("node fee-quote evidence does not match the final transaction")]
12862    InvalidFeeQuote,
12863    #[error("the reserved change address was concurrently advanced")]
12864    StaleAddressReservation,
12865    #[error("runtime configuration is invalid")]
12866    InvalidRuntimeConfiguration,
12867    #[error("mainnet value operations remain disabled by release policy")]
12868    MainnetDisabled,
12869    #[error("Handshake value runtime integration has not passed its release gate")]
12870    RuntimeIntegrationUnavailable,
12871    #[error("prepared transaction artifact is invalid")]
12872    InvalidPreparedArtifact,
12873    #[error("prepared transaction artifact has expired")]
12874    PreparedArtifactExpired,
12875    #[error("a fresh trusted approval is required")]
12876    ApprovalRequired,
12877    #[error("transaction signing failed")]
12878    Signing,
12879    #[error("history result exceeds the configured bound")]
12880    HistoryLimit,
12881    #[error("current name owner output is not controlled by this account")]
12882    NameNotOwned,
12883    #[error("Handshake name is expired and cannot be transferred or finalized")]
12884    NameExpired,
12885    #[error("name transfer is not finalizable before candidate height {eligible_height}")]
12886    NameFinalizeNotMature { eligible_height: u64 },
12887    #[error("wallet state encoding failed")]
12888    Encoding,
12889    #[error("HNS header round timed out before enough independent peers responded")]
12890    HeaderRoundInsufficientResponses,
12891    #[error("HNS header round needs more independent peers")]
12892    HeaderRoundInsufficientPeers,
12893    #[error("HNS header round received a highest-work chain without independent peer agreement")]
12894    HeaderRoundInsufficientAgreement,
12895    #[error("Handshake backend failed: {0}")]
12896    Backend(String),
12897}
12898
12899impl From<StoreError> for HnsWalletError {
12900    fn from(_: StoreError) -> Self {
12901        Self::Store
12902    }
12903}
12904
12905impl From<serde_json::Error> for HnsWalletError {
12906    fn from(_: serde_json::Error) -> Self {
12907        Self::Encoding
12908    }
12909}
12910
12911#[cfg(test)]
12912mod tests {
12913    use super::*;
12914    use hns_primitives::{BlockHash, Height, Outpoint as CanonicalOutpoint};
12915    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
12916    use std::sync::mpsc;
12917    use std::time::Duration;
12918
12919    #[test]
12920    fn send_propagation_grace_applies_only_to_recent_broadcasts() {
12921        assert!(send_is_within_propagation_grace(
12922            HnsSendStage::Broadcast,
12923            1_000,
12924            1_000 + SEND_PROPAGATION_GRACE_SECONDS - 1,
12925        ));
12926        assert!(!send_is_within_propagation_grace(
12927            HnsSendStage::Broadcast,
12928            1_000,
12929            1_000 + SEND_PROPAGATION_GRACE_SECONDS,
12930        ));
12931        assert!(!send_is_within_propagation_grace(
12932            HnsSendStage::Mempool,
12933            1_000,
12934            1_001,
12935        ));
12936        // A persisted timestamp slightly ahead of a corrected wall clock is
12937        // treated conservatively as recent instead of forcing a resubmission.
12938        assert!(send_is_within_propagation_grace(
12939            HnsSendStage::Broadcast,
12940            1_001,
12941            1_000,
12942        ));
12943    }
12944
12945    #[test]
12946    fn propagating_send_activity_comes_from_exact_durable_bytes() {
12947        let config = test_runtime_config();
12948        let transaction = Transaction {
12949            version: 0,
12950            inputs: Vec::new(),
12951            outputs: vec![Output {
12952                value: Dollarydoos::new(90),
12953                address: Address::new(0, vec![3; 20]).expect("payment address"),
12954                covenant: Covenant::default(),
12955            }],
12956            locktime: 0,
12957        };
12958        let raw = transaction.encode().expect("transaction bytes");
12959        let txid = TransactionHash::new(
12960            transaction
12961                .transaction_hash()
12962                .expect("transaction hash")
12963                .into_bytes(),
12964        );
12965        let stored = StoredWorkflow {
12966            id: WorkflowId::new([41; 16]),
12967            kind: WorkflowKind::HnsSend,
12968            revision: 3,
12969            state: HnsSendWorkflow {
12970                plan: HnsSpendPlan {
12971                    wallet_id: config.wallet_id,
12972                    account_id: config.account_id,
12973                    workflow_id: WorkflowId::new([41; 16]),
12974                    request_nonce: 7,
12975                    unsigned_transaction: raw.clone(),
12976                    inputs: Vec::new(),
12977                    amount: BaseUnits::new(90),
12978                    fee: BaseUnits::new(10),
12979                    maximum_fee: BaseUnits::new(10),
12980                    destination: "rs1qexample".to_owned(),
12981                    expires_at_unix: 2_000,
12982                },
12983                stage: HnsSendStage::Broadcast,
12984                transaction: Some(txid),
12985                signed_transaction: Some(raw.clone()),
12986                fee_quote: None,
12987            },
12988            irreversible_broadcast_prepared: true,
12989            updated_at_unix: 1_000,
12990        };
12991
12992        let record = pending_send_record(&stored, LocalTransactionStatus::Broadcast)
12993            .expect("broadcast activity");
12994        assert_eq!(record.raw, raw);
12995        assert_eq!(record.summary.txid, txid);
12996        assert_eq!(record.summary.status, LocalTransactionStatus::Broadcast);
12997        assert_eq!(record.summary.fee, Some(BaseUnits::new(10)));
12998        assert_eq!(record.summary.first_seen_unix, Some(1_000));
12999        assert!(record.summary.net_amount.negative);
13000        assert_eq!(record.summary.net_amount.magnitude, BaseUnits::new(100));
13001        let dropped = pending_send_record(&stored, LocalTransactionStatus::Dropped)
13002            .expect("durable dropped activity");
13003        assert_eq!(dropped.summary.status, LocalTransactionStatus::Dropped);
13004        assert_eq!(dropped.raw, raw);
13005
13006        let mut mismatched = stored;
13007        mismatched.state.transaction = Some(TransactionHash::new([9; 32]));
13008        assert!(matches!(
13009            pending_send_record(&mismatched, LocalTransactionStatus::Broadcast),
13010            Err(HnsWalletError::InvalidEvidence)
13011        ));
13012    }
13013
13014    #[test]
13015    fn pending_name_activity_statuses_cover_submission_and_recovery() {
13016        assert_eq!(
13017            pending_name_transaction_status(NameOperationState::Authorized),
13018            Some(LocalTransactionStatus::Authorized)
13019        );
13020        assert_eq!(
13021            pending_name_transaction_status(NameOperationState::Broadcast),
13022            Some(LocalTransactionStatus::Broadcast)
13023        );
13024        assert_eq!(
13025            pending_name_transaction_status(NameOperationState::Mempool),
13026            Some(LocalTransactionStatus::Mempool)
13027        );
13028        assert_eq!(
13029            pending_name_transaction_status(NameOperationState::RequiresRebroadcast),
13030            Some(LocalTransactionStatus::Dropped)
13031        );
13032        assert_eq!(
13033            pending_name_transaction_status(NameOperationState::Conflicted),
13034            Some(LocalTransactionStatus::Conflicted)
13035        );
13036        assert_eq!(
13037            pending_name_transaction_status(NameOperationState::Finalized),
13038            None
13039        );
13040    }
13041
13042    #[test]
13043    fn terminal_dropped_sends_atomically_release_activated_reservations() {
13044        let mut store = WalletStore::create(":memory:", "passphrase").expect("store");
13045        let config = test_runtime_config();
13046        let workflow_id = WorkflowId::new([42; 16]);
13047        let transaction_id = TransactionHash::new([43; 32]);
13048        let outpoint = HnsOutpoint {
13049            transaction: TransactionHash::new([44; 32]),
13050            output_index: 1,
13051        };
13052        let input = TrackedHnsCoin {
13053            coin: WalletCoin {
13054                outpoint,
13055                value: BaseUnits::new(1_000_000),
13056                confirmation_count: 3,
13057                confirmed_height: Some(500),
13058                coinbase: false,
13059                covenant: Covenant::default().encode().expect("covenant"),
13060                name_locked: false,
13061            },
13062            derivation: DerivationReference {
13063                role: KeyRole::HnsCoin,
13064                account: config.account_derivation_index,
13065                change: 0,
13066                index: 2,
13067            },
13068            address_program: vec![45; 20],
13069        };
13070        let binding = test_snapshot(46);
13071        let mempool = test_mempool(47);
13072        let state = HnsSendWorkflow {
13073            plan: HnsSpendPlan {
13074                wallet_id: config.wallet_id,
13075                account_id: config.account_id,
13076                workflow_id,
13077                request_nonce: 1,
13078                unsigned_transaction: vec![1],
13079                inputs: vec![input],
13080                amount: BaseUnits::new(100_000),
13081                fee: BaseUnits::new(10_000),
13082                maximum_fee: BaseUnits::new(10_000),
13083                destination: "rs1qexample".to_owned(),
13084                expires_at_unix: 2_000,
13085            },
13086            stage: HnsSendStage::RequiresRebroadcast,
13087            transaction: Some(transaction_id),
13088            signed_transaction: Some(vec![2]),
13089            fee_quote: Some(HnsTransactionFeeQuote {
13090                txid: transaction_id,
13091                binding,
13092                mempool,
13093                target_blocks: DEFAULT_FEE_TARGET_BLOCKS,
13094                rate_atomic_units_per_1000_policy_vbytes: 1_000,
13095                rate_sample_count: 0,
13096                rate_source: HnsFeeRateSource::MinimumRelay,
13097                transaction_weight: 1,
13098                transaction_sigops: 0,
13099                sigop_adjusted_policy_vbytes: 1,
13100                minimum_policy_fee: BaseUnits::new(1),
13101                actual_fee: BaseUnits::new(10_000),
13102                meets_minimum_policy_fee: true,
13103                minimum_policy_fee_shortfall: BaseUnits::ZERO,
13104            }),
13105        };
13106        let reservation = HnsInputReservation {
13107            wallet_id: config.wallet_id,
13108            account_id: config.account_id,
13109            outpoint,
13110            workflow_id,
13111            expires_at_unix: None,
13112            kind: HnsInputReservationKind::Ordinary,
13113        };
13114        store
13115            .save_workflow(workflow_id, WorkflowKind::HnsSend, 0, &state, true, 1_000)
13116            .expect("workflow");
13117        store
13118            .save_input_reservation(
13119                &namespaced_outpoint_id(&config, outpoint),
13120                0,
13121                &reservation,
13122                1_000,
13123            )
13124            .expect("activated reservation");
13125
13126        let observed = store
13127            .load_workflow::<HnsSendWorkflow>(workflow_id)
13128            .expect("load observed workflow")
13129            .expect("observed workflow");
13130        persist_observed_send_stage(
13131            &mut store,
13132            &config,
13133            &observed,
13134            HnsSendStage::Conflicted,
13135            1_050,
13136        )
13137        .expect("persist conflict and release reservation");
13138        let observed = store
13139            .load_workflow::<HnsSendWorkflow>(workflow_id)
13140            .expect("reload observed workflow")
13141            .expect("observed workflow remains auditable");
13142        assert_eq!(observed.state.stage, HnsSendStage::Conflicted);
13143        assert!(
13144            account_input_reservations(&store, &config)
13145                .expect("conflict reservations")
13146                .is_empty()
13147        );
13148
13149        let obsolete_workflow_id = WorkflowId::new([48; 16]);
13150        let mut obsolete_state = state;
13151        obsolete_state.plan.workflow_id = obsolete_workflow_id;
13152        let mut obsolete_reservation = reservation;
13153        obsolete_reservation.workflow_id = obsolete_workflow_id;
13154        store
13155            .save_workflow(
13156                obsolete_workflow_id,
13157                WorkflowKind::HnsSend,
13158                0,
13159                &obsolete_state,
13160                true,
13161                1_075,
13162            )
13163            .expect("obsolete workflow");
13164        store
13165            .save_input_reservation(
13166                &namespaced_outpoint_id(&config, outpoint),
13167                0,
13168                &obsolete_reservation,
13169                1_075,
13170            )
13171            .expect("obsolete activated reservation");
13172
13173        abandon_obsolete_dropped_send(
13174            &mut store,
13175            &config,
13176            obsolete_workflow_id,
13177            &BTreeSet::from([transaction_id]),
13178            1_100,
13179        )
13180        .expect("abandon obsolete send");
13181
13182        let stored = store
13183            .load_workflow::<HnsSendWorkflow>(obsolete_workflow_id)
13184            .expect("load workflow")
13185            .expect("workflow remains auditable");
13186        assert_eq!(stored.state.stage, HnsSendStage::Abandoned);
13187        assert!(
13188            account_input_reservations(&store, &config)
13189                .expect("reservations")
13190                .is_empty()
13191        );
13192    }
13193
13194    fn test_runtime_config() -> HnsRuntimeConfig {
13195        HnsRuntimeConfig {
13196            wallet_id: WalletId::new([11; 16]),
13197            account_id: AccountId::new([12; 16]),
13198            account_derivation_index: 7,
13199            network: HnsNetwork::Regtest,
13200            birthday_height: 100,
13201            restore_lookahead: DEFAULT_RESTORE_LOOKAHEAD,
13202            minimum_confirmations: 2,
13203            dust_threshold: BaseUnits::new(DEFAULT_DUST_THRESHOLD),
13204            value_operations_enabled: false,
13205            settlement_enabled: false,
13206        }
13207    }
13208
13209    #[test]
13210    fn settlement_preparation_rebases_an_unchanged_account_revision() {
13211        let prepared =
13212            HnsAccountRecord::initial_non_value(test_runtime_config()).expect("test account");
13213        assert_eq!(
13214            authoritative_unchanged_account_revision(&prepared, &prepared, 37)
13215                .expect("an evidence-only reconciliation may advance the revision"),
13216            37,
13217        );
13218
13219        let mut changed = prepared.clone();
13220        changed.next_change_index = changed.next_change_index.saturating_add(1);
13221        assert_eq!(
13222            authoritative_unchanged_account_revision(&prepared, &changed, 38),
13223            Err(ChainError::InvalidEvidence),
13224        );
13225    }
13226
13227    fn twenty_four_word_phrase() -> String {
13228        Mnemonic::from_entropy(&[0_u8; 32])
13229            .expect("32-byte BIP-39 entropy")
13230            .to_string()
13231    }
13232
13233    #[test]
13234    fn native_bootstrap_restores_one_non_value_account_atomically() {
13235        let phrase = twenty_four_word_phrase();
13236        assert_eq!(phrase.split_whitespace().count(), 24);
13237        let policy = HnsBootstrapPolicy::new(HnsNetwork::Regtest, 123);
13238        let bootstrap = HnsWalletBootstrap::restore(&phrase, policy).expect("prepare restore");
13239
13240        let mut legacy_store = WalletStore::create(":memory:", "legacy restore passphrase")
13241            .expect("legacy restore store");
13242        let legacy_wallet_id =
13243            restore_wallet(&mut legacy_store, &phrase, 1).expect("legacy restore wallet ID");
13244        assert_eq!(bootstrap.wallet_id(), legacy_wallet_id);
13245
13246        let account = bootstrap.account_record();
13247        assert!(
13248            account
13249                .config
13250                .account_id
13251                .as_bytes()
13252                .iter()
13253                .any(|byte| *byte != 0)
13254        );
13255        assert_eq!(account.config.account_derivation_index, 0);
13256        assert_eq!(account.config.network, HnsNetwork::Regtest);
13257        assert_eq!(account.config.birthday_height, 123);
13258        assert_eq!(account.config.restore_lookahead, DEFAULT_RESTORE_LOOKAHEAD);
13259        assert_eq!(account.config.minimum_confirmations, 2);
13260        assert_eq!(
13261            account.config.dust_threshold,
13262            BaseUnits::new(DEFAULT_DUST_THRESHOLD)
13263        );
13264        assert!(!account.config.value_operations_enabled);
13265        assert!(!account.config.settlement_enabled);
13266        assert_eq!(account.external_scan_end, DEFAULT_RESTORE_LOOKAHEAD - 1);
13267        assert_eq!(account.internal_scan_end, DEFAULT_RESTORE_LOOKAHEAD - 1);
13268        assert_eq!(account.shakedex_scan_end, DEFAULT_RESTORE_LOOKAHEAD - 1);
13269        assert!(!account.shakedex_scan_complete);
13270        assert!(!format!("{bootstrap:?}").contains(&phrase));
13271
13272        let expected_account = account.clone();
13273        let mut store = WalletStore::create(":memory:", "native bootstrap passphrase")
13274            .expect("native bootstrap store");
13275        assert_eq!(
13276            bootstrap.persist(&mut store, 5).expect("persist bootstrap"),
13277            1
13278        );
13279        let seed = store
13280            .get_secret(bootstrap.wallet_id().as_bytes(), SecretKind::RecoverySeed)
13281            .expect("read seed")
13282            .expect("seed present");
13283        let mnemonic = Mnemonic::parse_in_normalized(Language::English, &phrase)
13284            .expect("parse fixture mnemonic");
13285        assert_eq!(seed.as_slice(), mnemonic.to_seed_normalized("").as_slice());
13286        let stored = store
13287            .wallet_account::<HnsAccountRecord>(&account_entity_id(&expected_account.config))
13288            .expect("read account")
13289            .expect("account present");
13290        assert_eq!(stored.revision, 1);
13291        assert_eq!(stored.value, expected_account);
13292
13293        let displayed = bootstrap
13294            .into_recovery_phrase()
13295            .expose_for_dedicated_display();
13296        assert_eq!(displayed, phrase);
13297    }
13298
13299    #[test]
13300    fn native_bootstrap_requires_24_words_and_rejects_replay() {
13301        const TWELVE_WORD_PHRASE: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
13302        let policy = HnsBootstrapPolicy::new(HnsNetwork::Testnet, 456);
13303        assert!(matches!(
13304            HnsWalletBootstrap::restore(TWELVE_WORD_PHRASE, policy),
13305            Err(HnsWalletError::InvalidRecoveryPhrase)
13306        ));
13307
13308        // The legacy seed-only API retains its historical support for valid
13309        // BIP-39 word counts other than 24.
13310        let mut legacy_store =
13311            WalletStore::create(":memory:", "legacy twelve-word passphrase").expect("legacy store");
13312        restore_wallet(&mut legacy_store, TWELVE_WORD_PHRASE, 1)
13313            .expect("legacy twelve-word restore");
13314
13315        let phrase = twenty_four_word_phrase();
13316        let first = HnsWalletBootstrap::restore(&phrase, policy).expect("first bootstrap");
13317        let second = HnsWalletBootstrap::restore(&phrase, policy).expect("replayed bootstrap");
13318        let mut store = WalletStore::create(":memory:", "replay bootstrap passphrase")
13319            .expect("bootstrap store");
13320        first.persist(&mut store, 2).expect("first persistence");
13321        assert!(matches!(
13322            second.persist(&mut store, 3),
13323            Err(StoreError::BootstrapConflict)
13324        ));
13325        let accounts = store
13326            .wallet_accounts::<HnsAccountRecord>(2)
13327            .expect("complete account list");
13328        assert_eq!(accounts.len(), 1);
13329        assert_eq!(&accounts[0].value, first.account_record());
13330    }
13331
13332    #[test]
13333    fn generated_native_bootstrap_uses_24_words_and_nonzero_account_id() {
13334        let bootstrap =
13335            HnsWalletBootstrap::generate(HnsBootstrapPolicy::new(HnsNetwork::Simnet, 0))
13336                .expect("generated bootstrap");
13337        assert!(
13338            bootstrap
13339                .account_record()
13340                .config
13341                .account_id
13342                .as_bytes()
13343                .iter()
13344                .any(|byte| *byte != 0)
13345        );
13346        let phrase = bootstrap
13347            .into_recovery_phrase()
13348            .expose_for_dedicated_display();
13349        assert_eq!(phrase.split_whitespace().count(), 24);
13350    }
13351
13352    #[test]
13353    fn hsd_bip44_payment_branch_is_canonical() {
13354        // Generated independently by canonical hsd 8.0.0. This proves the
13355        // implementation rather than comparing two paths through this crate.
13356        let phrase = "april coyote civil finger crane uncle situate moon choice wrong \
13357            goose client purse deer funny hobby shrug give anxiety truly rack stand salad coach";
13358        let mnemonic =
13359            Mnemonic::parse_in_normalized(Language::English, phrase).expect("fixture mnemonic");
13360        let seed = mnemonic.to_seed_normalized("");
13361        let payment = DerivationReference {
13362            role: KeyRole::HnsCoin,
13363            account: 0,
13364            change: 0,
13365            index: 0,
13366        };
13367        let actual =
13368            derive_hsd_bip44_secret(&seed, HnsNetwork::Mainnet, payment).expect("HNS BIP-44 key");
13369        let expected_path = "m/44'/5353'/0'/0/0"
13370            .parse::<DerivationPath>()
13371            .expect("canonical hsd path");
13372        let expected = XPrv::derive_from_path(&seed, &expected_path).expect("canonical hsd child");
13373        assert_eq!(
13374            actual.as_slice(),
13375            expected.private_key().to_bytes().as_slice()
13376        );
13377        let public = SigningKey::from_slice(actual.as_slice())
13378            .expect("hsd secret")
13379            .verifying_key()
13380            .to_sec1_point(true);
13381        assert_eq!(
13382            hex::encode(public.as_bytes()),
13383            "03a527c08aeb86e99f6a4019d9bcd38290a598d7287fcca929a684004ed8d41d39"
13384        );
13385        let public_bytes: [u8; 33] = public.as_bytes().try_into().expect("compressed hsd key");
13386        let program = public_key_hash(&public_bytes).expect("hsd key hash");
13387        assert_eq!(
13388            encode_v0_address(HnsNetwork::Mainnet, &program).expect("hsd address"),
13389            "hs1q79vn7nsmua98v4gme98w0a07rgrvvxy9d93qw8"
13390        );
13391        assert_eq!(
13392            [
13393                hsd_bip44_coin_type(HnsNetwork::Mainnet),
13394                hsd_bip44_coin_type(HnsNetwork::Testnet),
13395                hsd_bip44_coin_type(HnsNetwork::Regtest),
13396                hsd_bip44_coin_type(HnsNetwork::Simnet),
13397            ],
13398            [5353, 5354, 5355, 5356]
13399        );
13400
13401        let policy = HnsBootstrapPolicy::new(HnsNetwork::Mainnet, 0);
13402        let restored = HnsWalletBootstrap::restore(phrase, policy).expect("standard restore");
13403        assert_eq!(
13404            restored.account_record().config.network,
13405            HnsNetwork::Mainnet
13406        );
13407    }
13408
13409    fn test_derived_address(role: KeyRole, program: u8) -> DerivedHnsAddress {
13410        let config = test_runtime_config();
13411        let program_length = if role == KeyRole::HnsShakedex { 32 } else { 20 };
13412        DerivedHnsAddress {
13413            account_id: config.account_id,
13414            derivation: DerivationReference {
13415                role,
13416                account: config.account_derivation_index,
13417                change: 0,
13418                index: 0,
13419            },
13420            address: format!("test-address-{program}"),
13421            program: vec![program; program_length],
13422            used: false,
13423        }
13424    }
13425
13426    fn test_snapshot(epoch: u64) -> SnapshotBinding {
13427        SnapshotBinding {
13428            tip: ChainTip {
13429                height: 500,
13430                block_hash: [21; 32],
13431                tree_root: [22; 32],
13432                median_time_past: 1_700_000_000,
13433            },
13434            chain_epoch: epoch,
13435        }
13436    }
13437
13438    fn test_mempool(generation: u64) -> MempoolSnapshotBinding {
13439        MempoolSnapshotBinding {
13440            instance_nonce: [23; 32],
13441            generation,
13442        }
13443    }
13444
13445    const PRODUCTION_FOLLOWUP_PASSPHRASE: &str = "correct horse battery staple";
13446
13447    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
13448    enum ProductionFollowupReadFault {
13449        Healthy,
13450        WrongNetwork,
13451        StaleChain,
13452        RestartedMempool,
13453        ChangedAccount,
13454        LockedStore,
13455    }
13456
13457    struct ProductionFollowupReadBackend {
13458        store: SharedWalletStore,
13459        account_id: [u8; 32],
13460        network: HnsNetwork,
13461        fault: ProductionFollowupReadFault,
13462        name_history_program: Option<Vec<u8>>,
13463        incoming_candidates: Vec<IncomingTransferCandidate>,
13464        finalize_coin: Option<(WalletAddressKey, Coin)>,
13465        active_owner: Option<([u8; 32], ActiveNameOwnerCoinEvidence)>,
13466        snapshot_calls: AtomicUsize,
13467        tip_calls: AtomicUsize,
13468        confirmed_calls: AtomicUsize,
13469        mempool_calls: AtomicUsize,
13470        change_watch_calls: AtomicUsize,
13471        change_watch_fails: AtomicBool,
13472    }
13473
13474    impl ProductionFollowupReadBackend {
13475        fn new(
13476            store: SharedWalletStore,
13477            config: &HnsRuntimeConfig,
13478            fault: ProductionFollowupReadFault,
13479        ) -> Self {
13480            Self {
13481                store,
13482                account_id: account_entity_id(config),
13483                network: config.network,
13484                fault,
13485                name_history_program: None,
13486                incoming_candidates: Vec::new(),
13487                finalize_coin: None,
13488                active_owner: None,
13489                snapshot_calls: AtomicUsize::new(0),
13490                tip_calls: AtomicUsize::new(0),
13491                confirmed_calls: AtomicUsize::new(0),
13492                mempool_calls: AtomicUsize::new(0),
13493                change_watch_calls: AtomicUsize::new(0),
13494                change_watch_fails: AtomicBool::new(false),
13495            }
13496        }
13497
13498        fn with_name_history_program(mut self, program: Vec<u8>) -> Self {
13499            self.name_history_program = Some(program);
13500            self
13501        }
13502
13503        fn with_incoming_candidate(mut self, candidate: IncomingTransferCandidate) -> Self {
13504            self.incoming_candidates = vec![candidate];
13505            self
13506        }
13507
13508        fn with_incoming_candidates(mut self, candidates: Vec<IncomingTransferCandidate>) -> Self {
13509            self.incoming_candidates = candidates;
13510            self
13511        }
13512
13513        fn with_finalize_owner(
13514            mut self,
13515            script: WalletAddressKey,
13516            coin: Coin,
13517            name_hash: [u8; 32],
13518            evidence: ActiveNameOwnerCoinEvidence,
13519        ) -> Self {
13520            self.finalize_coin = Some((script, coin));
13521            self.active_owner = Some((name_hash, evidence));
13522            self
13523        }
13524
13525        fn binding() -> SnapshotBinding {
13526            SnapshotBinding {
13527                tip: ChainTip {
13528                    height: 1,
13529                    block_hash: [31; 32],
13530                    tree_root: [32; 32],
13531                    median_time_past: 1_700_000_000,
13532                },
13533                chain_epoch: 7,
13534            }
13535        }
13536
13537        fn mempool() -> MempoolSnapshotBinding {
13538            MempoolSnapshotBinding {
13539                instance_nonce: [33; 32],
13540                generation: 9,
13541            }
13542        }
13543
13544        fn prove_store_mutex_is_released(&self) -> Result<(), HnsWalletError> {
13545            let store = self.store.clone();
13546            let (sender, receiver) = mpsc::sync_channel(1);
13547            std::thread::spawn(move || {
13548                let result = store.with_store(|_| Ok(())).is_ok();
13549                let _ = sender.send(result);
13550            });
13551            match receiver.recv_timeout(Duration::from_secs(1)) {
13552                Ok(true) => Ok(()),
13553                Ok(false) => Err(HnsWalletError::Backend(
13554                    "shared store probe failed during backend I/O".to_owned(),
13555                )),
13556                Err(_) => Err(HnsWalletError::Backend(
13557                    "backend was invoked while the shared store mutex was held".to_owned(),
13558                )),
13559            }
13560        }
13561
13562        fn fail_if_unexpected(method: &str) -> HnsWalletError {
13563            HnsWalletError::Backend(format!(
13564                "unexpected value or evidence method in account read: {method}"
13565            ))
13566        }
13567    }
13568
13569    impl HnsBackend for ProductionFollowupReadBackend {
13570        fn extend_locally_allocated_change_watch_set(
13571            &self,
13572            _account: &HnsAccountRecord,
13573            _now_unix: u64,
13574        ) -> Result<bool, HnsWalletError> {
13575            self.prove_store_mutex_is_released()?;
13576            self.change_watch_calls.fetch_add(1, Ordering::SeqCst);
13577            if self.change_watch_fails.load(Ordering::SeqCst) {
13578                return Err(HnsWalletError::Backend(
13579                    "injected change watch extension failure".to_owned(),
13580                ));
13581            }
13582            Ok(true)
13583        }
13584
13585        fn get_chain_snapshot(&self) -> Result<SnapshotBinding, HnsWalletError> {
13586            self.prove_store_mutex_is_released()?;
13587            if self.snapshot_calls.fetch_add(1, Ordering::SeqCst) == 0 {
13588                match self.fault {
13589                    ProductionFollowupReadFault::ChangedAccount => {
13590                        self.store
13591                            .with_store_mut(|store| {
13592                                let stored = store
13593                                    .wallet_account::<HnsAccountRecord>(&self.account_id)?
13594                                    .ok_or(StoreError::CorruptMetadata)?;
13595                                let mut changed = stored.value;
13596                                changed.next_receive_index = changed
13597                                    .next_receive_index
13598                                    .checked_add(1)
13599                                    .ok_or(StoreError::RevisionOverflow)?;
13600                                store
13601                                    .save_wallet_account(
13602                                        &self.account_id,
13603                                        stored.revision,
13604                                        &changed,
13605                                        101,
13606                                    )
13607                                    .map(|_| ())
13608                            })
13609                            .map_err(HnsWalletError::from)?;
13610                    }
13611                    ProductionFollowupReadFault::LockedStore => {
13612                        self.store.lock().map_err(HnsWalletError::from)?;
13613                    }
13614                    _ => {}
13615                }
13616            }
13617            Ok(Self::binding())
13618        }
13619
13620        fn get_chain_tip(&self) -> Result<ChainTip, HnsWalletError> {
13621            self.prove_store_mutex_is_released()?;
13622            self.tip_calls.fetch_add(1, Ordering::SeqCst);
13623            Ok(Self::binding().tip)
13624        }
13625
13626        fn get_block_hash(
13627            &self,
13628            height: u64,
13629            binding: SnapshotBinding,
13630        ) -> Result<BlockHashEvidence, HnsWalletError> {
13631            self.prove_store_mutex_is_released()?;
13632            let block_hash = if height == 0 {
13633                let network = if self.fault == ProductionFollowupReadFault::WrongNetwork {
13634                    HnsNetwork::Mainnet
13635                } else {
13636                    self.network
13637                };
13638                name_workflow::expected_chain_identity(network)?.1
13639            } else if height == binding.tip.height {
13640                binding.tip.block_hash
13641            } else {
13642                [35; 32]
13643            };
13644            Ok(BlockHashEvidence {
13645                binding,
13646                height,
13647                block_hash: Some(block_hash),
13648            })
13649        }
13650
13651        fn get_confirmed_wallet_page(
13652            &self,
13653            request: ConfirmedWalletPageRequest<'_>,
13654        ) -> Result<ConfirmedWalletPage, HnsWalletError> {
13655            self.prove_store_mutex_is_released()?;
13656            let call = self.confirmed_calls.fetch_add(1, Ordering::SeqCst);
13657            let mut binding = Self::binding();
13658            if request.expected_tip != binding.tip
13659                || request.expected_epoch != Some(binding.chain_epoch)
13660            {
13661                return Err(HnsWalletError::StaleNodeSnapshot);
13662            }
13663            if self.fault == ProductionFollowupReadFault::StaleChain && call > 0 {
13664                binding.chain_epoch += 1;
13665            }
13666            let history = self
13667                .name_history_program
13668                .as_ref()
13669                .and_then(|program| {
13670                    request
13671                        .scripts
13672                        .iter()
13673                        .position(|script| script.hash.as_slice() == program.as_slice())
13674                })
13675                .map(|script_index| HistoryEntry {
13676                    txid: TransactionHash::new([0x71; 32]),
13677                    height: Some(binding.tip.height),
13678                    block_hash: Some(binding.tip.block_hash),
13679                    transaction_position: Some(0),
13680                    spent: false,
13681                    first_seen_unix: Some(binding.tip.median_time_past),
13682                    script_index: u32::try_from(script_index).expect("bounded script index"),
13683                })
13684                .into_iter()
13685                .collect();
13686            let utxos = self
13687                .finalize_coin
13688                .as_ref()
13689                .and_then(|(expected_script, coin)| {
13690                    request
13691                        .scripts
13692                        .iter()
13693                        .position(|script| script == expected_script)
13694                        .map(|script_index| IndexedWalletCoin {
13695                            coin: WalletCoin {
13696                                outpoint: HnsOutpoint {
13697                                    transaction: TransactionHash::new(
13698                                        coin.outpoint.transaction_hash.into_bytes(),
13699                                    ),
13700                                    output_index: coin.outpoint.index,
13701                                },
13702                                value: BaseUnits::new(u128::from(coin.value.get())),
13703                                confirmation_count: u32::try_from(
13704                                    binding.tip.height - u64::from(coin.height.get()) + 1,
13705                                )
13706                                .expect("fixture confirmation count"),
13707                                confirmed_height: Some(coin.height.get()),
13708                                coinbase: coin.coinbase,
13709                                covenant: coin.covenant.encode().expect("fixture covenant"),
13710                                name_locked: !matches!(coin.covenant.kind, CovenantKind::None),
13711                            },
13712                            script_index: u32::try_from(script_index)
13713                                .expect("bounded fixture script index"),
13714                            output_address: expected_script.clone(),
13715                        })
13716                })
13717                .into_iter()
13718                .collect();
13719            Ok(ConfirmedWalletPage {
13720                binding,
13721                next_cursor: None,
13722                history,
13723                utxos,
13724            })
13725        }
13726
13727        fn get_incoming_transfers_page(
13728            &self,
13729            request: IncomingTransfersPageRequest<'_>,
13730        ) -> Result<IncomingTransfersPage, HnsWalletError> {
13731            self.prove_store_mutex_is_released()?;
13732            if request.binding != Self::binding()
13733                || request.scripts.is_empty()
13734                || request.limit == 0
13735            {
13736                return Err(HnsWalletError::StaleNodeSnapshot);
13737            }
13738            let start = request.cursor.map_or(Ok(0usize), |cursor| {
13739                let raw: [u8; 4] = cursor
13740                    .try_into()
13741                    .map_err(|_| HnsWalletError::StaleNodeSnapshot)?;
13742                usize::try_from(u32::from_le_bytes(raw))
13743                    .map_err(|_| HnsWalletError::StaleNodeSnapshot)
13744            })?;
13745            if start > self.incoming_candidates.len() {
13746                return Err(HnsWalletError::StaleNodeSnapshot);
13747            }
13748            let selected = self
13749                .incoming_candidates
13750                .iter()
13751                .enumerate()
13752                .skip(start)
13753                .find_map(|(candidate_index, candidate)| {
13754                    request
13755                        .scripts
13756                        .iter()
13757                        .position(|script| script == &candidate.recipient)
13758                        .map(|script_index| (candidate_index, script_index, candidate))
13759                });
13760            let (entries, next_cursor) = selected.map_or_else(
13761                || (Vec::new(), None),
13762                |(candidate_index, script_index, candidate)| {
13763                    let next = candidate_index + 1;
13764                    (
13765                        vec![IncomingTransferCandidate {
13766                            script_index: u32::try_from(script_index)
13767                                .expect("bounded fixture script index"),
13768                            ..candidate.clone()
13769                        }],
13770                        (next < self.incoming_candidates.len()).then(|| {
13771                            u32::try_from(next)
13772                                .expect("bounded fixture continuation")
13773                                .to_le_bytes()
13774                                .to_vec()
13775                        }),
13776                    )
13777                },
13778            );
13779            Ok(IncomingTransfersPage {
13780                projection_version: 1,
13781                binding: request.binding,
13782                entries,
13783                script_examinations: request.scripts.len().min(MAX_SCAN_PAGE_RESULTS),
13784                next_cursor,
13785            })
13786        }
13787
13788        fn get_mempool_wallet_page(
13789            &self,
13790            _: MempoolWalletPageRequest<'_>,
13791        ) -> Result<MempoolWalletPage, HnsWalletError> {
13792            self.prove_store_mutex_is_released()?;
13793            let call = self.mempool_calls.fetch_add(1, Ordering::SeqCst);
13794            let mempool =
13795                if self.fault == ProductionFollowupReadFault::RestartedMempool && call >= 3 {
13796                    MempoolSnapshotBinding {
13797                        instance_nonce: [34; 32],
13798                        generation: 1,
13799                    }
13800                } else {
13801                    Self::mempool()
13802                };
13803            Ok(MempoolWalletPage {
13804                binding: Self::binding(),
13805                mempool,
13806                next_cursor: None,
13807                history: Vec::new(),
13808            })
13809        }
13810
13811        fn get_transaction_evidence(
13812            &self,
13813            _: TransactionHash,
13814            _: SnapshotBinding,
13815            _: Option<MempoolSnapshotBinding>,
13816        ) -> Result<TransactionEvidence, HnsWalletError> {
13817            Err(Self::fail_if_unexpected("get_transaction_evidence"))
13818        }
13819
13820        fn get_outpoint_spend_evidence(
13821            &self,
13822            _: &[HnsOutpoint],
13823            _: SnapshotBinding,
13824        ) -> Result<OutpointSpendEvidence, HnsWalletError> {
13825            Err(Self::fail_if_unexpected("get_outpoint_spend_evidence"))
13826        }
13827
13828        fn broadcast_transaction(&self, _: &[u8]) -> Result<TransactionHash, HnsWalletError> {
13829            Err(Self::fail_if_unexpected("broadcast_transaction"))
13830        }
13831
13832        fn quote_transaction_fee(
13833            &self,
13834            _: &[u8],
13835            _: &[Coin],
13836            _: u16,
13837            _: SnapshotBinding,
13838            _: MempoolSnapshotBinding,
13839        ) -> Result<HnsTransactionFeeQuote, HnsWalletError> {
13840            Err(Self::fail_if_unexpected("quote_transaction_fee"))
13841        }
13842
13843        fn estimate_fee_rate(&self, _: u16) -> Result<BaseUnits, HnsWalletError> {
13844            Err(Self::fail_if_unexpected("estimate_fee_rate"))
13845        }
13846
13847        fn get_name_evidence(
13848            &self,
13849            _: [u8; 32],
13850            _: SnapshotBinding,
13851        ) -> Result<NameEvidence, HnsWalletError> {
13852            Err(Self::fail_if_unexpected("get_name_evidence"))
13853        }
13854
13855        fn get_active_name_owner_coin(
13856            &self,
13857            name_hash: [u8; 32],
13858            binding: SnapshotBinding,
13859        ) -> Result<ActiveNameOwnerCoinEvidence, HnsWalletError> {
13860            self.prove_store_mutex_is_released()?;
13861            let (expected_name_hash, evidence) = self
13862                .active_owner
13863                .as_ref()
13864                .ok_or_else(|| Self::fail_if_unexpected("get_active_name_owner_coin"))?;
13865            if *expected_name_hash != name_hash || evidence.binding != binding {
13866                return Err(HnsWalletError::InvalidEvidence);
13867            }
13868            Ok(evidence.clone())
13869        }
13870
13871        fn get_name_action_context(
13872            &self,
13873            _: HnsNameAction,
13874            _: [u8; 32],
13875            _: SnapshotBinding,
13876            _: MempoolSnapshotBinding,
13877        ) -> Result<NameActionContextEvidence, HnsWalletError> {
13878            Err(Self::fail_if_unexpected("get_name_action_context"))
13879        }
13880    }
13881
13882    struct NativeNameImportBackend {
13883        store: SharedWalletStore,
13884        account_id: [u8; 32],
13885        network: HnsNetwork,
13886        evidence: Vec<NameEvidence>,
13887        mutate_account_on_evidence: AtomicBool,
13888        snapshot_calls: AtomicUsize,
13889        evidence_calls: AtomicUsize,
13890    }
13891
13892    impl NativeNameImportBackend {
13893        fn new(
13894            store: SharedWalletStore,
13895            config: &HnsRuntimeConfig,
13896            evidence: NameEvidence,
13897        ) -> Self {
13898            Self {
13899                store,
13900                account_id: account_entity_id(config),
13901                network: config.network,
13902                evidence: vec![evidence],
13903                mutate_account_on_evidence: AtomicBool::new(false),
13904                snapshot_calls: AtomicUsize::new(0),
13905                evidence_calls: AtomicUsize::new(0),
13906            }
13907        }
13908
13909        fn with_stale_account_mutation(self) -> Self {
13910            self.mutate_account_on_evidence
13911                .store(true, Ordering::SeqCst);
13912            self
13913        }
13914
13915        fn with_evidence(mut self, evidence: NameEvidence) -> Self {
13916            self.evidence.push(evidence);
13917            self
13918        }
13919
13920        fn binding() -> SnapshotBinding {
13921            SnapshotBinding {
13922                tip: ChainTip {
13923                    height: 500,
13924                    block_hash: [81; 32],
13925                    tree_root: [0; 32],
13926                    median_time_past: 1_700_000_000,
13927                },
13928                chain_epoch: 12,
13929            }
13930        }
13931
13932        fn prove_store_mutex_is_released(&self) -> Result<(), HnsWalletError> {
13933            let store = self.store.clone();
13934            let (sender, receiver) = mpsc::sync_channel(1);
13935            std::thread::spawn(move || {
13936                let result = store.with_store(|_| Ok(())).is_ok();
13937                let _ = sender.send(result);
13938            });
13939            match receiver.recv_timeout(Duration::from_secs(1)) {
13940                Ok(true) => Ok(()),
13941                _ => Err(HnsWalletError::Backend(
13942                    "backend was invoked while the shared store mutex was held".to_owned(),
13943                )),
13944            }
13945        }
13946
13947        fn unexpected(method: &str) -> HnsWalletError {
13948            HnsWalletError::Backend(format!(
13949                "unexpected backend method during native name import: {method}"
13950            ))
13951        }
13952    }
13953
13954    impl HnsBackend for NativeNameImportBackend {
13955        fn get_chain_snapshot(&self) -> Result<SnapshotBinding, HnsWalletError> {
13956            self.prove_store_mutex_is_released()?;
13957            self.snapshot_calls.fetch_add(1, Ordering::SeqCst);
13958            Ok(Self::binding())
13959        }
13960
13961        fn get_chain_tip(&self) -> Result<ChainTip, HnsWalletError> {
13962            Err(Self::unexpected("get_chain_tip"))
13963        }
13964
13965        fn get_block_hash(
13966            &self,
13967            height: u64,
13968            binding: SnapshotBinding,
13969        ) -> Result<BlockHashEvidence, HnsWalletError> {
13970            self.prove_store_mutex_is_released()?;
13971            if height != 0 || binding != Self::binding() {
13972                return Err(HnsWalletError::StaleNodeSnapshot);
13973            }
13974            Ok(BlockHashEvidence {
13975                binding,
13976                height,
13977                block_hash: Some(name_workflow::expected_chain_identity(self.network)?.1),
13978            })
13979        }
13980
13981        fn get_confirmed_wallet_page(
13982            &self,
13983            _: ConfirmedWalletPageRequest<'_>,
13984        ) -> Result<ConfirmedWalletPage, HnsWalletError> {
13985            Err(Self::unexpected("get_confirmed_wallet_page"))
13986        }
13987
13988        fn get_mempool_wallet_page(
13989            &self,
13990            _: MempoolWalletPageRequest<'_>,
13991        ) -> Result<MempoolWalletPage, HnsWalletError> {
13992            Err(Self::unexpected("get_mempool_wallet_page"))
13993        }
13994
13995        fn get_transaction_evidence(
13996            &self,
13997            _: TransactionHash,
13998            _: SnapshotBinding,
13999            _: Option<MempoolSnapshotBinding>,
14000        ) -> Result<TransactionEvidence, HnsWalletError> {
14001            Err(Self::unexpected("get_transaction_evidence"))
14002        }
14003
14004        fn get_outpoint_spend_evidence(
14005            &self,
14006            _: &[HnsOutpoint],
14007            _: SnapshotBinding,
14008        ) -> Result<OutpointSpendEvidence, HnsWalletError> {
14009            Err(Self::unexpected("get_outpoint_spend_evidence"))
14010        }
14011
14012        fn broadcast_transaction(&self, _: &[u8]) -> Result<TransactionHash, HnsWalletError> {
14013            Err(Self::unexpected("broadcast_transaction"))
14014        }
14015
14016        fn quote_transaction_fee(
14017            &self,
14018            _: &[u8],
14019            _: &[Coin],
14020            _: u16,
14021            _: SnapshotBinding,
14022            _: MempoolSnapshotBinding,
14023        ) -> Result<HnsTransactionFeeQuote, HnsWalletError> {
14024            Err(Self::unexpected("quote_transaction_fee"))
14025        }
14026
14027        fn estimate_fee_rate(&self, _: u16) -> Result<BaseUnits, HnsWalletError> {
14028            Err(Self::unexpected("estimate_fee_rate"))
14029        }
14030
14031        fn get_name_evidence(
14032            &self,
14033            name_hash: [u8; 32],
14034            binding: SnapshotBinding,
14035        ) -> Result<NameEvidence, HnsWalletError> {
14036            self.prove_store_mutex_is_released()?;
14037            self.evidence_calls.fetch_add(1, Ordering::SeqCst);
14038            let evidence = self
14039                .evidence
14040                .iter()
14041                .find(|evidence| evidence.proof.name_hash == name_hash)
14042                .ok_or(HnsWalletError::InvalidEvidence)?;
14043            if binding != Self::binding() {
14044                return Err(HnsWalletError::InvalidEvidence);
14045            }
14046            if self
14047                .mutate_account_on_evidence
14048                .swap(false, Ordering::SeqCst)
14049            {
14050                self.store
14051                    .with_store_mut(|store| {
14052                        let stored = store
14053                            .wallet_account::<HnsAccountRecord>(&self.account_id)?
14054                            .ok_or(StoreError::CorruptMetadata)?;
14055                        let mut changed = stored.value;
14056                        changed.next_receive_index = changed
14057                            .next_receive_index
14058                            .checked_add(1)
14059                            .ok_or(StoreError::RevisionOverflow)?;
14060                        store
14061                            .save_wallet_account(&self.account_id, stored.revision, &changed, 102)
14062                            .map(|_| ())
14063                    })
14064                    .map_err(HnsWalletError::from)?;
14065            }
14066            Ok(evidence.clone())
14067        }
14068
14069        fn get_name_action_context(
14070            &self,
14071            _: HnsNameAction,
14072            _: [u8; 32],
14073            _: SnapshotBinding,
14074            _: MempoolSnapshotBinding,
14075        ) -> Result<NameActionContextEvidence, HnsWalletError> {
14076            Err(Self::unexpected("get_name_action_context"))
14077        }
14078    }
14079
14080    #[derive(Clone, Copy)]
14081    struct ProductionFollowupClock;
14082
14083    impl HnsClock for ProductionFollowupClock {
14084        fn now_unix(&self) -> Result<u64, HnsWalletError> {
14085            Ok(100)
14086        }
14087    }
14088
14089    fn production_followup_read_store() -> (SharedWalletStore, HnsRuntimeConfig) {
14090        let mut config = test_runtime_config();
14091        config.birthday_height = 0;
14092        config.restore_lookahead = 1;
14093        config.minimum_confirmations = 1;
14094        let store = production_followup_read_store_for_config(config.clone());
14095        (store, config)
14096    }
14097
14098    fn production_followup_read_store_for_config(config: HnsRuntimeConfig) -> SharedWalletStore {
14099        let mut store = WalletStore::create(":memory:", PRODUCTION_FOLLOWUP_PASSPHRASE)
14100            .expect("create synchronized-read store");
14101        store
14102            .put_secret(
14103                config.wallet_id.as_bytes(),
14104                SecretKind::RecoverySeed,
14105                &[41; 64],
14106                1,
14107            )
14108            .expect("persist synchronized-read seed");
14109        let account = HnsAccountRecord {
14110            config: config.clone(),
14111            next_receive_index: 0,
14112            next_change_index: 0,
14113            next_shakedex_index: 0,
14114            external_scan_end: 0,
14115            internal_scan_end: 0,
14116            shakedex_scan_end: 0,
14117            shakedex_scan_complete: false,
14118            shakedex_scan_in_progress: false,
14119            last_used_external: None,
14120            last_used_internal: None,
14121            last_used_shakedex: None,
14122        };
14123        store
14124            .save_wallet_account(&account_entity_id(&config), 0, &account, 1)
14125            .expect("persist synchronized-read account");
14126        SharedWalletStore::new(store)
14127    }
14128
14129    fn production_followup_read_runtime(
14130        store: SharedWalletStore,
14131        config: HnsRuntimeConfig,
14132        fault: ProductionFollowupReadFault,
14133    ) -> HnsAccountReadRuntime<ProductionFollowupReadBackend, ProductionFollowupClock> {
14134        let selector = HnsExistingAccountSelector::new(store.clone(), config.clone())
14135            .expect("exact synchronized-read selector");
14136        HnsAccountReadRuntime::new(
14137            ProductionFollowupReadBackend::new(store.clone(), &config, fault),
14138            ProductionFollowupClock,
14139            store,
14140            selector,
14141        )
14142        .expect("synchronized account read runtime")
14143    }
14144
14145    #[test]
14146    fn full_runtime_retains_the_exact_shared_store_and_lock_authority() {
14147        let (store, config) = production_followup_read_store();
14148        let runtime = HnsWalletRuntime::open_shared(
14149            ProductionFollowupReadBackend::new(
14150                store.clone(),
14151                &config,
14152                ProductionFollowupReadFault::Healthy,
14153            ),
14154            store.clone(),
14155            config,
14156            ProductionFollowupClock,
14157        )
14158        .expect("open full runtime over shared authority");
14159
14160        assert!(runtime.shares_store_authority(&store));
14161        let (different_store, _) = production_followup_read_store();
14162        assert!(!runtime.shares_store_authority(&different_store));
14163
14164        store.lock().expect("lock shared authority");
14165        assert!(
14166            runtime
14167                .store_lock()
14168                .expect("locked runtime guard")
14169                .is_locked()
14170        );
14171        store
14172            .unlock(PRODUCTION_FOLLOWUP_PASSPHRASE)
14173            .expect("unlock shared authority");
14174        assert!(
14175            !runtime
14176                .store_lock()
14177                .expect("runtime observes shared unlock")
14178                .is_locked()
14179        );
14180    }
14181
14182    #[test]
14183    fn committed_change_updates_backend_after_releasing_store_authority() {
14184        let (store, config) = production_followup_read_store();
14185        let runtime = HnsWalletRuntime::open_shared(
14186            ProductionFollowupReadBackend::new(
14187                store.clone(),
14188                &config,
14189                ProductionFollowupReadFault::Healthy,
14190            ),
14191            store.clone(),
14192            config.clone(),
14193            ProductionFollowupClock,
14194        )
14195        .expect("open full runtime over shared authority");
14196        let mut next_account = store
14197            .try_with_store(|wallet| {
14198                wallet
14199                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))
14200                    .map_err(HnsWalletError::from)
14201            })
14202            .expect("read current account")
14203            .expect("current account exists")
14204            .value;
14205        next_account.next_change_index = 1;
14206        next_account.internal_scan_end = 1;
14207        let next_revision = store
14208            .with_store_mut(|wallet| {
14209                wallet.save_wallet_account(&account_entity_id(&config), 1, &next_account, 101)
14210            })
14211            .expect("commit local change allocation");
14212
14213        runtime
14214            .install_committed_account(1, next_revision, next_account.clone(), 101)
14215            .expect("install committed change without holding the store mutex");
14216
14217        assert_eq!(runtime.backend.change_watch_calls.load(Ordering::SeqCst), 1);
14218        let cache = runtime.cache_read().expect("read updated runtime cache");
14219        assert_eq!(cache.account_revision, next_revision);
14220        assert_eq!(cache.account, next_account);
14221    }
14222
14223    #[test]
14224    fn committed_change_cache_advances_when_watch_extension_requires_recovery() {
14225        let (store, config) = production_followup_read_store();
14226        let runtime = HnsWalletRuntime::open_shared(
14227            ProductionFollowupReadBackend::new(
14228                store.clone(),
14229                &config,
14230                ProductionFollowupReadFault::Healthy,
14231            ),
14232            store.clone(),
14233            config.clone(),
14234            ProductionFollowupClock,
14235        )
14236        .expect("open full runtime over shared authority");
14237        runtime
14238            .backend
14239            .change_watch_fails
14240            .store(true, Ordering::SeqCst);
14241        let mut next_account = store
14242            .try_with_store(|wallet| {
14243                wallet
14244                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))
14245                    .map_err(HnsWalletError::from)
14246            })
14247            .expect("read current account")
14248            .expect("current account exists")
14249            .value;
14250        next_account.next_change_index = 1;
14251        next_account.internal_scan_end = 1;
14252        let next_revision = store
14253            .with_store_mut(|wallet| {
14254                wallet.save_wallet_account(&account_entity_id(&config), 1, &next_account, 101)
14255            })
14256            .expect("commit local change allocation");
14257
14258        assert!(matches!(
14259            runtime.install_committed_account(1, next_revision, next_account.clone(), 101),
14260            Err(HnsWalletError::Backend(_))
14261        ));
14262        assert_eq!(runtime.backend.change_watch_calls.load(Ordering::SeqCst), 1);
14263        let cache = runtime.cache_read().expect("read recovered runtime cache");
14264        assert_eq!(cache.account_revision, next_revision);
14265        assert_eq!(cache.account, next_account);
14266    }
14267
14268    fn zero_value_incoming_candidate(recipient: &DerivedHnsAddress) -> IncomingTransferCandidate {
14269        zero_value_incoming_candidate_at(recipient, 0)
14270    }
14271
14272    fn zero_value_incoming_candidate_at(
14273        recipient: &DerivedHnsAddress,
14274        candidate_index: u32,
14275    ) -> IncomingTransferCandidate {
14276        let name = format!("alpha{candidate_index}");
14277        let name_hash = hash_name(name.as_bytes()).expect("incoming name hash");
14278        let covenant =
14279            TransferCovenant::new(name_hash, Height::new(0), 0, recipient.program.clone())
14280                .expect("incoming TRANSFER")
14281                .to_covenant()
14282                .expect("incoming TRANSFER covenant");
14283        IncomingTransferCandidate {
14284            script_index: 0,
14285            recipient: WalletAddressKey {
14286                version: 0,
14287                hash: recipient.program.clone(),
14288            },
14289            name_hash: name_hash.into_bytes(),
14290            start_height: 0,
14291            transfer_coin: Coin {
14292                outpoint: CanonicalOutpoint {
14293                    transaction_hash: CanonicalTransactionHash::new({
14294                        let mut transaction = [0x91; 32];
14295                        transaction[..4].copy_from_slice(&candidate_index.to_le_bytes());
14296                        transaction
14297                    }),
14298                    index: 0,
14299                },
14300                value: Dollarydoos::new(0),
14301                height: Height::new(1),
14302                coinbase: false,
14303                address: Address::new(0, vec![0x92; 20]).expect("old-owner address"),
14304                covenant,
14305            },
14306            inclusion: TransactionInclusion {
14307                block_hash: ProductionFollowupReadBackend::binding().tip.block_hash,
14308                height: 1,
14309                transaction_index: Some(0),
14310            },
14311            source_output_count: 1,
14312            source_binding: IncomingTransferSourceBinding::PrunedTrustedNodeProjection,
14313        }
14314    }
14315
14316    fn zero_value_finalize_owner(
14317        recipient: &DerivedHnsAddress,
14318    ) -> ([u8; 32], Coin, ActiveNameOwnerCoinEvidence) {
14319        let name = b"alpha".to_vec();
14320        let name_hash = hash_name(&name).expect("FINALIZE name hash");
14321        let outpoint = CanonicalOutpoint {
14322            transaction_hash: CanonicalTransactionHash::new([0xa1; 32]),
14323            index: 0,
14324        };
14325        let covenant = FinalizeCovenant::new(
14326            name.clone(),
14327            Height::new(0),
14328            false,
14329            Height::new(0),
14330            0,
14331            BlockHash::new([0xa2; 32]),
14332        )
14333        .expect("zero-value FINALIZE")
14334        .to_covenant()
14335        .expect("zero-value FINALIZE covenant");
14336        let coin = Coin {
14337            outpoint,
14338            value: Dollarydoos::new(0),
14339            height: Height::new(1),
14340            coinbase: false,
14341            address: Address::new(0, recipient.program.clone()).expect("name address"),
14342            covenant,
14343        };
14344        let mut state = NameState::null(name_hash);
14345        state.name = name;
14346        state.height = Height::new(0);
14347        state.renewal = Height::new(1);
14348        state.owner = outpoint;
14349        state.value = Dollarydoos::new(0);
14350        state.highest = Dollarydoos::new(0);
14351        state.renewals = 1;
14352        state.registered = true;
14353        let binding = ProductionFollowupReadBackend::binding();
14354        let evidence = ActiveNameOwnerCoinEvidence {
14355            projection_version: 1,
14356            binding,
14357            current_state: state.encode().expect("zero-value current NameState"),
14358            owner_coin: coin.clone(),
14359            inclusion: TransactionInclusion {
14360                block_hash: binding.tip.block_hash,
14361                height: 1,
14362                transaction_index: None,
14363            },
14364            source_binding: ActiveNameOwnerCoinSourceBinding::TrustedNodeActiveUtxoProjection,
14365        };
14366        (name_hash.into_bytes(), coin, evidence)
14367    }
14368
14369    fn production_followup_recovery_read_runtime(
14370        store: SharedWalletStore,
14371        config: HnsRuntimeConfig,
14372        fault: ProductionFollowupReadFault,
14373    ) -> HnsPersistedRecoveryReadOnlyRuntime<ProductionFollowupReadBackend, ProductionFollowupClock>
14374    {
14375        HnsPersistedRecoveryReadOnlyRuntime::new(
14376            ProductionFollowupReadBackend::new(store.clone(), &config, fault),
14377            ProductionFollowupClock,
14378            store,
14379            config,
14380        )
14381        .expect("persisted recovery-only read runtime")
14382    }
14383
14384    fn canonical_name_view(
14385        owner_program: Vec<u8>,
14386        resource_data: Vec<u8>,
14387        transfer_recipient: Option<Address>,
14388    ) -> (Vec<u8>, NameState, Transaction, HnsOutpoint) {
14389        let name = b"alpha".to_vec();
14390        let name_hash = hash_name(&name).expect("name hash");
14391        let mut state = NameState {
14392            name_hash,
14393            name: name.clone(),
14394            height: Height::new(100),
14395            renewal: Height::new(120),
14396            owner: CanonicalOutpoint::NULL,
14397            value: Dollarydoos::new(50_000),
14398            highest: Dollarydoos::new(60_000),
14399            resource_data,
14400            transfer: Height::new(if transfer_recipient.is_some() { 400 } else { 0 }),
14401            revoked: Height::new(0),
14402            claimed: Height::new(0),
14403            renewals: 1,
14404            registered: true,
14405            expired: false,
14406            weak: false,
14407        };
14408        let covenant = match transfer_recipient {
14409            Some(recipient) => {
14410                TransferCovenant::new(name_hash, state.height, recipient.version, recipient.hash)
14411                    .expect("transfer")
14412                    .to_covenant()
14413                    .expect("transfer covenant")
14414            }
14415            None => {
14416                // FINALIZE commits the pre-finalization renewal count. Applying
14417                // it advances the canonical NameState count by one.
14418                let mut pre_finalize = state.clone();
14419                pre_finalize.renewals = state
14420                    .renewals
14421                    .checked_sub(1)
14422                    .expect("post-finalize renewal count");
14423                FinalizeCovenant::from_name_state(&pre_finalize, BlockHash::new([9; 32]))
14424                    .expect("finalize")
14425                    .to_covenant()
14426                    .expect("finalize covenant")
14427            }
14428        };
14429        let transaction = Transaction {
14430            version: 0,
14431            inputs: Vec::new(),
14432            outputs: vec![Output {
14433                value: state.value,
14434                address: Address::new(0, owner_program).expect("owner address"),
14435                covenant,
14436            }],
14437            locktime: 0,
14438        };
14439        let transaction_hash = transaction.transaction_hash().expect("transaction hash");
14440        state.owner = CanonicalOutpoint {
14441            transaction_hash,
14442            index: 0,
14443        };
14444        let outpoint = HnsOutpoint {
14445            transaction: TransactionHash::new(transaction_hash.into_bytes()),
14446            output_index: 0,
14447        };
14448        (name, state, transaction, outpoint)
14449    }
14450
14451    fn native_import_evidence(
14452        name: &[u8],
14453        current: Option<(NameState, Transaction, HnsOutpoint)>,
14454    ) -> NameEvidence {
14455        let binding = NativeNameImportBackend::binding();
14456        let name_hash = hash_name(name).expect("import name hash").into_bytes();
14457        let (current_state, current_owner_outpoint, current_owner_transaction, current_inclusion) =
14458            current.map_or(
14459                (None, None, None, None),
14460                |(state, transaction, outpoint)| {
14461                    let height = u64::from(state.transfer.get().max(1));
14462                    (
14463                        Some(state.encode().expect("current name state")),
14464                        Some(outpoint),
14465                        Some(transaction.encode().expect("current owner transaction")),
14466                        Some(TransactionInclusion {
14467                            block_hash: [82; 32],
14468                            height,
14469                            transaction_index: Some(0),
14470                        }),
14471                    )
14472                },
14473            );
14474        let current_resource = current_state.as_ref().map(|raw| {
14475            NameState::decode(NameHash::new(name_hash), raw)
14476                .expect("decode current import state")
14477                .resource_data
14478        });
14479        NameEvidence {
14480            binding,
14481            proof: NameProofResponse {
14482                name_hash,
14483                tree_root: binding.tip.tree_root,
14484                proof: vec![0, 0, 0, 0],
14485                proof_height: binding.tip.height,
14486            },
14487            proof_state: None,
14488            proof_owner_outpoint: None,
14489            proof_owner_transaction: None,
14490            proof_owner_inclusion: None,
14491            current_state,
14492            current_owner_outpoint,
14493            current_owner_transaction,
14494            current_owner_inclusion: current_inclusion,
14495            untrusted_current_raw_resource: current_resource,
14496        }
14497    }
14498
14499    fn native_import_store() -> (SharedWalletStore, HnsRuntimeConfig, DerivedHnsAddress) {
14500        let (store, config) = production_followup_read_store();
14501        let address = store
14502            .try_with_store_mut(|wallet| {
14503                let account = wallet
14504                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))?
14505                    .ok_or(HnsWalletError::StaleAccountRead)?
14506                    .value;
14507                let addresses = derive_restore_addresses(wallet, &account, KeyRole::HnsCoin)?;
14508                persist_derived_addresses(wallet, &config, &addresses, 2)?;
14509                addresses
14510                    .into_iter()
14511                    .find(|address| address.derivation.change == 0)
14512                    .ok_or(HnsWalletError::InvalidEvidence)
14513            })
14514            .expect("prepare exact name derivation evidence");
14515        (store, config, address)
14516    }
14517
14518    fn native_import_runtime(
14519        store: SharedWalletStore,
14520        config: HnsRuntimeConfig,
14521        evidence: NameEvidence,
14522        stale_account: bool,
14523    ) -> HnsAccountReadRuntime<NativeNameImportBackend, ProductionFollowupClock> {
14524        let selector = HnsExistingAccountSelector::new(store.clone(), config.clone())
14525            .expect("native import selector");
14526        let backend = NativeNameImportBackend::new(store.clone(), &config, evidence);
14527        let backend = if stale_account {
14528            backend.with_stale_account_mutation()
14529        } else {
14530            backend
14531        };
14532        HnsAccountReadRuntime::new(backend, ProductionFollowupClock, store, selector)
14533            .expect("native import runtime")
14534    }
14535
14536    fn native_import_bulk_runtime(
14537        store: SharedWalletStore,
14538        config: HnsRuntimeConfig,
14539        evidence: &[NameEvidence],
14540    ) -> HnsAccountReadRuntime<NativeNameImportBackend, ProductionFollowupClock> {
14541        let selector = HnsExistingAccountSelector::new(store.clone(), config.clone())
14542            .expect("native bulk import selector");
14543        let first = evidence.first().expect("nonempty bulk evidence").clone();
14544        let backend = evidence.iter().skip(1).cloned().fold(
14545            NativeNameImportBackend::new(store.clone(), &config, first),
14546            NativeNameImportBackend::with_evidence,
14547        );
14548        HnsAccountReadRuntime::new(backend, ProductionFollowupClock, store, selector)
14549            .expect("native bulk import runtime")
14550    }
14551
14552    fn validate_test_name_view(
14553        name: &[u8],
14554        state: &NameState,
14555        transaction: &Transaction,
14556        outpoint: HnsOutpoint,
14557    ) -> Result<ValidatedCanonicalNameState, HnsWalletError> {
14558        let raw_state = state.encode().expect("name state");
14559        let raw_transaction = transaction.encode().expect("owner transaction");
14560        let inclusion_height = u64::from(state.transfer.get().max(1));
14561        validate_canonical_name_state(
14562            name,
14563            state.name_hash.into_bytes(),
14564            Some(&raw_state),
14565            Some(outpoint),
14566            Some(&raw_transaction),
14567            Some(TransactionInclusion {
14568                block_hash: [24; 32],
14569                height: inclusion_height,
14570                transaction_index: Some(0),
14571            }),
14572        )?
14573        .ok_or(HnsWalletError::InvalidEvidence)
14574    }
14575
14576    #[test]
14577    fn canonical_hns_v2_binds_owner_resource_and_account_zero_key() {
14578        assert_eq!(
14579            classify_name_ownership(None, None).expect("context-free classification"),
14580            NameOwnershipStatus::WalletContextUnavailable
14581        );
14582        let address = test_derived_address(KeyRole::HnsCoin, 31);
14583        let (name, state, transaction, outpoint) =
14584            canonical_name_view(address.program.clone(), vec![1], None);
14585        let current =
14586            validate_test_name_view(&name, &state, &transaction, outpoint).expect("canonical view");
14587        assert_eq!(current.summary.owner_outpoint, Some(outpoint));
14588        assert_eq!(current.summary.value, 50_000);
14589        assert_eq!(
14590            classify_name_ownership(Some(&current), Some(std::slice::from_ref(&address)))
14591                .expect("ownership"),
14592            NameOwnershipStatus::WalletOwned {
14593                derivation: address.derivation
14594            }
14595        );
14596        let (resource, status) =
14597            bind_current_name_resource(Some(&current), Some(vec![1])).expect("canonical resource");
14598        assert_eq!(resource, Some(vec![1]));
14599        assert_eq!(status, NameResourceStatus::CanonicalOpaque);
14600
14601        let coin_role = test_derived_address(KeyRole::HnsCoin, 32);
14602        validate_wallet_name_addresses(std::slice::from_ref(&coin_role))
14603            .expect("ordinary external receive keys remain name-recovery authorities");
14604        assert_eq!(
14605            classify_name_ownership(Some(&current), Some(std::slice::from_ref(&coin_role)))
14606                .expect("ordinary receive ownership"),
14607            NameOwnershipStatus::NotWalletOwned,
14608        );
14609        let (_, coin_state, coin_transaction, coin_outpoint) =
14610            canonical_name_view(coin_role.program.clone(), vec![1], None);
14611        let coin_current =
14612            validate_test_name_view(&name, &coin_state, &coin_transaction, coin_outpoint)
14613                .expect("ordinary receive canonical view");
14614        assert_eq!(
14615            classify_name_ownership(Some(&coin_current), Some(std::slice::from_ref(&coin_role)),)
14616                .expect("ordinary receive name ownership"),
14617            NameOwnershipStatus::WalletOwned {
14618                derivation: coin_role.derivation,
14619            },
14620        );
14621    }
14622
14623    #[test]
14624    fn native_exact_text_name_import_rejects_before_every_backend_call() {
14625        let (store, config, _) = native_import_store();
14626        let evidence = native_import_evidence(b"alpha", None);
14627        let runtime = native_import_runtime(store.clone(), config.clone(), evidence, false);
14628        for invalid in [
14629            "",
14630            " alpha",
14631            "alpha ",
14632            "ALPHA",
14633            "alpha.",
14634            "alpha.beta",
14635            "alph\u{00e1}",
14636            "alpha\n",
14637        ] {
14638            assert!(matches!(
14639                runtime.import_name_exact_text(invalid),
14640                Err(HnsWalletError::InvalidName)
14641            ));
14642        }
14643        assert_eq!(runtime.backend.snapshot_calls.load(Ordering::SeqCst), 0);
14644        assert_eq!(runtime.backend.evidence_calls.load(Ordering::SeqCst), 0);
14645        assert!(
14646            store
14647                .with_store(|wallet| wallet.list_entities_by_id_prefix::<KnownName>(
14648                    EntityKind::KnownName,
14649                    &account_entity_prefix(&config),
14650                    MAX_HISTORY_RESULTS,
14651                ))
14652                .expect("unchanged name store")
14653                .is_empty()
14654        );
14655    }
14656
14657    #[test]
14658    fn native_name_import_rejects_same_id_with_different_exact_text_before_backend() {
14659        let (store, config, _) = native_import_store();
14660        let alpha_hash = hash_name(b"alpha").expect("alpha hash").into_bytes();
14661        let corrupt = KnownName {
14662            name: b"beta".to_vec(),
14663            name_hash: alpha_hash,
14664            proof_height: 1,
14665            unbound_proof_owner_outpoint: None,
14666            unbound_current_owner_outpoint: None,
14667            proof_state: None,
14668            current_state: None,
14669            canonical_proof_state: None,
14670            canonical_current_state: None,
14671            current_raw_resource: None,
14672            resource_status: NameResourceStatus::NoCurrentState,
14673            ownership_status: NameOwnershipStatus::NoCurrentOwner,
14674        };
14675        store
14676            .with_store_mut(|wallet| {
14677                wallet
14678                    .save_known_name(&namespaced_name_id(&config, alpha_hash), 0, &corrupt, 3)
14679                    .map(|_| ())
14680            })
14681            .expect("inject authenticated corrupt hash/text row");
14682        let evidence = native_import_evidence(b"alpha", None);
14683        let runtime = native_import_runtime(store, config, evidence, false);
14684        assert!(matches!(
14685            runtime.import_name_exact_text("alpha"),
14686            Err(HnsWalletError::InvalidEvidence)
14687        ));
14688        assert_eq!(runtime.backend.snapshot_calls.load(Ordering::SeqCst), 0);
14689        assert_eq!(runtime.backend.evidence_calls.load(Ordering::SeqCst), 0);
14690    }
14691
14692    #[test]
14693    fn native_bulk_name_import_authenticates_all_before_one_atomic_commit() {
14694        let (store, config, _) = native_import_store();
14695        let alpha = native_import_evidence(b"alpha", None);
14696        let beta = native_import_evidence(b"beta", None);
14697        let runtime =
14698            native_import_bulk_runtime(store.clone(), config.clone(), std::slice::from_ref(&alpha));
14699        assert!(matches!(
14700            runtime.import_names_exact_text_bounded(&["alpha", "beta"], MAX_HISTORY_RESULTS),
14701            Err(HnsWalletError::InvalidEvidence)
14702        ));
14703        assert!(
14704            store
14705                .with_store(|wallet| wallet.list_entities_by_id_prefix::<KnownName>(
14706                    EntityKind::KnownName,
14707                    &account_entity_prefix(&config),
14708                    MAX_HISTORY_RESULTS,
14709                ))
14710                .expect("failed bulk import leaves no prefix")
14711                .is_empty()
14712        );
14713
14714        let runtime = native_import_bulk_runtime(store.clone(), config.clone(), &[alpha, beta]);
14715        let imported = runtime
14716            .import_names_exact_text_bounded(&["alpha", "beta"], MAX_HISTORY_RESULTS)
14717            .expect("authenticated bulk import");
14718        assert_eq!(
14719            imported
14720                .iter()
14721                .map(|name| name.name.as_slice())
14722                .collect::<Vec<_>>(),
14723            vec![b"alpha".as_slice(), b"beta".as_slice()]
14724        );
14725        assert_eq!(
14726            store
14727                .with_store(|wallet| wallet.list_entities_by_id_prefix::<KnownName>(
14728                    EntityKind::KnownName,
14729                    &account_entity_prefix(&config),
14730                    MAX_HISTORY_RESULTS,
14731                ))
14732                .expect("atomic bulk rows")
14733                .len(),
14734            2
14735        );
14736    }
14737
14738    #[test]
14739    fn native_name_import_rotates_only_exact_wallet_ownership_classes() {
14740        #[derive(Clone, Copy)]
14741        enum ImportClass {
14742            WalletOwned,
14743            IncomingTransfer,
14744            OutgoingTransfer,
14745            NotWalletOwned,
14746            NoCurrentOwner,
14747        }
14748
14749        for class in [
14750            ImportClass::WalletOwned,
14751            ImportClass::IncomingTransfer,
14752            ImportClass::OutgoingTransfer,
14753            ImportClass::NotWalletOwned,
14754            ImportClass::NoCurrentOwner,
14755        ] {
14756            let (store, config, address) = native_import_store();
14757            let current = match class {
14758                ImportClass::WalletOwned => {
14759                    let (_, state, transaction, outpoint) =
14760                        canonical_name_view(address.program.clone(), Vec::new(), None);
14761                    Some((state, transaction, outpoint))
14762                }
14763                ImportClass::IncomingTransfer => {
14764                    let recipient =
14765                        Address::new(0, address.program.clone()).expect("wallet recipient");
14766                    let (_, state, transaction, outpoint) =
14767                        canonical_name_view(vec![91; 20], Vec::new(), Some(recipient));
14768                    Some((state, transaction, outpoint))
14769                }
14770                ImportClass::OutgoingTransfer => {
14771                    let recipient = Address::new(0, vec![92; 20]).expect("external recipient");
14772                    let (_, state, transaction, outpoint) =
14773                        canonical_name_view(address.program.clone(), Vec::new(), Some(recipient));
14774                    Some((state, transaction, outpoint))
14775                }
14776                ImportClass::NotWalletOwned => {
14777                    let (_, state, transaction, outpoint) =
14778                        canonical_name_view(vec![93; 20], Vec::new(), None);
14779                    Some((state, transaction, outpoint))
14780                }
14781                ImportClass::NoCurrentOwner => None,
14782            };
14783            let evidence = native_import_evidence(b"alpha", current);
14784            let runtime = native_import_runtime(store.clone(), config.clone(), evidence, false);
14785            let imported = runtime
14786                .import_name_exact_text("alpha")
14787                .expect("exact native name import");
14788            match class {
14789                ImportClass::WalletOwned => assert!(matches!(
14790                    imported.ownership_status,
14791                    NameOwnershipStatus::WalletOwned { derivation }
14792                        if derivation == address.derivation
14793                )),
14794                ImportClass::IncomingTransfer => assert!(matches!(
14795                    imported.ownership_status,
14796                    NameOwnershipStatus::IncomingTransfer {
14797                        recipient_derivation,
14798                        ..
14799                    } if recipient_derivation == address.derivation
14800                )),
14801                ImportClass::OutgoingTransfer => assert!(matches!(
14802                    imported.ownership_status,
14803                    NameOwnershipStatus::OutgoingTransfer {
14804                        owner_derivation,
14805                        ..
14806                    } if owner_derivation == address.derivation
14807                )),
14808                ImportClass::NotWalletOwned => assert_eq!(
14809                    imported.ownership_status,
14810                    NameOwnershipStatus::NotWalletOwned
14811                ),
14812                ImportClass::NoCurrentOwner => assert_eq!(
14813                    imported.ownership_status,
14814                    NameOwnershipStatus::NoCurrentOwner
14815                ),
14816            }
14817            let wallet_bearing = matches!(
14818                class,
14819                ImportClass::WalletOwned
14820                    | ImportClass::IncomingTransfer
14821                    | ImportClass::OutgoingTransfer
14822            );
14823            store
14824                .with_store(|wallet| {
14825                    let account = wallet
14826                        .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))?
14827                        .ok_or(StoreError::CorruptMetadata)?;
14828                    assert_eq!(
14829                        account.value.last_used_external,
14830                        wallet_bearing.then_some(0)
14831                    );
14832                    assert_eq!(account.value.next_receive_index, u32::from(wallet_bearing));
14833                    assert_eq!(account.value.external_scan_end, u32::from(wallet_bearing));
14834                    let stored = wallet
14835                        .known_name::<KnownName>(&namespaced_name_id(&config, imported.name_hash))?
14836                        .ok_or(StoreError::CorruptMetadata)?;
14837                    assert_eq!(stored.value, imported);
14838                    Ok(())
14839                })
14840                .expect("atomic account and name import");
14841        }
14842    }
14843
14844    #[test]
14845    fn native_name_import_stale_account_cannot_partially_persist_or_rotate() {
14846        let (store, config, address) = native_import_store();
14847        let (_, state, transaction, outpoint) =
14848            canonical_name_view(address.program, Vec::new(), None);
14849        let evidence = native_import_evidence(b"alpha", Some((state, transaction, outpoint)));
14850        let runtime = native_import_runtime(store.clone(), config.clone(), evidence, true);
14851        assert!(matches!(
14852            runtime.import_name_exact_text("alpha"),
14853            Err(HnsWalletError::StaleAccountRead)
14854        ));
14855        store
14856            .with_store(|wallet| {
14857                let account = wallet
14858                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))?
14859                    .ok_or(StoreError::CorruptMetadata)?;
14860                assert_eq!(account.value.next_receive_index, 1);
14861                assert_eq!(account.value.last_used_external, None);
14862                assert_eq!(account.value.next_receive_index, 1);
14863                assert_eq!(account.value.external_scan_end, 0);
14864                assert!(
14865                    wallet
14866                        .known_name::<KnownName>(&namespaced_name_id(
14867                            &config,
14868                            hash_name(b"alpha").expect("hash").into_bytes(),
14869                        ))?
14870                        .is_none()
14871                );
14872                Ok(())
14873            })
14874            .expect("no partial name mutation");
14875    }
14876
14877    #[test]
14878    fn native_name_import_tracks_authenticated_owner_without_historical_transaction() {
14879        let (store, config, _) = native_import_store();
14880        let (_, state, transaction, outpoint) =
14881            canonical_name_view(vec![93; 20], vec![7, 8, 9], None);
14882        let mut evidence = native_import_evidence(b"alpha", Some((state, transaction, outpoint)));
14883        evidence.current_owner_transaction = None;
14884        evidence.current_owner_inclusion = None;
14885        let runtime = native_import_runtime(store, config, evidence, false);
14886
14887        let imported = runtime
14888            .import_name_exact_text("alpha")
14889            .expect("watch-only import with authenticated owner outpoint");
14890        assert_eq!(
14891            imported.ownership_status,
14892            NameOwnershipStatus::WatchOnlyOwnerTransactionUnavailable
14893        );
14894        assert_eq!(imported.unbound_current_owner_outpoint, Some(outpoint));
14895        assert_eq!(
14896            imported.current_raw_resource.as_deref(),
14897            Some(&[7, 8, 9][..])
14898        );
14899        assert!(imported.canonical_current_state.is_some());
14900    }
14901
14902    #[test]
14903    fn native_name_import_is_bounded_idempotent_and_monotonic_after_restart() {
14904        let (store, config, address) = native_import_store();
14905        let (_, state, transaction, outpoint) =
14906            canonical_name_view(address.program, Vec::new(), None);
14907        let owned = native_import_evidence(b"alpha", Some((state, transaction, outpoint)));
14908        let runtime = native_import_runtime(store.clone(), config.clone(), owned, false);
14909        let first = runtime
14910            .import_name_exact_text_bounded("alpha", 1)
14911            .expect("initial bounded import");
14912        drop(runtime);
14913
14914        let beta = native_import_evidence(b"beta", None);
14915        let bounded = native_import_runtime(store.clone(), config.clone(), beta, false);
14916        assert!(matches!(
14917            bounded.import_name_exact_text_bounded("beta", 1),
14918            Err(HnsWalletError::HistoryLimit)
14919        ));
14920        assert_eq!(bounded.backend.snapshot_calls.load(Ordering::SeqCst), 0);
14921        assert_eq!(bounded.backend.evidence_calls.load(Ordering::SeqCst), 0);
14922        drop(bounded);
14923
14924        let reused = native_import_evidence(b"alpha", None);
14925        let restarted = native_import_runtime(store.clone(), config.clone(), reused, false);
14926        let second = restarted
14927            .import_name_exact_text_bounded("alpha", 1)
14928            .expect("idempotent import at the bound after restart");
14929        assert_eq!(second.name, first.name);
14930        assert_eq!(second.name_hash, first.name_hash);
14931        assert_eq!(second.ownership_status, NameOwnershipStatus::NoCurrentOwner);
14932        store
14933            .with_store(|wallet| {
14934                let account = wallet
14935                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))?
14936                    .ok_or(StoreError::CorruptMetadata)?;
14937                assert_eq!(account.value.last_used_external, Some(0));
14938                assert_eq!(account.value.next_receive_index, 1);
14939                assert_eq!(account.value.external_scan_end, 1);
14940                assert_eq!(
14941                    wallet
14942                        .list_entities_by_id_prefix::<KnownName>(
14943                            EntityKind::KnownName,
14944                            &account_entity_prefix(&config),
14945                            MAX_HISTORY_RESULTS,
14946                        )?
14947                        .len(),
14948                    1
14949                );
14950                Ok(())
14951            })
14952            .expect("monotonic idempotent import state");
14953    }
14954
14955    #[test]
14956    fn canonical_hns_v2_rejects_owner_value_covenant_and_resource_mismatch() {
14957        let address = test_derived_address(KeyRole::HnsCoin, 32);
14958        let (name, state, transaction, outpoint) =
14959            canonical_name_view(address.program.clone(), Vec::new(), None);
14960        let raw_state = state.encode().expect("state");
14961        let raw_transaction = transaction.encode().expect("transaction");
14962        let wrong_outpoint = HnsOutpoint {
14963            output_index: 1,
14964            ..outpoint
14965        };
14966        assert!(
14967            validate_canonical_name_state(
14968                &name,
14969                state.name_hash.into_bytes(),
14970                Some(&raw_state),
14971                Some(wrong_outpoint),
14972                Some(&raw_transaction),
14973                Some(TransactionInclusion {
14974                    block_hash: [24; 32],
14975                    height: 1,
14976                    transaction_index: Some(0),
14977                }),
14978            )
14979            .is_err()
14980        );
14981
14982        let mut wrong_value_transaction = transaction.clone();
14983        wrong_value_transaction.outputs[0].value = Dollarydoos::new(state.value.get() + 1);
14984        let wrong_value_hash = wrong_value_transaction
14985            .transaction_hash()
14986            .expect("wrong-value hash");
14987        let mut wrong_value_state = state.clone();
14988        wrong_value_state.owner.transaction_hash = wrong_value_hash;
14989        assert!(
14990            validate_test_name_view(
14991                &name,
14992                &wrong_value_state,
14993                &wrong_value_transaction,
14994                HnsOutpoint {
14995                    transaction: TransactionHash::new(wrong_value_hash.into_bytes()),
14996                    output_index: 0,
14997                },
14998            )
14999            .is_err()
15000        );
15001
15002        let mut wrong_covenant_transaction = transaction;
15003        wrong_covenant_transaction.outputs[0].covenant.items[0] = vec![7; 32];
15004        let wrong_covenant_hash = wrong_covenant_transaction
15005            .transaction_hash()
15006            .expect("wrong-covenant hash");
15007        let mut wrong_covenant_state = state;
15008        wrong_covenant_state.owner.transaction_hash = wrong_covenant_hash;
15009        assert!(
15010            validate_test_name_view(
15011                &name,
15012                &wrong_covenant_state,
15013                &wrong_covenant_transaction,
15014                HnsOutpoint {
15015                    transaction: TransactionHash::new(wrong_covenant_hash.into_bytes()),
15016                    output_index: 0,
15017                },
15018            )
15019            .is_err()
15020        );
15021
15022        let (name, state, transaction, outpoint) =
15023            canonical_name_view(address.program, vec![1], None);
15024        let current =
15025            validate_test_name_view(&name, &state, &transaction, outpoint).expect("canonical view");
15026        assert!(bind_current_name_resource(Some(&current), Some(vec![2])).is_err());
15027    }
15028
15029    #[test]
15030    fn canonical_hns_v2_classifies_incoming_and_outgoing_transfers() {
15031        let owner = test_derived_address(KeyRole::HnsCoin, 41);
15032        let recipient = test_derived_address(KeyRole::HnsCoin, 42);
15033        let recipient_address = Address::new(0, recipient.program.clone()).expect("recipient");
15034        let (name, state, transaction, outpoint) =
15035            canonical_name_view(owner.program.clone(), Vec::new(), Some(recipient_address));
15036        let current =
15037            validate_test_name_view(&name, &state, &transaction, outpoint).expect("transfer view");
15038        assert_eq!(
15039            classify_name_ownership(Some(&current), Some(std::slice::from_ref(&owner)))
15040                .expect("outgoing"),
15041            NameOwnershipStatus::OutgoingTransfer {
15042                owner_derivation: owner.derivation,
15043                recipient: WalletAddressKey {
15044                    version: 0,
15045                    hash: recipient.program.clone(),
15046                },
15047            }
15048        );
15049        assert_eq!(
15050            classify_name_ownership(Some(&current), Some(std::slice::from_ref(&recipient)))
15051                .expect("incoming"),
15052            NameOwnershipStatus::IncomingTransfer {
15053                recipient_derivation: recipient.derivation,
15054                current_owner: WalletAddressKey {
15055                    version: 0,
15056                    hash: owner.program,
15057                },
15058            }
15059        );
15060    }
15061
15062    #[test]
15063    fn canonical_hns_v2_legacy_cache_requires_fresh_revalidation() {
15064        let legacy = KnownName {
15065            name: b"alpha".to_vec(),
15066            name_hash: [1; 32],
15067            proof_height: 10,
15068            unbound_proof_owner_outpoint: None,
15069            unbound_current_owner_outpoint: None,
15070            proof_state: None,
15071            current_state: None,
15072            canonical_proof_state: None,
15073            canonical_current_state: None,
15074            current_raw_resource: None,
15075            resource_status: NameResourceStatus::UnavailableCanonicalBinding,
15076            ownership_status: NameOwnershipStatus::WatchOnlyCanonicalStateDecoderUnavailable,
15077        };
15078        let mut encoded = serde_json::to_value(legacy).expect("legacy cache");
15079        let object = encoded.as_object_mut().expect("known name object");
15080        object.remove("canonical_proof_state");
15081        object.remove("canonical_current_state");
15082        object.remove("current_raw_resource");
15083        let decoded: KnownName = serde_json::from_value(encoded).expect("legacy decode");
15084        assert_eq!(decoded.canonical_proof_state, None);
15085        assert_eq!(decoded.canonical_current_state, None);
15086        assert_eq!(decoded.current_raw_resource, None);
15087        assert_eq!(
15088            decoded.ownership_status,
15089            NameOwnershipStatus::WatchOnlyCanonicalStateDecoderUnavailable
15090        );
15091    }
15092
15093    #[test]
15094    fn canonical_hns_v2_persisted_queries_are_complete_and_account_scoped() {
15095        assert_eq!(
15096            MAX_RESTORE_SCRIPTS_PER_QUERY,
15097            hns_wallet_store::MAX_ENTITY_LIST_RESULTS
15098        );
15099        let mut store = WalletStore::create(":memory:", "passphrase").expect("store");
15100        let config = test_runtime_config();
15101        let mut other_config = config.clone();
15102        other_config.account_id = AccountId::new([13; 16]);
15103        other_config.account_derivation_index = 8;
15104        let address = |config: &HnsRuntimeConfig, role, index, program| DerivedHnsAddress {
15105            account_id: config.account_id,
15106            derivation: DerivationReference {
15107                role,
15108                account: config.account_derivation_index,
15109                change: 0,
15110                index,
15111            },
15112            address: format!("test-address-{program}"),
15113            program: vec![program; 20],
15114            used: false,
15115        };
15116        let coin = address(&config, KeyRole::HnsCoin, 1, 21);
15117        let second_coin = address(&config, KeyRole::HnsCoin, 2, 22);
15118        let other_coin = address(&other_config, KeyRole::HnsCoin, 3, 23);
15119        for (owner, value) in [
15120            (&config, coin),
15121            (&config, second_coin.clone()),
15122            (&other_config, other_coin),
15123        ] {
15124            let id = derived_address_record_id(owner, value.derivation).expect("address id");
15125            store
15126                .save_derived_address(&id, 0, &value, 1)
15127                .expect("persist address");
15128        }
15129        assert_eq!(
15130            persisted_name_addresses(&store, &config).expect("scoped name addresses"),
15131            vec![address(&config, KeyRole::HnsCoin, 1, 21), second_coin]
15132        );
15133
15134        let current_name_id = namespaced_name_id(&config, [31; 32]);
15135        let other_name_id = namespaced_name_id(&other_config, [32; 32]);
15136        store
15137            .save_known_name(
15138                &current_name_id,
15139                0,
15140                &serde_json::json!({"name":"current"}),
15141                2,
15142            )
15143            .expect("current name");
15144        store
15145            .save_known_name(&other_name_id, 0, &serde_json::json!({"name":"other"}), 2)
15146            .expect("other name");
15147        let scoped = store
15148            .list_entities_by_id_prefix::<serde_json::Value>(
15149                EntityKind::KnownName,
15150                &account_entity_prefix(&config),
15151                MAX_HISTORY_RESULTS,
15152            )
15153            .expect("scoped names");
15154        assert_eq!(scoped.len(), 1);
15155        assert_eq!(scoped[0].id, current_name_id);
15156
15157        let current_reservation = HnsInputReservation {
15158            wallet_id: config.wallet_id,
15159            account_id: config.account_id,
15160            outpoint: HnsOutpoint {
15161                transaction: TransactionHash::new([41; 32]),
15162                output_index: 1,
15163            },
15164            workflow_id: WorkflowId::new([42; 16]),
15165            expires_at_unix: Some(10),
15166            kind: HnsInputReservationKind::Ordinary,
15167        };
15168        let other_reservation = HnsInputReservation {
15169            wallet_id: other_config.wallet_id,
15170            account_id: other_config.account_id,
15171            outpoint: HnsOutpoint {
15172                transaction: TransactionHash::new([43; 32]),
15173                output_index: 2,
15174            },
15175            workflow_id: WorkflowId::new([44; 16]),
15176            expires_at_unix: Some(10),
15177            kind: HnsInputReservationKind::Ordinary,
15178        };
15179        for (owner, reservation) in [
15180            (&config, current_reservation.clone()),
15181            (&other_config, other_reservation),
15182        ] {
15183            store
15184                .save_input_reservation(
15185                    &namespaced_outpoint_id(owner, reservation.outpoint),
15186                    0,
15187                    &reservation,
15188                    3,
15189                )
15190                .expect("reservation");
15191        }
15192        assert_eq!(
15193            account_input_reservations(&store, &config)
15194                .expect("scoped reservations")
15195                .into_iter()
15196                .map(|stored| stored.value)
15197                .collect::<Vec<_>>(),
15198            vec![current_reservation]
15199        );
15200
15201        for (id, account) in [
15202            (WorkflowId::new([51; 16]), config.account_id),
15203            (WorkflowId::new([52; 16]), other_config.account_id),
15204        ] {
15205            store
15206                .save_workflow(
15207                    id,
15208                    WorkflowKind::HnsSend,
15209                    0,
15210                    &serde_json::json!({"account": account}),
15211                    false,
15212                    4,
15213                )
15214                .expect("workflow");
15215        }
15216        assert_eq!(
15217            store
15218                .list_workflows_complete::<serde_json::Value>(
15219                    WorkflowKind::HnsSend,
15220                    MAX_HISTORY_RESULTS,
15221                )
15222                .expect("complete workflows")
15223                .len(),
15224            2
15225        );
15226    }
15227
15228    #[test]
15229    fn authoritative_reconcile_account_rejects_derivation_rollback() {
15230        let cached = HnsAccountRecord {
15231            config: test_runtime_config(),
15232            next_receive_index: 3,
15233            next_change_index: 4,
15234            next_shakedex_index: 6,
15235            external_scan_end: 102,
15236            internal_scan_end: 103,
15237            shakedex_scan_end: 105,
15238            shakedex_scan_complete: true,
15239            shakedex_scan_in_progress: false,
15240            last_used_external: Some(2),
15241            last_used_internal: Some(3),
15242            last_used_shakedex: Some(5),
15243        };
15244        assert!(validate_authoritative_reconcile_account(&cached, 7, &cached, 7).is_ok());
15245
15246        let mut advanced = cached.clone();
15247        advanced.next_change_index = 5;
15248        advanced.internal_scan_end = 104;
15249        assert!(validate_authoritative_reconcile_account(&cached, 7, &advanced, 8).is_ok());
15250
15251        let mut rolled_back = advanced.clone();
15252        rolled_back.next_receive_index = 2;
15253        assert!(matches!(
15254            validate_authoritative_reconcile_account(&cached, 7, &rolled_back, 8),
15255            Err(HnsWalletError::InvalidEvidence)
15256        ));
15257        assert!(matches!(
15258            validate_authoritative_reconcile_account(&cached, 7, &advanced, 6),
15259            Err(HnsWalletError::InvalidEvidence)
15260        ));
15261        assert!(matches!(
15262            validate_authoritative_reconcile_account(&cached, 7, &advanced, 7),
15263            Err(HnsWalletError::InvalidEvidence)
15264        ));
15265
15266        let mut mismatched = advanced;
15267        mismatched.config.minimum_confirmations += 1;
15268        assert!(matches!(
15269            validate_authoritative_reconcile_account(&cached, 7, &mismatched, 8),
15270            Err(HnsWalletError::AccountConfigurationMismatch)
15271        ));
15272    }
15273
15274    #[test]
15275    fn missing_optional_account_state_defaults_independent_scans() {
15276        let account = HnsAccountRecord {
15277            config: test_runtime_config(),
15278            next_receive_index: 3,
15279            next_change_index: 4,
15280            next_shakedex_index: 9,
15281            external_scan_end: 102,
15282            internal_scan_end: 103,
15283            shakedex_scan_end: 108,
15284            shakedex_scan_complete: true,
15285            shakedex_scan_in_progress: false,
15286            last_used_external: Some(2),
15287            last_used_internal: Some(3),
15288            last_used_shakedex: Some(8),
15289        };
15290        let mut encoded = serde_json::to_value(account).expect("encode account");
15291        let object = encoded.as_object_mut().expect("account object");
15292        object.remove("next_shakedex_index");
15293        object.remove("shakedex_scan_end");
15294        object.remove("shakedex_scan_complete");
15295        object.remove("shakedex_scan_in_progress");
15296        object.remove("last_used_shakedex");
15297        let decoded: HnsAccountRecord =
15298            serde_json::from_value(encoded).expect("decode account defaults");
15299        assert_eq!(decoded.next_shakedex_index, 0);
15300        assert_eq!(decoded.shakedex_scan_end, 0);
15301        assert!(!decoded.shakedex_scan_complete);
15302        assert!(!decoded.shakedex_scan_in_progress);
15303        assert_eq!(decoded.last_used_shakedex, None);
15304        assert_eq!(decoded.next_receive_index, 3);
15305        assert_eq!(decoded.external_scan_end, 102);
15306    }
15307
15308    #[test]
15309    fn shakedex_address_ids_are_role_discriminated_without_changing_coin_ids() {
15310        let config = test_runtime_config();
15311        let coin = DerivationReference {
15312            role: KeyRole::HnsCoin,
15313            account: config.account_derivation_index,
15314            change: 0,
15315            index: 9,
15316        };
15317        let name = DerivationReference {
15318            role: KeyRole::HnsName,
15319            ..coin
15320        };
15321        let shakedex = DerivationReference {
15322            role: KeyRole::HnsShakedex,
15323            ..coin
15324        };
15325        let coin_id = derived_address_record_id(&config, coin).expect("coin id");
15326        let shakedex_id =
15327            derived_address_record_id(&config, shakedex).expect("Shakedex address id");
15328        assert_eq!(coin_id, derived_address_id(&config, 0, 9).to_vec());
15329        assert_eq!(coin_id.len(), 40);
15330        assert_eq!(shakedex_id.len(), 41);
15331        assert_ne!(coin_id, shakedex_id);
15332        assert!(derived_address_record_id(&config, name).is_err());
15333        assert!(
15334            derived_address_record_id(
15335                &config,
15336                DerivationReference {
15337                    change: 1,
15338                    ..shakedex
15339                }
15340            )
15341            .is_err()
15342        );
15343    }
15344
15345    #[test]
15346    fn separate_restore_queries_share_one_exact_snapshot() {
15347        let binding = test_snapshot(4);
15348        let mempool = test_mempool(5);
15349        assert!(validate_same_restore_snapshot(binding, mempool, binding, mempool).is_ok());
15350        assert!(
15351            validate_same_restore_snapshot(binding, mempool, test_snapshot(6), mempool).is_err()
15352        );
15353        assert!(
15354            validate_same_restore_snapshot(binding, mempool, binding, test_mempool(6)).is_err()
15355        );
15356        let restarted = MempoolSnapshotBinding {
15357            instance_nonce: [24; 32],
15358            generation: mempool.generation,
15359        };
15360        assert!(validate_same_restore_snapshot(binding, mempool, binding, restarted).is_err());
15361    }
15362
15363    #[test]
15364    fn hns_shakedex_legacy_snapshot_time_defaults_fail_closed() {
15365        let mut encoded = serde_json::to_value(test_snapshot(4).tip).expect("encode tip");
15366        encoded
15367            .as_object_mut()
15368            .expect("tip object")
15369            .remove("median_time_past");
15370        let decoded: ChainTip = serde_json::from_value(encoded).expect("decode legacy tip");
15371        assert_eq!(decoded.median_time_past, 0);
15372    }
15373
15374    #[test]
15375    fn separated_gap_and_next_indexes_never_shrink_after_restart_or_reorg() {
15376        assert_eq!(required_scan_end(None, 500, 100), 500);
15377        assert_eq!(required_scan_end(Some(3), 500, 100), 500);
15378        assert_eq!(required_scan_end(Some(550), 500, 100), 650);
15379        assert_eq!(advance_next_derivation_index(50, None), 50);
15380        assert_eq!(advance_next_derivation_index(50, Some(3)), 50);
15381        assert_eq!(advance_next_derivation_index(50, Some(80)), 81);
15382        assert_eq!(
15383            checked_scan_address_count(&[4_999, 4_999]).expect("full coin query"),
15384            MAX_RESTORE_SCRIPTS_PER_QUERY
15385        );
15386        assert_eq!(
15387            checked_scan_address_count(&[9_999]).expect("full name query"),
15388            MAX_RESTORE_SCRIPTS_PER_QUERY
15389        );
15390        assert!(checked_scan_address_count(&[5_000, 5_000]).is_err());
15391        assert_eq!(
15392            MAX_RESTORE_ADDRESS_RECORDS,
15393            MAX_RESTORE_SCRIPTS_PER_QUERY * 3
15394        );
15395    }
15396
15397    #[test]
15398    fn name_receive_target_is_the_canonical_payment_target() {
15399        let mut account =
15400            HnsAccountRecord::initial_non_value(test_runtime_config()).expect("non-value account");
15401        account.next_receive_index = 3;
15402        let address = DerivedHnsAddress {
15403            account_id: account.config.account_id,
15404            derivation: DerivationReference {
15405                role: KeyRole::HnsCoin,
15406                account: account.config.account_derivation_index,
15407                change: 0,
15408                index: 3,
15409            },
15410            address: "canonical-receive".to_owned(),
15411            program: vec![3; 20],
15412            used: false,
15413        };
15414        let ordinary = hns_read_receive_target(&account, std::slice::from_ref(&address))
15415            .expect("ordinary target");
15416        let name = hns_read_name_receive_target(&account, &[address]).expect("name target");
15417        assert_eq!(ordinary.display, "canonical-receive");
15418        assert_eq!(ordinary.derivation_index, 3);
15419        assert_eq!(name.display, ordinary.display);
15420        assert_eq!(name.derivation_index, ordinary.derivation_index);
15421        assert_eq!(name.account, account.config.account_id);
15422        assert_eq!(name.module, ModuleId::Handshake);
15423    }
15424
15425    #[test]
15426    fn shakedex_output_is_not_an_ordinary_value_candidate() {
15427        let role = KeyRole::HnsShakedex;
15428        let byte = 32;
15429        let address = test_derived_address(role, byte);
15430        let tracked = reconcile_coins(
15431            vec![IndexedWalletCoin {
15432                coin: WalletCoin {
15433                    outpoint: HnsOutpoint {
15434                        transaction: TransactionHash::new([byte; 32]),
15435                        output_index: 1,
15436                    },
15437                    value: BaseUnits::new(1_000),
15438                    confirmation_count: 10,
15439                    confirmed_height: Some(491),
15440                    coinbase: false,
15441                    covenant: Covenant::default().encode().expect("covenant"),
15442                    name_locked: false,
15443                },
15444                script_index: 0,
15445                output_address: WalletAddressKey {
15446                    version: 0,
15447                    hash: address.program.clone(),
15448                },
15449            }],
15450            &[address],
15451            500,
15452        )
15453        .expect("track separated output");
15454        assert_eq!(tracked.len(), 1);
15455        assert_eq!(tracked[0].derivation.role, role);
15456        assert!(!is_ordinary_hns_spend_candidate(&tracked[0]));
15457    }
15458
15459    #[test]
15460    fn unconfirmed_ordinary_output_is_not_presented_as_spendable() {
15461        let address = test_derived_address(KeyRole::HnsCoin, 33);
15462        let mut coin = TrackedHnsCoin {
15463            coin: WalletCoin {
15464                outpoint: HnsOutpoint {
15465                    transaction: TransactionHash::new([33; 32]),
15466                    output_index: 0,
15467                },
15468                value: BaseUnits::new(1_000_000),
15469                confirmation_count: 0,
15470                confirmed_height: None,
15471                coinbase: false,
15472                covenant: Covenant::default().encode().expect("covenant"),
15473                name_locked: false,
15474            },
15475            derivation: address.derivation,
15476            address_program: address.program,
15477        };
15478        assert!(is_ordinary_hns_spend_candidate(&coin));
15479        assert!(!is_confirmed_ordinary_hns_spend_candidate(&coin));
15480        coin.coin.confirmation_count = 1;
15481        coin.coin.confirmed_height = Some(500);
15482        assert!(is_confirmed_ordinary_hns_spend_candidate(&coin));
15483    }
15484
15485    #[test]
15486    fn duplicate_programs_and_unsupported_roles_fail_closed() {
15487        let coin = test_derived_address(KeyRole::HnsCoin, 41);
15488        let duplicate = test_derived_address(KeyRole::HnsCoin, 41);
15489        assert!(validate_disjoint_restore_programs(&[coin], &[duplicate]).is_err());
15490        assert!(
15491            restore_derivation_key(DerivationReference {
15492                role: KeyRole::HnsName,
15493                account: 7,
15494                change: 1,
15495                index: 0,
15496            })
15497            .is_err()
15498        );
15499        assert!(
15500            restore_derivation_key(DerivationReference {
15501                role: KeyRole::HnsShakedex,
15502                account: 7,
15503                change: 1,
15504                index: 0,
15505            })
15506            .is_err()
15507        );
15508    }
15509
15510    #[test]
15511    fn coin_selection_excludes_name_locked_outputs_and_is_deterministic() {
15512        let coins = vec![
15513            WalletCoin {
15514                outpoint: HnsOutpoint {
15515                    transaction: TransactionHash::new([1; 32]),
15516                    output_index: 0,
15517                },
15518                value: BaseUnits::new(7),
15519                confirmation_count: 1,
15520                confirmed_height: Some(500),
15521                coinbase: false,
15522                covenant: Covenant {
15523                    kind: CovenantKind::Update,
15524                    items: Vec::new(),
15525                }
15526                .encode()
15527                .expect("name covenant"),
15528                name_locked: true,
15529            },
15530            WalletCoin {
15531                outpoint: HnsOutpoint {
15532                    transaction: TransactionHash::new([2; 32]),
15533                    output_index: 0,
15534                },
15535                value: BaseUnits::new(5),
15536                confirmation_count: 1,
15537                confirmed_height: Some(500),
15538                coinbase: false,
15539                covenant: Covenant::default().encode().expect("covenant"),
15540                name_locked: false,
15541            },
15542            WalletCoin {
15543                outpoint: HnsOutpoint {
15544                    transaction: TransactionHash::new([3; 32]),
15545                    output_index: 0,
15546                },
15547                value: BaseUnits::new(4),
15548                confirmation_count: 2,
15549                confirmed_height: Some(499),
15550                coinbase: false,
15551                covenant: Covenant::default().encode().expect("covenant"),
15552                name_locked: false,
15553            },
15554        ];
15555        let selected = select_coins(&coins, BaseUnits::new(8)).expect("selection");
15556        assert_eq!(selected.coins.len(), 2);
15557        assert_eq!(selected.total, BaseUnits::new(9));
15558        assert_eq!(selected.change, BaseUnits::new(1));
15559        assert!(
15560            selected
15561                .coins
15562                .iter()
15563                .all(|coin| !coin.name_locked && !coin.coinbase)
15564        );
15565    }
15566
15567    #[test]
15568    fn exact_coin_evidence_rejects_legacy_and_mismatched_rows() {
15569        let covenant = Covenant::default().encode().expect("covenant");
15570        let tracked = TrackedHnsCoin {
15571            coin: WalletCoin {
15572                outpoint: HnsOutpoint {
15573                    transaction: TransactionHash::new([61; 32]),
15574                    output_index: 2,
15575                },
15576                value: BaseUnits::new(50_000),
15577                confirmation_count: 4,
15578                confirmed_height: Some(497),
15579                coinbase: false,
15580                covenant: covenant.clone(),
15581                name_locked: false,
15582            },
15583            derivation: DerivationReference {
15584                role: KeyRole::HnsCoin,
15585                account: 7,
15586                change: 0,
15587                index: 3,
15588            },
15589            address_program: vec![62; 20],
15590        };
15591        let canonical = tracked.to_canonical_coin().expect("canonical coin");
15592        assert_eq!(canonical.height, Height::new(497));
15593        assert_eq!(canonical.covenant.encode().expect("encode"), covenant);
15594        assert_eq!(canonical.address.hash, vec![62; 20]);
15595
15596        let mut legacy = serde_json::to_value(&tracked).expect("tracked coin");
15597        let coin = legacy
15598            .get_mut("coin")
15599            .and_then(serde_json::Value::as_object_mut)
15600            .expect("coin object");
15601        coin.remove("confirmed_height");
15602        coin.remove("covenant");
15603        let legacy: TrackedHnsCoin = serde_json::from_value(legacy).expect("legacy row decodes");
15604        assert!(matches!(
15605            legacy.to_canonical_coin(),
15606            Err(HnsWalletError::InvalidEvidence)
15607        ));
15608
15609        let mut mismatched = tracked;
15610        mismatched.coin.name_locked = true;
15611        assert!(matches!(
15612            mismatched.to_canonical_coin(),
15613            Err(HnsWalletError::InvalidEvidence)
15614        ));
15615
15616        let mut zero_ordinary = mismatched;
15617        zero_ordinary.coin.name_locked = false;
15618        zero_ordinary.coin.value = BaseUnits::ZERO;
15619        assert!(matches!(
15620            zero_ordinary.to_canonical_coin(),
15621            Err(HnsWalletError::InvalidEvidence)
15622        ));
15623        let mut zero_ordinary_input =
15624            HnsInputCoinEvidence::from_canonical_coin(&canonical).expect("ordinary input");
15625        zero_ordinary_input.value = BaseUnits::ZERO;
15626        assert!(matches!(
15627            zero_ordinary_input.to_canonical_coin(),
15628            Err(HnsWalletError::InvalidEvidence)
15629        ));
15630        let shakedex_address = test_derived_address(KeyRole::HnsShakedex, 63);
15631        let zero_shakedex = TrackedHnsCoin {
15632            coin: WalletCoin {
15633                outpoint: HnsOutpoint {
15634                    transaction: TransactionHash::new([63; 32]),
15635                    output_index: 0,
15636                },
15637                value: BaseUnits::ZERO,
15638                confirmation_count: 1,
15639                confirmed_height: Some(500),
15640                coinbase: false,
15641                covenant: Covenant::default().encode().expect("NONE covenant"),
15642                name_locked: false,
15643            },
15644            derivation: shakedex_address.derivation,
15645            address_program: shakedex_address.program,
15646        };
15647        assert!(matches!(
15648            zero_shakedex.to_canonical_coin(),
15649            Err(HnsWalletError::InvalidEvidence)
15650        ));
15651    }
15652
15653    #[test]
15654    fn exact_coin_evidence_accepts_finalized_name_on_shakedex_script() {
15655        let shakedex_address = test_derived_address(KeyRole::HnsShakedex, 64);
15656        let (_, finalized_coin, _) = zero_value_finalize_owner(&shakedex_address);
15657        let tracked = TrackedHnsCoin {
15658            coin: WalletCoin {
15659                outpoint: HnsOutpoint {
15660                    transaction: TransactionHash::new(
15661                        finalized_coin.outpoint.transaction_hash.into_bytes(),
15662                    ),
15663                    output_index: finalized_coin.outpoint.index,
15664                },
15665                value: BaseUnits::ZERO,
15666                confirmation_count: 1,
15667                confirmed_height: Some(finalized_coin.height.get()),
15668                coinbase: finalized_coin.coinbase,
15669                covenant: finalized_coin.covenant.encode().expect("FINALIZE covenant"),
15670                name_locked: true,
15671            },
15672            derivation: shakedex_address.derivation,
15673            address_program: shakedex_address.program.clone(),
15674        };
15675
15676        let canonical = tracked
15677            .to_canonical_coin()
15678            .expect("confirmed FINALIZE on tracked ShakeDex P2WSH");
15679        assert_eq!(canonical.address.version, 0);
15680        assert_eq!(canonical.address.hash, shakedex_address.program);
15681        assert_eq!(canonical.value, Dollarydoos::new(0));
15682        assert_eq!(canonical.covenant.kind, CovenantKind::Finalize);
15683    }
15684
15685    #[test]
15686    fn canonical_policy_quote_is_recomputed_from_ordered_input_coins() {
15687        let input_coin = Coin {
15688            outpoint: Outpoint {
15689                transaction_hash: CanonicalTransactionHash::new([71; 32]),
15690                index: 0,
15691            },
15692            value: Dollarydoos::new(100_000),
15693            height: Height::new(450),
15694            coinbase: false,
15695            address: Address::new(0, vec![72; 20]).expect("address"),
15696            covenant: Covenant::default(),
15697        };
15698        let mut transaction = Transaction {
15699            version: 0,
15700            inputs: vec![Input {
15701                previous_output: input_coin.outpoint,
15702                sequence: u32::MAX,
15703                witness: Witness {
15704                    items: vec![vec![0; 65], vec![0; 33]],
15705                },
15706            }],
15707            outputs: vec![Output {
15708                value: input_coin.value,
15709                address: Address::new(0, vec![73; 20]).expect("address"),
15710                covenant: Covenant::default(),
15711            }],
15712            locktime: 0,
15713        };
15714        let rate = BaseUnits::new(1_000);
15715        let fee =
15716            canonical_policy_minimum_fee(&transaction, std::slice::from_ref(&input_coin), rate)
15717                .expect("minimum fee");
15718        transaction.outputs[0].value = Dollarydoos::new(
15719            input_coin.value.get() - u64::try_from(fee.get()).expect("bounded fee"),
15720        );
15721        let local =
15722            local_fee_policy_evidence(&transaction, std::slice::from_ref(&input_coin), rate)
15723                .expect("policy evidence");
15724        let binding = test_snapshot(8);
15725        let mempool = test_mempool(9);
15726        let mut quote = HnsTransactionFeeQuote {
15727            txid: wallet_transaction_hash(&transaction).expect("txid"),
15728            binding,
15729            mempool,
15730            target_blocks: DEFAULT_FEE_TARGET_BLOCKS,
15731            rate_atomic_units_per_1000_policy_vbytes: 1_000,
15732            rate_sample_count: 0,
15733            rate_source: HnsFeeRateSource::MinimumRelay,
15734            transaction_weight: local.transaction_weight,
15735            transaction_sigops: local.transaction_sigops,
15736            sigop_adjusted_policy_vbytes: local.policy_virtual_size,
15737            minimum_policy_fee: local.minimum_fee,
15738            actual_fee: fee,
15739            meets_minimum_policy_fee: true,
15740            minimum_policy_fee_shortfall: BaseUnits::ZERO,
15741        };
15742        assert!(
15743            validate_local_fee_quote_evidence(
15744                &transaction,
15745                std::slice::from_ref(&input_coin),
15746                &quote,
15747            )
15748            .is_ok()
15749        );
15750        validate_final_fee_quote(
15751            &transaction.encode().expect("transaction"),
15752            std::slice::from_ref(&input_coin),
15753            &quote,
15754            binding,
15755            mempool,
15756            fee,
15757            fee,
15758        )
15759        .expect("qualified fee policy accepts its canonical evidence");
15760        quote.transaction_sigops = quote.transaction_sigops.saturating_add(1);
15761        assert!(matches!(
15762            validate_local_fee_quote_evidence(&transaction, &[input_coin], &quote),
15763            Err(HnsWalletError::InvalidFeeQuote)
15764        ));
15765    }
15766
15767    #[test]
15768    fn ordered_p2pkh_signer_handles_value_and_name_coins_on_account_zero() {
15769        let mut store = WalletStore::create(":memory:", "passphrase").expect("store");
15770        let account = HnsAccountRecord {
15771            config: test_runtime_config(),
15772            next_receive_index: 0,
15773            next_change_index: 0,
15774            next_shakedex_index: 0,
15775            external_scan_end: 99,
15776            internal_scan_end: 99,
15777            shakedex_scan_end: 99,
15778            shakedex_scan_complete: true,
15779            shakedex_scan_in_progress: false,
15780            last_used_external: None,
15781            last_used_internal: None,
15782            last_used_shakedex: None,
15783        };
15784        store
15785            .put_secret(
15786                account.config.wallet_id.as_bytes(),
15787                SecretKind::RecoverySeed,
15788                &[81; 64],
15789                1,
15790            )
15791            .expect("seed");
15792        let make_coin = |index, tx_byte, value, name_locked| {
15793            let derivation = DerivationReference {
15794                role: KeyRole::HnsCoin,
15795                account: account_number(&account),
15796                change: 0,
15797                index,
15798            };
15799            let public =
15800                derive_hns_account_public_key(&store, &account, derivation).expect("public key");
15801            let program = public_key_hash(&public).expect("program").to_vec();
15802            let covenant = if name_locked {
15803                Covenant {
15804                    kind: CovenantKind::Update,
15805                    items: Vec::new(),
15806                }
15807            } else {
15808                Covenant::default()
15809            };
15810            TrackedHnsCoin {
15811                coin: WalletCoin {
15812                    outpoint: HnsOutpoint {
15813                        transaction: TransactionHash::new([tx_byte; 32]),
15814                        output_index: 0,
15815                    },
15816                    value: BaseUnits::new(value),
15817                    confirmation_count: 5,
15818                    confirmed_height: Some(496),
15819                    coinbase: false,
15820                    covenant: covenant.encode().expect("covenant"),
15821                    name_locked,
15822                },
15823                derivation,
15824                address_program: program,
15825            }
15826        };
15827        let name = make_coin(1, 82, 50_000, true);
15828        let fee = make_coin(2, 83, 10_000, false);
15829        let inputs = vec![name, fee];
15830        let transaction = Transaction {
15831            version: 0,
15832            inputs: inputs
15833                .iter()
15834                .map(|coin| Input {
15835                    previous_output: coin.to_canonical_coin().expect("coin").outpoint,
15836                    sequence: u32::MAX,
15837                    witness: Witness::default(),
15838                })
15839                .collect(),
15840            outputs: vec![Output {
15841                value: Dollarydoos::new(59_000),
15842                address: Address::new(0, vec![84; 20]).expect("address"),
15843                covenant: Covenant::default(),
15844            }],
15845            locktime: 0,
15846        };
15847        let signed = sign_ordered_p2pkh_inputs(
15848            &store,
15849            &account,
15850            transaction.clone(),
15851            &inputs,
15852            &[KeyRole::HnsCoin, KeyRole::HnsCoin],
15853        )
15854        .expect("ordered signing");
15855        let signed = Transaction::decode(&signed).expect("signed transaction");
15856        assert!(signed.inputs.iter().all(|input| {
15857            input.witness.items.len() == 2
15858                && input.witness.items[0].len() == 65
15859                && input.witness.items[1].len() == 33
15860        }));
15861        let input_coins = canonical_input_coins(&inputs).expect("canonical input coins");
15862        validate_standard_input_authorizations(&signed, &input_coins)
15863            .expect("standard input authorizations");
15864        let mut corrupted = signed.clone();
15865        corrupted.inputs[0].witness.items[0][0] ^= 1;
15866        assert!(matches!(
15867            validate_standard_input_authorizations(&corrupted, &input_coins),
15868            Err(HnsWalletError::Signing)
15869        ));
15870        assert!(matches!(
15871            sign_ordered_p2pkh_inputs(
15872                &store,
15873                &account,
15874                transaction,
15875                &inputs,
15876                &[KeyRole::HnsShakedex, KeyRole::HnsCoin],
15877            ),
15878            Err(HnsWalletError::InvalidPreparedArtifact)
15879        ));
15880    }
15881
15882    #[test]
15883    fn tiny_htlc_redeem_can_be_fee_sponsored_and_all_inputs_verify() {
15884        let mut store = WalletStore::create(":memory:", "passphrase").expect("store");
15885        let account = HnsAccountRecord {
15886            config: test_runtime_config(),
15887            next_receive_index: 0,
15888            next_change_index: 0,
15889            next_shakedex_index: 0,
15890            external_scan_end: 99,
15891            internal_scan_end: 99,
15892            shakedex_scan_end: 99,
15893            shakedex_scan_complete: true,
15894            shakedex_scan_in_progress: false,
15895            last_used_external: None,
15896            last_used_internal: None,
15897            last_used_shakedex: None,
15898        };
15899        store
15900            .put_secret(
15901                account.config.wallet_id.as_bytes(),
15902                SecretKind::RecoverySeed,
15903                &[91; 64],
15904                1,
15905            )
15906            .expect("seed");
15907        let session_id = SessionId::new([92; 32]);
15908        let receiver =
15909            derive_settlement_public_key(&store, &account, session_id, false).expect("receiver");
15910        let refund = SigningKey::from_slice(&[93; 32])
15911            .expect("refund key")
15912            .verifying_key()
15913            .to_sec1_point(true);
15914        let refund: [u8; 33] = refund.as_bytes().try_into().expect("compressed refund key");
15915        let preimage = Preimage::new([94; 32]);
15916        let hashlock = ObjectHash::new(Sha256::digest(preimage.expose_for_settlement()).into());
15917        let script = hns_htlc_script(hashlock, &receiver, &refund, 600).expect("HTLC script");
15918        let funding_id = TransactionHash::new([95; 32]);
15919        let lock = VerifiedLock {
15920            module: ModuleId::Handshake,
15921            session_id,
15922            funding_id,
15923            amount: Amount::new(WalletAsset::Hns, 546),
15924            hashlock,
15925            absolute_timelock: 600,
15926            confirmation_count: 2,
15927            evidence_hash: ObjectHash::new([96; 32]),
15928        };
15929        let sponsor_derivation = DerivationReference {
15930            role: KeyRole::HnsCoin,
15931            account: account_number(&account),
15932            change: 0,
15933            index: 4,
15934        };
15935        let sponsor_public = derive_hns_account_public_key(&store, &account, sponsor_derivation)
15936            .expect("sponsor public key");
15937        let sponsor = TrackedHnsCoin {
15938            coin: WalletCoin {
15939                outpoint: HnsOutpoint {
15940                    transaction: TransactionHash::new([97; 32]),
15941                    output_index: 1,
15942                },
15943                value: BaseUnits::new(100_000),
15944                confirmation_count: 3,
15945                confirmed_height: Some(500),
15946                coinbase: false,
15947                covenant: Covenant::default().encode().expect("covenant"),
15948                name_locked: false,
15949            },
15950            derivation: sponsor_derivation,
15951            address_program: public_key_hash(&sponsor_public)
15952                .expect("sponsor program")
15953                .to_vec(),
15954        };
15955        let destination = Address::new(0, vec![98; 20]).expect("destination");
15956        let unsponsored = unsigned_sponsored_htlc_spend(
15957            &lock,
15958            0,
15959            &script,
15960            546,
15961            &[],
15962            destination.clone(),
15963            u32::MAX,
15964            0,
15965            false,
15966        )
15967        .expect("unsponsored template");
15968        let funding_coin = Coin {
15969            outpoint: unsponsored.inputs[0].previous_output,
15970            value: Dollarydoos::new(546),
15971            height: Height::new(500),
15972            coinbase: false,
15973            address: Address::new(0, Sha3_256::digest(&script).to_vec()).expect("HTLC address"),
15974            covenant: Covenant::default(),
15975        };
15976        let rate = BaseUnits::new(1_000);
15977        let unsponsored_fee =
15978            canonical_policy_minimum_fee(&unsponsored, std::slice::from_ref(&funding_coin), rate)
15979                .expect("unsponsored fee");
15980        assert!(
15981            u128::from(funding_coin.value.get()) - unsponsored_fee.get()
15982                < account.config.dust_threshold.get()
15983        );
15984
15985        let mut transaction = unsigned_sponsored_htlc_spend(
15986            &lock,
15987            0,
15988            &script,
15989            546,
15990            std::slice::from_ref(&sponsor),
15991            destination,
15992            u32::MAX,
15993            0,
15994            false,
15995        )
15996        .expect("sponsored template");
15997        let sponsor_coin = sponsor.to_canonical_coin().expect("sponsor coin");
15998        let input_coins = vec![funding_coin, sponsor_coin];
15999        let fee =
16000            canonical_policy_minimum_fee(&transaction, &input_coins, rate).expect("sponsored fee");
16001        let total = 100_546_u64;
16002        transaction.outputs[0].value =
16003            Dollarydoos::new(total - u64::try_from(fee.get()).expect("bounded sponsored fee"));
16004        let signed_sponsor = sign_ordered_p2pkh_inputs_from(
16005            &store,
16006            &account,
16007            transaction,
16008            1,
16009            std::slice::from_ref(&sponsor),
16010            &[KeyRole::HnsCoin],
16011        )
16012        .expect("sponsor signature");
16013        let signed = sign_htlc_spend(
16014            &store,
16015            &account,
16016            Transaction::decode(&signed_sponsor).expect("sponsor transaction"),
16017            session_id,
16018            &script,
16019            546,
16020            Some(&preimage),
16021            false,
16022        )
16023        .expect("HTLC signature");
16024        let signed = Transaction::decode(&signed).expect("signed transaction");
16025        validate_standard_input_authorizations(&signed, &input_coins)
16026            .expect("all mixed input authorizations");
16027        let funding_evidence =
16028            HnsInputCoinEvidence::from_canonical_coin(&input_coins[0]).expect("funding evidence");
16029        let unsponsored_evidence = settlement_input_evidence(funding_evidence.clone(), &[])
16030            .expect("unsponsored settlement evidence");
16031        assert_eq!(unsponsored_evidence, vec![funding_evidence.clone()]);
16032        assert_eq!(
16033            canonical_evidence_coins(&unsponsored_evidence)
16034                .expect("canonical unsponsored settlement evidence"),
16035            vec![input_coins[0].clone()]
16036        );
16037        let sponsored_evidence =
16038            settlement_input_evidence(funding_evidence, std::slice::from_ref(&sponsor))
16039                .expect("sponsored settlement evidence");
16040        assert_eq!(sponsored_evidence.len(), 2);
16041        assert_eq!(
16042            canonical_evidence_coins(&sponsored_evidence)
16043                .expect("canonical sponsored settlement evidence"),
16044            input_coins
16045        );
16046        assert_eq!(signed.inputs[0].witness.items.len(), 4);
16047        assert_eq!(signed.inputs[1].witness.items.len(), 2);
16048        assert!(u128::from(signed.outputs[0].value.get()) >= account.config.dust_threshold.get());
16049    }
16050
16051    #[test]
16052    fn settlement_retry_terms_accept_only_monotonic_confirmation_refreshes() {
16053        let stored_lock = VerifiedLock {
16054            module: ModuleId::Handshake,
16055            session_id: SessionId::new([101; 32]),
16056            funding_id: TransactionHash::new([102; 32]),
16057            amount: Amount::new(WalletAsset::Hns, 546),
16058            hashlock: ObjectHash::new([103; 32]),
16059            absolute_timelock: 700,
16060            confirmation_count: 2,
16061            evidence_hash: ObjectHash::new([104; 32]),
16062        };
16063        let mut refreshed_lock = stored_lock.clone();
16064        refreshed_lock.confirmation_count = 5;
16065        assert_eq!(
16066            refreshed_verified_settlement_lock(&refreshed_lock, &stored_lock)
16067                .expect("the freshest equivalent verified lock wins"),
16068            refreshed_lock,
16069        );
16070        assert!(settlement_terms_are_retry_compatible(
16071            &HnsSettlementTerms::Redeem {
16072                lock: stored_lock.clone(),
16073            },
16074            &HnsSettlementTerms::Redeem {
16075                lock: refreshed_lock.clone(),
16076            },
16077        ));
16078
16079        let mut regressed_lock = stored_lock.clone();
16080        regressed_lock.confirmation_count = 1;
16081        assert!(!settlement_terms_are_retry_compatible(
16082            &HnsSettlementTerms::Redeem {
16083                lock: stored_lock.clone(),
16084            },
16085            &HnsSettlementTerms::Redeem {
16086                lock: regressed_lock,
16087            },
16088        ));
16089
16090        refreshed_lock.evidence_hash = ObjectHash::new([105; 32]);
16091        assert!(matches!(
16092            refreshed_verified_settlement_lock(&refreshed_lock, &stored_lock),
16093            Err(ChainError::InvalidEvidenceContext(
16094                "verified HNS lock binding"
16095            ))
16096        ));
16097        assert!(!settlement_terms_are_retry_compatible(
16098            &HnsSettlementTerms::Redeem { lock: stored_lock },
16099            &HnsSettlementTerms::Redeem {
16100                lock: refreshed_lock,
16101            },
16102        ));
16103    }
16104
16105    #[test]
16106    fn production_followup_account_reads_commit_one_live_binding_without_store_locked_node_io() {
16107        let (store, config) = production_followup_read_store();
16108        let runtime = production_followup_read_runtime(
16109            store.clone(),
16110            config.clone(),
16111            ProductionFollowupReadFault::Healthy,
16112        );
16113
16114        let snapshot = runtime.synchronize().expect("one synchronized read");
16115        assert_eq!(snapshot.account_id, config.account_id);
16116        assert_eq!(
16117            snapshot.binding.chain,
16118            ProductionFollowupReadBackend::binding()
16119        );
16120        assert_eq!(
16121            snapshot.binding.mempool,
16122            ProductionFollowupReadBackend::mempool()
16123        );
16124        assert_eq!(snapshot.balance, Amount::new(WalletAsset::Hns, 0));
16125        assert!(snapshot.transactions.is_empty());
16126        assert!(snapshot.known_names.is_empty());
16127        assert_eq!(snapshot.receive_target.module, ModuleId::Handshake);
16128        assert_eq!(snapshot.receive_target.account, config.account_id);
16129        assert_eq!(snapshot.receive_target.derivation_index, 0);
16130        assert!(snapshot.receive_target.display.starts_with("rs1"));
16131        assert_eq!(snapshot.name_receive_target.module, ModuleId::Handshake);
16132        assert_eq!(snapshot.name_receive_target.account, config.account_id);
16133        assert_eq!(snapshot.name_receive_target.derivation_index, 0);
16134        assert!(snapshot.name_receive_target.display.starts_with("rs1"));
16135        assert_eq!(
16136            snapshot.name_receive_target.display,
16137            snapshot.receive_target.display
16138        );
16139        assert!(!config.value_operations_enabled);
16140        assert!(!config.settlement_enabled);
16141        assert_eq!(runtime.backend.snapshot_calls.load(Ordering::SeqCst), 1);
16142        assert_eq!(runtime.backend.tip_calls.load(Ordering::SeqCst), 0);
16143        assert!(runtime.backend.confirmed_calls.load(Ordering::SeqCst) > 0);
16144        assert!(runtime.backend.mempool_calls.load(Ordering::SeqCst) > 0);
16145
16146        store
16147            .with_store(|wallet| {
16148                let account = wallet
16149                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))?
16150                    .ok_or(StoreError::CorruptMetadata)?;
16151                assert!(account.value.shakedex_scan_complete);
16152                assert!(!account.value.shakedex_scan_in_progress);
16153                let recovery = wallet
16154                    .hns_recovery_state::<HnsRecoveryState>(&recovery_entity_id(&config))?
16155                    .ok_or(StoreError::CorruptMetadata)?;
16156                assert_eq!(recovery.value.last_tip, Some(snapshot.binding.chain.tip));
16157                assert_eq!(recovery.value.last_reconciled_unix, 100);
16158                Ok(())
16159            })
16160            .expect("authenticated read commit");
16161    }
16162
16163    #[test]
16164    fn direct_light_watch_set_is_complete_public_and_bound_to_the_selected_account() {
16165        let (store, config) = production_followup_read_store();
16166        let watch_set = store
16167            .try_with_store(|wallet| derive_hns_light_watch_set(wallet, &config))
16168            .expect("derive local direct-light watch set");
16169        // One external and one internal account-zero branch plus the
16170        // independent Shakedex branch are installed before a peer scan.
16171        assert_eq!(watch_set.scripts.len(), 3);
16172        assert!(watch_set.name_hashes.is_empty());
16173        assert!(
16174            watch_set
16175                .scripts
16176                .iter()
16177                .all(|script| script.version == 0 && matches!(script.hash.len(), 20 | 32))
16178        );
16179
16180        let mut other = config.clone();
16181        other.account_id = AccountId::new([77; 16]);
16182        assert!(matches!(
16183            store.try_with_store(|wallet| derive_hns_light_watch_set(wallet, &other)),
16184            Err(HnsWalletError::AccountConfigurationMismatch)
16185        ));
16186    }
16187
16188    #[test]
16189    fn direct_light_watch_set_covers_the_normalized_recovery_frontier() {
16190        let (store, config) = production_followup_read_store();
16191        store
16192            .with_store_mut(|wallet| {
16193                let stored = wallet
16194                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))?
16195                    .ok_or(StoreError::CorruptMetadata)?;
16196                let mut account = stored.value;
16197                // Model a durable recovery frontier that has advanced beyond
16198                // the last persisted scan end. The direct index must include
16199                // the normalized successor script before peer scanning starts.
16200                account.next_shakedex_index = 1;
16201                account.shakedex_scan_end = 0;
16202                wallet.save_wallet_account(
16203                    &account_entity_id(&config),
16204                    stored.revision,
16205                    &account,
16206                    100,
16207                )?;
16208                Ok(())
16209            })
16210            .expect("persist normalized direct-light fixture");
16211
16212        let watch_set = store
16213            .try_with_store(|wallet| derive_hns_light_watch_set(wallet, &config))
16214            .expect("derive normalized direct-light watch set");
16215        let expected_scripts = store
16216            .try_with_store(|wallet| {
16217                let stored = wallet
16218                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))?
16219                    .ok_or(HnsWalletError::StaleAccountRead)?;
16220                let mut scan_account = stored.value;
16221                let allocated_next = scan_account.next_shakedex_index;
16222                normalize_restore_scan_account(&mut scan_account, allocated_next)?;
16223                Ok::<BTreeSet<WalletAddressKey>, HnsWalletError>(
16224                    [
16225                        derive_restore_addresses(wallet, &scan_account, KeyRole::HnsCoin)?,
16226                        derive_restore_addresses(wallet, &scan_account, KeyRole::HnsShakedex)?,
16227                    ]
16228                    .into_iter()
16229                    .flatten()
16230                    .map(|address| WalletAddressKey {
16231                        version: 0,
16232                        hash: address.program,
16233                    })
16234                    .collect::<BTreeSet<_>>(),
16235                )
16236            })
16237            .expect("derive normalized recovery scripts");
16238        assert_eq!(
16239            watch_set.scripts.iter().cloned().collect::<BTreeSet<_>>(),
16240            expected_scripts
16241        );
16242        assert_eq!(watch_set.scripts.len(), 4);
16243    }
16244
16245    #[test]
16246    fn name_history_advances_the_canonical_receive_target() {
16247        let (store, config) = production_followup_read_store();
16248        let account = store
16249            .with_store(|wallet| {
16250                wallet
16251                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))?
16252                    .map(|stored| stored.value)
16253                    .ok_or(StoreError::CorruptMetadata)
16254            })
16255            .expect("persisted scan account");
16256        let used_receive = store
16257            .try_with_store(|wallet| {
16258                derive_restore_addresses(wallet, &account, KeyRole::HnsCoin).map(|addresses| {
16259                    addresses
16260                        .into_iter()
16261                        .find(|address| address.derivation.change == 0)
16262                        .expect("initial external branch")
16263                })
16264            })
16265            .expect("derive used receive target");
16266        assert_eq!(used_receive.derivation.index, 0);
16267
16268        let backend = ProductionFollowupReadBackend::new(
16269            store.clone(),
16270            &config,
16271            ProductionFollowupReadFault::Healthy,
16272        )
16273        .with_name_history_program(used_receive.program.clone());
16274        let binding = ProductionFollowupReadBackend::binding();
16275        let scan =
16276            scan_restore_snapshot(&backend, account, binding.tip, Some(binding), |candidate| {
16277                store.try_with_store(|wallet| {
16278                    Ok([
16279                        derive_restore_addresses(wallet, candidate, KeyRole::HnsCoin)?,
16280                        derive_restore_addresses(wallet, candidate, KeyRole::HnsShakedex)?,
16281                    ])
16282                })
16283            })
16284            .expect("scan name history and extend the trailing gap");
16285
16286        assert_eq!(scan.account.last_used_external, Some(0));
16287        assert_eq!(scan.account.next_receive_index, 1);
16288        assert!(scan.account.external_scan_end >= 1);
16289        let target = hns_read_name_receive_target(&scan.account, &scan.addresses)
16290            .expect("post-scan name receive target");
16291        let post_scan_address = scan
16292            .addresses
16293            .iter()
16294            .find(|address| {
16295                address.derivation.role == KeyRole::HnsCoin
16296                    && address.derivation.change == 0
16297                    && address.derivation.index == scan.account.next_receive_index
16298            })
16299            .expect("derived post-scan name address");
16300        assert_eq!(target.derivation_index, 1);
16301        assert_eq!(target.display, post_scan_address.address);
16302        assert_ne!(target.display, used_receive.address);
16303    }
16304
16305    #[test]
16306    fn zero_value_incoming_transfer_advances_canonical_receive_high_water() {
16307        let (store, config) = production_followup_read_store();
16308        let account = store
16309            .with_store(|wallet| {
16310                wallet
16311                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))?
16312                    .map(|stored| stored.value)
16313                    .ok_or(StoreError::CorruptMetadata)
16314            })
16315            .expect("incoming account");
16316        let recipient = store
16317            .try_with_store(|wallet| {
16318                derive_restore_addresses(wallet, &account, KeyRole::HnsCoin).map(|addresses| {
16319                    addresses
16320                        .into_iter()
16321                        .find(|address| address.derivation.change == 0)
16322                        .expect("name recipient")
16323                })
16324            })
16325            .expect("derive incoming recipient");
16326        let candidate = zero_value_incoming_candidate(&recipient);
16327        assert_eq!(candidate.transfer_coin.value.get(), 0);
16328        assert_ne!(candidate.transfer_coin.address.hash, recipient.program);
16329        let selector = HnsExistingAccountSelector::new(store.clone(), config.clone())
16330            .expect("incoming selector");
16331        let backend = ProductionFollowupReadBackend::new(
16332            store.clone(),
16333            &config,
16334            ProductionFollowupReadFault::Healthy,
16335        )
16336        .with_incoming_candidate(candidate.clone());
16337        let runtime =
16338            HnsAccountReadRuntime::new(backend, ProductionFollowupClock, store.clone(), selector)
16339                .expect("incoming runtime");
16340
16341        let snapshot = runtime.synchronize().expect("incoming reconciliation");
16342        assert_eq!(snapshot.balance, Amount::new(WalletAsset::Hns, 0));
16343        assert!(snapshot.transactions.is_empty());
16344        assert!(snapshot.known_names.is_empty());
16345        assert_eq!(snapshot.name_receive_target.derivation_index, 1);
16346        store
16347            .with_store(|wallet| {
16348                let account = wallet
16349                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))?
16350                    .ok_or(StoreError::CorruptMetadata)?;
16351                assert_eq!(account.value.last_used_external, Some(0));
16352                assert_eq!(account.value.next_receive_index, 1);
16353                let coins = wallet.list_entities_by_id_prefix::<TrackedHnsCoin>(
16354                    EntityKind::HnsUtxo,
16355                    &account_entity_prefix(&config),
16356                    MAX_WALLET_COINS,
16357                )?;
16358                let names = wallet.list_entities_by_id_prefix::<KnownName>(
16359                    EntityKind::KnownName,
16360                    &account_entity_prefix(&config),
16361                    MAX_HISTORY_RESULTS,
16362                )?;
16363                assert!(coins.is_empty());
16364                assert!(names.is_empty());
16365                assert!(
16366                    wallet
16367                        .list_entities_by_id_prefix::<DerivedHnsAddress>(
16368                            EntityKind::DerivedAddress,
16369                            &account_entity_prefix(&config),
16370                            MAX_RESTORE_SCRIPTS_PER_QUERY,
16371                        )?
16372                        .iter()
16373                        .any(|stored| {
16374                            stored.value.derivation == recipient.derivation && stored.value.used
16375                        })
16376                );
16377                Ok(())
16378            })
16379            .expect("incoming high-water commit");
16380    }
16381
16382    #[test]
16383    fn incoming_transfer_to_payment_receive_advances_external_high_water() {
16384        let (store, config) = production_followup_read_store();
16385        let account = store
16386            .with_store(|wallet| {
16387                wallet
16388                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))?
16389                    .map(|stored| stored.value)
16390                    .ok_or(StoreError::CorruptMetadata)
16391            })
16392            .expect("payment-recipient account");
16393        let recipient = store
16394            .try_with_store(|wallet| {
16395                derive_restore_addresses(wallet, &account, KeyRole::HnsCoin).map(|addresses| {
16396                    addresses
16397                        .into_iter()
16398                        .find(|address| address.derivation.change == 0)
16399                        .expect("external payment recipient")
16400                })
16401            })
16402            .expect("derive payment recipient");
16403        let candidate = zero_value_incoming_candidate(&recipient);
16404        let selector = HnsExistingAccountSelector::new(store.clone(), config.clone())
16405            .expect("payment-recipient selector");
16406        let backend = ProductionFollowupReadBackend::new(
16407            store.clone(),
16408            &config,
16409            ProductionFollowupReadFault::Healthy,
16410        )
16411        .with_incoming_candidate(candidate);
16412        let runtime =
16413            HnsAccountReadRuntime::new(backend, ProductionFollowupClock, store.clone(), selector)
16414                .expect("payment-recipient runtime");
16415
16416        let snapshot = runtime
16417            .synchronize()
16418            .expect("payment-recipient incoming reconciliation");
16419        assert_eq!(snapshot.balance, Amount::new(WalletAsset::Hns, 0));
16420        assert!(snapshot.known_names.is_empty());
16421        assert_eq!(snapshot.receive_target.derivation_index, 1);
16422        assert_eq!(snapshot.name_receive_target.derivation_index, 1);
16423        assert_eq!(
16424            snapshot.name_receive_target.display,
16425            snapshot.receive_target.display
16426        );
16427        store
16428            .with_store(|wallet| {
16429                let account = wallet
16430                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))?
16431                    .ok_or(StoreError::CorruptMetadata)?;
16432                assert_eq!(account.value.last_used_external, Some(0));
16433                assert_eq!(account.value.next_receive_index, 1);
16434                Ok(())
16435            })
16436            .expect("payment-recipient high-water commit");
16437    }
16438
16439    #[test]
16440    fn incoming_transfer_pagination_supports_more_than_128_nonempty_receive_scripts() {
16441        let (store, config) = production_followup_read_store();
16442        let mut account = store
16443            .with_store(|wallet| {
16444                wallet
16445                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))?
16446                    .map(|stored| stored.value)
16447                    .ok_or(StoreError::CorruptMetadata)
16448            })
16449            .expect("pagination account");
16450        account.external_scan_end = 128;
16451        account.internal_scan_end = 0;
16452        let addresses = store
16453            .try_with_store(|wallet| derive_restore_addresses(wallet, &account, KeyRole::HnsCoin))
16454            .expect("derive receive scripts")
16455            .into_iter()
16456            .filter(|address| address.derivation.change == 0)
16457            .collect::<Vec<_>>();
16458        assert_eq!(addresses.len(), 129);
16459        let candidates = addresses
16460            .iter()
16461            .enumerate()
16462            .map(|(index, address)| {
16463                zero_value_incoming_candidate_at(
16464                    address,
16465                    u32::try_from(index).expect("candidate index"),
16466                )
16467            })
16468            .collect();
16469        let (scripts, index_remap) = sorted_restore_scripts(&addresses).expect("sorted scripts");
16470        let backend = ProductionFollowupReadBackend::new(
16471            store,
16472            &config,
16473            ProductionFollowupReadFault::Healthy,
16474        )
16475        .with_incoming_candidates(candidates);
16476        let derivations = load_incoming_transfer_derivations(
16477            &backend,
16478            &scripts,
16479            &index_remap,
16480            ProductionFollowupReadBackend::binding(),
16481        )
16482        .expect("129 nonempty incoming pages");
16483        assert_eq!(derivations.len(), 129);
16484        assert_eq!(derivations.first(), Some(&0));
16485        assert_eq!(derivations.last(), Some(&128));
16486    }
16487
16488    #[test]
16489    fn zero_value_wallet_finalize_requires_exact_active_coin_before_name_insert() {
16490        let (store, config) = production_followup_read_store();
16491        let account = store
16492            .with_store(|wallet| {
16493                wallet
16494                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))?
16495                    .map(|stored| stored.value)
16496                    .ok_or(StoreError::CorruptMetadata)
16497            })
16498            .expect("FINALIZE account");
16499        let recipient = store
16500            .try_with_store(|wallet| {
16501                derive_restore_addresses(wallet, &account, KeyRole::HnsCoin).map(|addresses| {
16502                    addresses
16503                        .into_iter()
16504                        .find(|address| address.derivation.change == 0)
16505                        .expect("FINALIZE recipient")
16506                })
16507            })
16508            .expect("derive FINALIZE recipient");
16509        let (name_hash, coin, evidence) = zero_value_finalize_owner(&recipient);
16510        assert_eq!(coin.value.get(), 0);
16511        assert_eq!(
16512            HnsInputCoinEvidence::from_canonical_coin(&coin)
16513                .expect("zero FINALIZE input evidence")
16514                .to_canonical_coin()
16515                .expect("zero FINALIZE canonical input"),
16516            coin
16517        );
16518        let script = WalletAddressKey {
16519            version: 0,
16520            hash: recipient.program.clone(),
16521        };
16522        let selector = HnsExistingAccountSelector::new(store.clone(), config.clone())
16523            .expect("FINALIZE selector");
16524        let backend = ProductionFollowupReadBackend::new(
16525            store.clone(),
16526            &config,
16527            ProductionFollowupReadFault::Healthy,
16528        )
16529        .with_finalize_owner(script, coin.clone(), name_hash, evidence);
16530        let runtime =
16531            HnsAccountReadRuntime::new(backend, ProductionFollowupClock, store.clone(), selector)
16532                .expect("FINALIZE runtime");
16533
16534        let snapshot = runtime.synchronize().expect("FINALIZE reconciliation");
16535        assert_eq!(snapshot.balance, Amount::new(WalletAsset::Hns, 0));
16536        assert_eq!(snapshot.known_names.len(), 1);
16537        assert_eq!(snapshot.known_names[0].name, b"alpha");
16538        assert_eq!(snapshot.known_names[0].name_hash, name_hash);
16539        assert_eq!(snapshot.known_names[0].proof_state, None);
16540        assert!(matches!(
16541            snapshot.known_names[0].ownership_status,
16542            NameOwnershipStatus::WalletOwned { derivation }
16543                if derivation == recipient.derivation
16544        ));
16545        assert_eq!(snapshot.name_receive_target.derivation_index, 1);
16546        let refreshed = runtime
16547            .synchronize()
16548            .expect("persisted FINALIZE rediscovery");
16549        assert_eq!(refreshed.known_names.len(), 1);
16550        assert_eq!(refreshed.known_names[0].name_hash, name_hash);
16551        store
16552            .with_store(|wallet| {
16553                let names = wallet.list_entities_by_id_prefix::<KnownName>(
16554                    EntityKind::KnownName,
16555                    &account_entity_prefix(&config),
16556                    MAX_HISTORY_RESULTS,
16557                )?;
16558                let coins = wallet.list_entities_by_id_prefix::<TrackedHnsCoin>(
16559                    EntityKind::HnsUtxo,
16560                    &account_entity_prefix(&config),
16561                    MAX_WALLET_COINS,
16562                )?;
16563                assert_eq!(names.len(), 1);
16564                assert_eq!(names[0].revision, 2);
16565                assert_eq!(coins.len(), 1);
16566                assert!(coins[0].value.coin.value.is_zero());
16567                assert_eq!(
16568                    coins[0].value.to_canonical_coin().expect("zero name Coin"),
16569                    coin
16570                );
16571                Ok(())
16572            })
16573            .expect("revision-zero name insertion");
16574    }
16575
16576    #[test]
16577    fn finalized_name_on_payment_receive_is_discovered_and_owned() {
16578        let (store, config) = production_followup_read_store();
16579        let account = store
16580            .with_store(|wallet| {
16581                wallet
16582                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))?
16583                    .map(|stored| stored.value)
16584                    .ok_or(StoreError::CorruptMetadata)
16585            })
16586            .expect("payment FINALIZE account");
16587        let recipient = store
16588            .try_with_store(|wallet| {
16589                derive_restore_addresses(wallet, &account, KeyRole::HnsCoin).map(|addresses| {
16590                    addresses
16591                        .into_iter()
16592                        .find(|address| address.derivation.change == 0)
16593                        .expect("payment FINALIZE recipient")
16594                })
16595            })
16596            .expect("derive payment FINALIZE recipient");
16597        let (name_hash, coin, evidence) = zero_value_finalize_owner(&recipient);
16598        let selector = HnsExistingAccountSelector::new(store.clone(), config.clone())
16599            .expect("payment FINALIZE selector");
16600        let backend = ProductionFollowupReadBackend::new(
16601            store.clone(),
16602            &config,
16603            ProductionFollowupReadFault::Healthy,
16604        )
16605        .with_finalize_owner(
16606            WalletAddressKey {
16607                version: 0,
16608                hash: recipient.program.clone(),
16609            },
16610            coin,
16611            name_hash,
16612            evidence,
16613        );
16614        let runtime = HnsAccountReadRuntime::new(backend, ProductionFollowupClock, store, selector)
16615            .expect("payment FINALIZE runtime");
16616
16617        let snapshot = runtime
16618            .synchronize()
16619            .expect("payment FINALIZE reconciliation");
16620        assert_eq!(snapshot.known_names.len(), 1);
16621        assert_eq!(snapshot.known_names[0].name, b"alpha");
16622        assert!(matches!(
16623            snapshot.known_names[0].ownership_status,
16624            NameOwnershipStatus::WalletOwned { derivation }
16625                if derivation == recipient.derivation
16626        ));
16627        assert_eq!(snapshot.receive_target.derivation_index, 1);
16628        assert_eq!(snapshot.name_receive_target.derivation_index, 1);
16629        assert_eq!(
16630            snapshot.name_receive_target.display,
16631            snapshot.receive_target.display
16632        );
16633    }
16634
16635    #[test]
16636    fn mismatched_active_finalize_coin_fails_before_name_or_coin_commit() {
16637        let (store, config) = production_followup_read_store();
16638        let account = store
16639            .with_store(|wallet| {
16640                wallet
16641                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&config))?
16642                    .map(|stored| stored.value)
16643                    .ok_or(StoreError::CorruptMetadata)
16644            })
16645            .expect("mismatch account");
16646        let recipient = store
16647            .try_with_store(|wallet| {
16648                derive_restore_addresses(wallet, &account, KeyRole::HnsCoin).map(|addresses| {
16649                    addresses
16650                        .into_iter()
16651                        .find(|address| address.derivation.change == 0)
16652                        .expect("mismatch recipient")
16653                })
16654            })
16655            .expect("derive mismatch recipient");
16656        let (name_hash, coin, mut evidence) = zero_value_finalize_owner(&recipient);
16657        evidence.owner_coin.address =
16658            Address::new(0, vec![0xb1; 20]).expect("mismatched active address");
16659        let selector = HnsExistingAccountSelector::new(store.clone(), config.clone())
16660            .expect("mismatch selector");
16661        let backend = ProductionFollowupReadBackend::new(
16662            store.clone(),
16663            &config,
16664            ProductionFollowupReadFault::Healthy,
16665        )
16666        .with_finalize_owner(
16667            WalletAddressKey {
16668                version: 0,
16669                hash: recipient.program,
16670            },
16671            coin,
16672            name_hash,
16673            evidence,
16674        );
16675        let runtime =
16676            HnsAccountReadRuntime::new(backend, ProductionFollowupClock, store.clone(), selector)
16677                .expect("mismatch runtime");
16678        assert!(matches!(
16679            runtime.synchronize(),
16680            Err(HnsWalletError::InvalidEvidence)
16681        ));
16682        store
16683            .with_store(|wallet| {
16684                assert!(
16685                    wallet
16686                        .list_entities_by_id_prefix::<KnownName>(
16687                            EntityKind::KnownName,
16688                            &account_entity_prefix(&config),
16689                            MAX_HISTORY_RESULTS,
16690                        )?
16691                        .is_empty()
16692                );
16693                assert!(
16694                    wallet
16695                        .list_entities_by_id_prefix::<TrackedHnsCoin>(
16696                            EntityKind::HnsUtxo,
16697                            &account_entity_prefix(&config),
16698                            MAX_WALLET_COINS,
16699                        )?
16700                        .is_empty()
16701                );
16702                Ok(())
16703            })
16704            .expect("no mismatched authority commit");
16705    }
16706
16707    #[test]
16708    fn production_followup_account_reads_reject_mainnet_genesis_for_regtest_account() {
16709        let (store, config) = production_followup_read_store();
16710        assert_eq!(config.network, HnsNetwork::Regtest);
16711        let runtime = production_followup_read_runtime(
16712            store,
16713            config,
16714            ProductionFollowupReadFault::WrongNetwork,
16715        );
16716        assert!(matches!(
16717            runtime.synchronize(),
16718            Err(HnsWalletError::InvalidEvidence)
16719        ));
16720        assert_eq!(runtime.backend.snapshot_calls.load(Ordering::SeqCst), 1);
16721        assert_eq!(runtime.backend.tip_calls.load(Ordering::SeqCst), 0);
16722        assert_eq!(runtime.backend.confirmed_calls.load(Ordering::SeqCst), 0);
16723        assert_eq!(runtime.backend.mempool_calls.load(Ordering::SeqCst), 0);
16724    }
16725
16726    #[test]
16727    fn production_followup_account_reads_fail_closed_on_stale_restart_account_and_lock_fences() {
16728        let (stale_store, stale_config) = production_followup_read_store();
16729        let stale = production_followup_read_runtime(
16730            stale_store.clone(),
16731            stale_config.clone(),
16732            ProductionFollowupReadFault::StaleChain,
16733        );
16734        assert!(matches!(
16735            stale.synchronize(),
16736            Err(HnsWalletError::StaleNodeSnapshot)
16737        ));
16738        stale_store
16739            .with_store(|wallet| {
16740                let account = wallet
16741                    .wallet_account::<HnsAccountRecord>(&account_entity_id(&stale_config))?
16742                    .ok_or(StoreError::CorruptMetadata)?;
16743                assert!(account.value.shakedex_scan_in_progress);
16744                assert!(!account.value.shakedex_scan_complete);
16745                Ok(())
16746            })
16747            .expect("durable stale scan fence");
16748        drop(stale);
16749        let recovered = production_followup_read_runtime(
16750            stale_store,
16751            stale_config,
16752            ProductionFollowupReadFault::Healthy,
16753        );
16754        recovered
16755            .synchronize()
16756            .expect("fresh process recovers the durable scan fence");
16757
16758        let (restart_store, restart_config) = production_followup_read_store();
16759        let restarted_node = production_followup_read_runtime(
16760            restart_store,
16761            restart_config,
16762            ProductionFollowupReadFault::RestartedMempool,
16763        );
16764        assert!(matches!(
16765            restarted_node.synchronize(),
16766            Err(HnsWalletError::StaleNodeSnapshot)
16767        ));
16768
16769        let (changed_store, changed_config) = production_followup_read_store();
16770        let changed_account = production_followup_read_runtime(
16771            changed_store,
16772            changed_config,
16773            ProductionFollowupReadFault::ChangedAccount,
16774        );
16775        assert!(matches!(
16776            changed_account.synchronize(),
16777            Err(HnsWalletError::StaleAccountRead)
16778        ));
16779
16780        let (locked_store, locked_config) = production_followup_read_store();
16781        let locked = production_followup_read_runtime(
16782            locked_store.clone(),
16783            locked_config,
16784            ProductionFollowupReadFault::LockedStore,
16785        );
16786        assert!(matches!(
16787            locked.synchronize(),
16788            Err(HnsWalletError::StoreLocked)
16789        ));
16790        assert!(locked_store.is_locked().expect("locked read store"));
16791
16792        let (selector_store, selector_config) = production_followup_read_store();
16793        let selector = HnsExistingAccountSelector::new(selector_store, selector_config.clone())
16794            .expect("selector authority");
16795        let (different_store, _) = production_followup_read_store();
16796        assert!(matches!(
16797            HnsAccountReadRuntime::new(
16798                ProductionFollowupReadBackend::new(
16799                    different_store.clone(),
16800                    &selector_config,
16801                    ProductionFollowupReadFault::Healthy,
16802                ),
16803                ProductionFollowupClock,
16804                different_store,
16805                selector,
16806            ),
16807            Err(HnsWalletError::StoreAuthorityMismatch)
16808        ));
16809    }
16810
16811    #[test]
16812    fn persisted_flagged_accounts_reject_ordinary_reads_but_allow_closed_lifecycle() {
16813        for (network, value_operations_enabled, settlement_enabled) in [
16814            (HnsNetwork::Mainnet, true, false),
16815            (HnsNetwork::Mainnet, false, true),
16816            (HnsNetwork::Testnet, true, false),
16817            (HnsNetwork::Testnet, false, true),
16818            (HnsNetwork::Testnet, true, true),
16819        ] {
16820            let mut config = test_runtime_config();
16821            config.network = network;
16822            config.birthday_height = 0;
16823            config.restore_lookahead = 1;
16824            config.minimum_confirmations = 1;
16825            config.value_operations_enabled = value_operations_enabled;
16826            config.settlement_enabled = settlement_enabled;
16827            let store = production_followup_read_store_for_config(config.clone());
16828
16829            config
16830                .validate_structure()
16831                .expect("flagged account structure remains valid");
16832            config
16833                .validate()
16834                .expect("qualified runtime accepts the persisted value flags");
16835            assert!(matches!(
16836                HnsExistingAccountSelector::new(store.clone(), config.clone()),
16837                Err(HnsWalletError::MainnetDisabled)
16838                    | Err(HnsWalletError::RuntimeIntegrationUnavailable)
16839            ));
16840            let lifecycle =
16841                HnsExistingAccountSelector::new_lifecycle(store.clone(), config.clone())
16842                    .expect("structure-only lifecycle selector");
16843            assert_eq!(
16844                lifecycle
16845                    .selected_account()
16846                    .expect("exact lifecycle account")
16847                    .config,
16848                config
16849            );
16850        }
16851    }
16852
16853    #[test]
16854    fn persisted_flagged_recovery_reads_reject_missing_mismatch_and_live_fence_changes() {
16855        let recovery_config = || {
16856            let mut config = test_runtime_config();
16857            config.network = HnsNetwork::Testnet;
16858            config.birthday_height = 0;
16859            config.restore_lookahead = 1;
16860            config.minimum_confirmations = 1;
16861            config.value_operations_enabled = true;
16862            config
16863        };
16864
16865        let missing_config = recovery_config();
16866        let missing_store = SharedWalletStore::new(
16867            WalletStore::create(":memory:", PRODUCTION_FOLLOWUP_PASSPHRASE)
16868                .expect("create missing-account store"),
16869        );
16870        let missing = production_followup_recovery_read_runtime(
16871            missing_store,
16872            missing_config,
16873            ProductionFollowupReadFault::Healthy,
16874        );
16875        assert!(matches!(
16876            missing.selected_account(),
16877            Err(HnsWalletError::AccountConfigurationMismatch)
16878        ));
16879
16880        let config = recovery_config();
16881        let mismatch_store = production_followup_read_store_for_config(config.clone());
16882        let mut mismatched = config.clone();
16883        mismatched.value_operations_enabled = false;
16884        mismatched.settlement_enabled = true;
16885        let mismatch = production_followup_recovery_read_runtime(
16886            mismatch_store,
16887            mismatched,
16888            ProductionFollowupReadFault::Healthy,
16889        );
16890        assert!(matches!(
16891            mismatch.selected_account(),
16892            Err(HnsWalletError::AccountConfigurationMismatch)
16893        ));
16894
16895        for fault in [
16896            ProductionFollowupReadFault::StaleChain,
16897            ProductionFollowupReadFault::RestartedMempool,
16898            ProductionFollowupReadFault::ChangedAccount,
16899            ProductionFollowupReadFault::LockedStore,
16900        ] {
16901            let config = recovery_config();
16902            let store = production_followup_read_store_for_config(config.clone());
16903            let runtime = production_followup_recovery_read_runtime(store, config, fault);
16904            let result = runtime.synchronize();
16905            match fault {
16906                ProductionFollowupReadFault::StaleChain
16907                | ProductionFollowupReadFault::RestartedMempool => {
16908                    assert!(matches!(result, Err(HnsWalletError::StaleNodeSnapshot)));
16909                }
16910                ProductionFollowupReadFault::ChangedAccount => {
16911                    assert!(matches!(result, Err(HnsWalletError::StaleAccountRead)));
16912                }
16913                ProductionFollowupReadFault::LockedStore => {
16914                    assert!(matches!(result, Err(HnsWalletError::StoreLocked)));
16915                }
16916                _ => unreachable!("the recovery fence matrix contains only fault cases"),
16917            }
16918        }
16919    }
16920
16921    #[test]
16922    fn hns_shakedex_role_separation_has_stable_recovery_vector() {
16923        let seed = [7_u8; 64];
16924        let atomic_swap = derive_secret(
16925            &seed,
16926            DerivationReference {
16927                role: KeyRole::HnsAtomicSwap,
16928                account: 0,
16929                change: 0,
16930                index: 0,
16931            },
16932        )
16933        .expect("atomic-swap key");
16934        let shakedex = derive_secret(
16935            &seed,
16936            DerivationReference {
16937                role: KeyRole::HnsShakedex,
16938                account: 0,
16939                change: 0,
16940                index: 0,
16941            },
16942        )
16943        .expect("Shakedex key");
16944        assert_ne!(*atomic_swap, *shakedex);
16945        assert_eq!(
16946            hex::encode(shakedex.as_slice()),
16947            "c1f343c505fbf40e41d41b4ad3571fb93c49f7687d197568ab901678a44c4d49"
16948        );
16949        let shakedex_signing =
16950            SigningKey::from_slice(shakedex.as_slice()).expect("Shakedex signing key");
16951        let shakedex_public: [u8; 33] = shakedex_signing
16952            .verifying_key()
16953            .to_sec1_point(true)
16954            .as_bytes()
16955            .try_into()
16956            .expect("compressed Shakedex key");
16957        assert_eq!(
16958            hex::encode(shakedex_public),
16959            "02479c879e5f2e087a998d5fa57ad1720ab8d56171b13f191beae222ddae20fb4a"
16960        );
16961        let shakedex_program = lock_script_hash(&shakedex_public);
16962        assert_eq!(
16963            hex::encode(shakedex_program),
16964            "b1194ad181a74b263cc84b8e80ca9078e32c15e72128c3473700f23c46ed9cca"
16965        );
16966        assert_eq!(
16967            encode_v0_address(HnsNetwork::Regtest, &shakedex_program)
16968                .expect("Shakedex lock address"),
16969            "rs1qkyv545vp5a9jv0xgfw8gpj5s0r3jc908yy5vx3ehqrerc3hdnn9qj0j5a4"
16970        );
16971        let coin = derive_hsd_bip44_secret(
16972            &seed,
16973            HnsNetwork::Mainnet,
16974            DerivationReference {
16975                role: KeyRole::HnsCoin,
16976                account: 0,
16977                change: 0,
16978                index: 0,
16979            },
16980        )
16981        .expect("canonical account-zero coin key");
16982        let signing = SigningKey::from_slice(coin.as_slice()).expect("signing key");
16983        let public: [u8; 33] = VerifyingKey::from(&signing)
16984            .to_sec1_point(true)
16985            .as_bytes()
16986            .try_into()
16987            .expect("compressed key");
16988        assert!(
16989            receive_address(HnsNetwork::Mainnet, &public)
16990                .expect("mainnet")
16991                .starts_with("hs1")
16992        );
16993        assert!(
16994            receive_address(HnsNetwork::Regtest, &public)
16995                .expect("regtest")
16996                .starts_with("rs1")
16997        );
16998    }
16999
17000    #[test]
17001    fn native_htlc_locktime_preserves_hns_height_and_median_time_domains() {
17002        assert!(hns_locktime_is_valid(42));
17003        assert!(!hns_locktime_is_time(42).expect("height encoding"));
17004        assert!(hns_refund_locktime_mature(42, 42).expect("height maturity"));
17005        assert!(!hns_refund_locktime_mature(42, 41).expect("height immaturity"));
17006
17007        // HNS's high-bit time encoding stores 512-second units.  The local
17008        // header authority must use strict parent-MTP maturity, not wall time
17009        // and not a translated block height.
17010        let encoded_time = u64::from(LOCKTIME_FLAG | 2);
17011        assert!(hns_locktime_is_valid(encoded_time));
17012        assert!(hns_locktime_is_time(encoded_time).expect("time encoding"));
17013        assert!(!hns_refund_locktime_mature(encoded_time, 1_024).expect("time immaturity"));
17014        assert!(hns_refund_locktime_mature(encoded_time, 1_025).expect("time maturity"));
17015        assert!(!hns_locktime_is_valid(u64::from(LOCKTIME_FLAG)));
17016    }
17017
17018    #[test]
17019    fn only_unbroadcast_terminal_or_locally_expired_hns_locks_are_repreparable() {
17020        assert!(!settlement_lock_workflow_may_be_reprepared(
17021            HnsSettlementStage::Prepared,
17022            100,
17023            false,
17024            99,
17025        ));
17026        assert!(settlement_lock_workflow_may_be_reprepared(
17027            HnsSettlementStage::Prepared,
17028            100,
17029            false,
17030            100,
17031        ));
17032        for stage in [HnsSettlementStage::Cancelled, HnsSettlementStage::Expired] {
17033            assert!(settlement_lock_workflow_may_be_reprepared(
17034                stage, 100, false, 99,
17035            ));
17036            assert!(!settlement_lock_workflow_may_be_reprepared(
17037                stage, 100, true, 99,
17038            ));
17039        }
17040        for stage in [
17041            HnsSettlementStage::Broadcast,
17042            HnsSettlementStage::Mempool,
17043            HnsSettlementStage::Confirmed,
17044            HnsSettlementStage::Conflicted,
17045            HnsSettlementStage::RequiresRebroadcast,
17046        ] {
17047            assert!(!settlement_lock_workflow_may_be_reprepared(
17048                stage, 0, false, 100,
17049            ));
17050        }
17051    }
17052
17053    #[test]
17054    fn hns_redeem_status_starts_at_the_irreversible_checkpoint() {
17055        let config = test_runtime_config();
17056        let session_id = SessionId::new([31; 32]);
17057        let transaction = TransactionHash::new([32; 32]);
17058        let id = settlement_workflow_id(&config, session_id, HnsSettlementAction::Redeem);
17059        let mut store = WalletStore::create(":memory:", "redeem-status").expect("store");
17060        let mut state = HnsPreparedSettlement {
17061            wallet_id: config.wallet_id,
17062            account_id: config.account_id,
17063            workflow_id: id,
17064            session_id,
17065            action: HnsSettlementAction::Redeem,
17066            stage: HnsSettlementStage::Prepared,
17067            transaction,
17068            signed_transaction: vec![1],
17069            input_coins: Vec::new(),
17070            fee: BaseUnits::new(1),
17071            maximum_fee: BaseUnits::new(1),
17072            fee_quote: None,
17073            expires_at_unix: 200,
17074            terms: HnsSettlementTerms::Redeem {
17075                lock: VerifiedLock {
17076                    module: ModuleId::Handshake,
17077                    session_id,
17078                    funding_id: TransactionHash::new([33; 32]),
17079                    amount: Amount::new(WalletAsset::Hns, 100),
17080                    hashlock: ObjectHash::new([34; 32]),
17081                    absolute_timelock: 300,
17082                    confirmation_count: 2,
17083                    evidence_hash: ObjectHash::new([35; 32]),
17084                },
17085            },
17086            recovery_publication: None,
17087            broadcast_guard: None,
17088        };
17089        let revision = store
17090            .save_workflow(id, WorkflowKind::AtomicSwap, 0, &state, false, 100)
17091            .expect("reversible preparation");
17092        assert!(
17093            hns_redeem_submission(&store, &config, session_id)
17094                .expect("unapproved state")
17095                .is_none()
17096        );
17097        let revision = store
17098            .save_workflow(id, WorkflowKind::AtomicSwap, revision, &state, true, 101)
17099            .expect("durable broadcast checkpoint");
17100        assert_eq!(
17101            hns_redeem_submission(&store, &config, session_id)
17102                .expect("queued state")
17103                .expect("queued claim")
17104                .stage,
17105            HnsRedeemSubmissionStage::Queued
17106        );
17107        state.stage = HnsSettlementStage::Broadcast;
17108        let revision = store
17109            .save_workflow(id, WorkflowKind::AtomicSwap, revision, &state, true, 102)
17110            .expect("submitted checkpoint");
17111        assert_eq!(
17112            hns_redeem_submission(&store, &config, session_id).expect("submitted state"),
17113            Some(HnsRedeemSubmission {
17114                transaction,
17115                stage: HnsRedeemSubmissionStage::Submitted,
17116            })
17117        );
17118        state.stage = HnsSettlementStage::Confirmed;
17119        let revision = store
17120            .save_workflow(id, WorkflowKind::AtomicSwap, revision, &state, true, 103)
17121            .expect("confirmed checkpoint");
17122        assert_eq!(
17123            hns_redeem_submission(&store, &config, session_id)
17124                .expect("confirmed state")
17125                .expect("same claim")
17126                .stage,
17127            HnsRedeemSubmissionStage::Confirmed
17128        );
17129        state.stage = HnsSettlementStage::RequiresRebroadcast;
17130        store
17131            .save_workflow(id, WorkflowKind::AtomicSwap, revision, &state, true, 104)
17132            .expect("reorged checkpoint");
17133        assert_eq!(
17134            hns_redeem_submission(&store, &config, session_id)
17135                .expect("reorged state")
17136                .expect("same claim")
17137                .stage,
17138            HnsRedeemSubmissionStage::Queued
17139        );
17140        assert!(
17141            hns_redeem_submission(&store, &config, SessionId::new([36; 32]))
17142                .expect("different session")
17143                .is_none()
17144        );
17145    }
17146
17147    #[test]
17148    fn irreversible_hns_settlements_outlive_the_prepared_artifact_window() {
17149        assert_eq!(
17150            unobserved_settlement_stage(HnsSettlementStage::Prepared, false, 100, 100),
17151            (HnsSettlementStage::Expired, false)
17152        );
17153        assert!(!settlement_requires_chain_observation(
17154            HnsSettlementStage::Expired,
17155            false,
17156        ));
17157
17158        for stage in [
17159            HnsSettlementStage::Broadcast,
17160            HnsSettlementStage::Mempool,
17161            HnsSettlementStage::RequiresRebroadcast,
17162        ] {
17163            assert!(settlement_requires_chain_observation(stage, false));
17164            assert_eq!(
17165                unobserved_settlement_stage(stage, false, 100, 10_000),
17166                (HnsSettlementStage::RequiresRebroadcast, true)
17167            );
17168        }
17169
17170        // Wallets created by the preceding release may carry the historical
17171        // irreversible bit on a merely prepared artifact. Stage is the
17172        // authoritative submission checkpoint during migration: a Prepared
17173        // row can be observed, but absence must never promote it to an
17174        // automatic rebroadcast.
17175        assert!(settlement_requires_chain_observation(
17176            HnsSettlementStage::Prepared,
17177            true,
17178        ));
17179        assert_eq!(
17180            unobserved_settlement_stage(HnsSettlementStage::Prepared, true, 100, 10_000),
17181            (HnsSettlementStage::Expired, false)
17182        );
17183        assert_eq!(
17184            unobserved_settlement_stage(HnsSettlementStage::Expired, true, 100, 10_000),
17185            (HnsSettlementStage::RequiresRebroadcast, true),
17186            "a legacy terminal row that really retained an irreversible checkpoint remains recoverable"
17187        );
17188        for stage in [
17189            HnsSettlementStage::Confirmed,
17190            HnsSettlementStage::Conflicted,
17191        ] {
17192            assert!(!settlement_requires_chain_observation(stage, true));
17193            assert_eq!(
17194                unobserved_settlement_stage(stage, true, 100, 10_000),
17195                (stage, false)
17196            );
17197        }
17198    }
17199
17200    #[test]
17201    fn native_htlc_lock_uses_the_protocol_descriptor_script_without_translation() {
17202        let receiver = SigningKey::from_bytes((&[31_u8; 32]).into())
17203            .expect("receiver key")
17204            .verifying_key()
17205            .to_sec1_point(true);
17206        let refund = SigningKey::from_bytes((&[32_u8; 32]).into())
17207            .expect("refund key")
17208            .verifying_key()
17209            .to_sec1_point(true);
17210        let receiver: [u8; 33] = receiver.as_bytes().try_into().expect("receiver SEC1");
17211        let refund: [u8; 33] = refund.as_bytes().try_into().expect("refund SEC1");
17212        let descriptor = HnsHtlc {
17213            network: shakedex_network_binding(HnsNetwork::Regtest).expect("regtest network"),
17214            value: Dollarydoos::new(1_000),
17215            hashlock: [7; 32],
17216            receiver_public_key: receiver,
17217            refund_public_key: refund,
17218            refund_locktime: LOCKTIME_FLAG | 2,
17219        };
17220        assert_eq!(
17221            hns_htlc_script(
17222                ObjectHash::new(descriptor.hashlock),
17223                &descriptor.receiver_public_key,
17224                &descriptor.refund_public_key,
17225                u64::from(descriptor.refund_locktime),
17226            )
17227            .expect("wallet HTLC script"),
17228            descriptor.script().expect("protocol HTLC script"),
17229        );
17230    }
17231}