Read watch-only Bitcoin wallets into a preview

Closed
VL
13d ago
+3165-81

Superseded by #5672 in the native Bitcoin stack. Further review continues there on the same commit, aa2eb4bde. This PR preserves the earlier discussion. Feature tracker.

Latest review update. A slow read can finish across new blocks. Sure verifies the intervening blocks, refreshes wallet addresses they touched and rechecks pending payments. Discovery also covers deposits made between jobs. A reorganization restarts the configured gap scan and preserves the last published balance until the retry completes.

Summary

Part 3 of the split of #3753 agreed in https://github.com/we-promise/sure/pull/3753#issuecomment-6248037835. It builds on the Bitcoin public keys from part 2 (#4615).

This part reads a watch-only Bitcoin wallet, from one or more public addresses or a BIP84 account key, into a preview: balance, addresses in use and transactions. It doesn't change the account the wallet belongs to.

Data

  • bitcoin_wallet_accounts: one per Crypto account, tracking a BTC security. Statuses: discovering, preview, failed (and active, used from part 4).
  • bitcoin_wallet_sources: a public address or an account key (xpub/zpub). The key is encrypted at rest, so a key source requires Active Record encryption to be configured. A fingerprint shared by the xpub and zpub forms of the same key keeps it from being added twice.
  • bitcoin_wallet_addresses: addresses found for the wallet. An address belongs to at most one wallet per family.
  • bitcoin_wallet_transactions: the wallet's net movement per transaction, with confirmation state and whether it's still present on the chain.

Discovery (BitcoinWalletAccount::Discovery)

  • Derives receive and change addresses from the account key and scans each branch until it reaches the gap limit of unused addresses (20 by default, up to 1000). An address counts as used if it has any history, including spent addresses and mempool transactions.
  • Reads at most 200 addresses per job, saves the position and continues in a child sync.
  • Once discovery is complete, routine syncs re-check the next 20 addresses after the last used one on each branch, and the full gap is rescanned once a day.
  • A completed scan must contain the receive address the user entered, so a key from a different account is rejected instead of reading as an empty wallet.

Reading (BitcoinWalletAccount::Snapshot)

  • Reads used addresses and checks the block hash. When new blocks arrive, the reader follows their parent hashes, refreshes affected addresses and rechecks addresses with pending transactions. A reorganized or unverifiable chain triggers a full discovery retry.
  • Follows wallet addresses touched by the transactions it sees, so change received in a pending transaction is counted in the same read.
  • The balance is confirmed plus pending, in satoshis.
  • Two pending transactions spending the same output, or a mempool list that disagrees with the address summary, make the read retry instead of producing a wrong balance.

Sync (BitcoinWalletAccount::Syncer)

  • One reader per wallet, using a session advisory lock. No row lock or transaction is held during HTTP, so editing sources stays possible while a read is running.
  • If the wallet's sources change during a read, its result is dropped and another read follows.
  • Explorer errors and inconsistent reads are retried twice inside the same sync tree, a rate limit after a minute. When the retries run out, or on any other error, the wallet keeps its last complete balance, is marked failed, and a DebugLogEntry records the error class only, never keys or explorer payloads.
  • Syncable#sync_later gets the same coalescible_syncs hook as #4613 (an identical hunk). The wallet uses it so a source change made during a running read gets its own follow-up.

Shared code

  • Provider::MempoolSpace reads block metadata, paginated block transactions, transaction status, and wallet history that stops at a start date or a page budget and reports truncation.
  • Wallet addresses and the existing single-address wallets claim an address under the same advisory lock, and an address tracked by one can't be added by the other (Family#onchain_address_linked?, OnchainWalletItem::WalletLinker).
  • Account and OnchainWalletItem own their wallets (dependent: :destroy), and the family data reset removes them through the existing provider-item path.
  • Sync.for_family includes a wallet's syncs wherever its account's syncs are visible. The family data reset now deletes them instead of leaving rows for a deleted wallet, and the family shows as syncing while a wallet reads. Once part 4 makes wallet reads children of the on-chain connection's sync, leaving them out would also break the reset on the syncs.parent_id foreign key.

Not in this PR

Nothing in the app creates a wallet yet, and a wallet doesn't publish into its account. Connecting a wallet, the provider link, recording movements, the cash anchor from #4613 and the hourly sync come in part 4; the setup UI behind the preview flag in part 5.

baseline_at, baseline_block_height and needs_reconciliation are set when a wallet is connected in part 4. Until then a read skips confirmed history and marks every transaction it sees as baseline. The migration is the one from #3753, unchanged, columns included, so an install already running #3753 has nothing new to migrate.

Validation

  • Wallet tests from #3753 that don't need a connected wallet: discovery (10), reading (8), sync (11), sync lifecycle (9), sources (3). Three sync tests that checked ledger entries now check the wallet's transaction rows instead (RBF, a dropped pending deposit, a reorg).
  • New test/models/provider/mempool_space_test.rb: wallet history deduplication, stopping at the start date, and truncation at the page budget.
  • New test/models/bitcoin_wallet_account_test.rb: a wallet only tracks a manual Crypto account of its own family, and its addresses can't be added as single-address wallets in that family. The reset test also checks that the wallet's syncs are gone.
  • db/schema.rb loads and dumps back unchanged, apart from how Postgres prints check constraints, which differs the same way for existing tables.
  • Rails suite on the rebased head passed with 18,605 tests, 113,948 assertions, 9 skips, zero failures or errors.
  • RuboCop: no offenses.

Summary by cubic

Reads watch-only Bitcoin wallets into a preview — balance, used addresses, and confirmed/pending transactions — from public addresses or a BIP84 account key, without changing the account the wallet belongs to. Adds cash anchors: a dated valuation that records only an account's cash component, letting imported accounts keep forward accounting and holding history without discarding earlier imported data.

Wallet reading

  • Four new tables: bitcoin_wallet_accounts, bitcoin_wallet_sources, bitcoin_wallet_addresses, and bitcoin_wallet_transactions. BIP84 keys are encrypted at rest, so key sources require Active Record encryption.
  • Discovery derives receive and change addresses, scans each branch to its gap limit (default 20, max 1000) in bounded 200-address jobs with saved checkpoints, and rescans the lookahead routinely and the full gap daily. A source's kind, key, receive address, and fingerprint are read-only once saved; replacing a key means removing and re-adding the source.
  • Reads run at a stable chain tip; a moved tip, a mempool that disagrees with address summaries, or conflicting pending spends retry instead of producing a wrong balance. On final failure the wallet keeps its last complete balance and is marked failed.
  • One reader per wallet under a session advisory lock — no row lock is held during HTTP — and a source change during a read voids its result and queues a follow-up. Wallet addresses and single-address wallets claim an address under the same advisory lock, so neither can track an address the other already tracks.
  • Provider::MempoolSpace gains tip hash and height, transaction status, block transaction counts, and paged wallet history that truncates at a page budget or baseline date.
  • security:backfill_encryption now covers BitcoinWalletSource keys (version 14); the backfill writes read-only attributes with update_all.

Cash anchors

  • A cash_anchor valuation records only the cash balance on a date with a cash_entry_total ledger baseline, so edits to earlier cash movements apply through it without double counting. A same-day older total valuation is marked superseded_at; monetary edits or a new reconciliation reactivate it.
  • Cash-anchored accounts materialize holdings and balances from their anchor date, preserving imported history before it, value untraded holdings in their own currency, and carry forward prices on days without quotes. Their syncs run in the family's time zone.

The Bitcoin wallet migration is unchanged from #3753, so installs already running it have nothing new to migrate; the cash anchor and holding columns are new migrations. Nothing in the app creates a wallet yet — connecting and publishing come in part 4, setup UI in part 5.

Summary by CodeRabbit

  • New Features
    • Added Bitcoin wallet tracking for manual crypto accounts using a wallet address or extended public key.
    • Wallet balances and transaction activity are discovered and synced, with updates reflected in wallet status.
    • Extended public key wallets scan receive and change addresses, resuming discovery between full rescans.
    • Bitcoin addresses tracked elsewhere in the same family are recognized to prevent duplicate linking.
  • Improvements
    • Added localized validation messages for provider conflicts, account eligibility, and unavailable extended public key encryption.
    • Wallet synchronization can retry incomplete or changing data reads while preserving the last available balance when a read fails.