Files
minibits_wallet/__mocks__/op-sqlite.js
minibits-cash f8ed2d4a71 Fix the upgrade path; master mints in SQLite
Two things, in one commit because the test that proves the first needs the second.

Fix the upgrade path (a bug shipped in 2f7a276)

A wallet at db v29 came up with a zero balance. instance.ts ran
createSchemaQueries on EVERY launch, before migrations. `CREATE TABLE IF NOT
EXISTS` skips the tables a device already has — but silently creates the ones it
does not, at TODAY's shape. A device predating a table therefore received it
fully formed, and the migration that adds a column to that table then died on
"duplicate column name". The batch is atomic, so EVERY migration rolled back:
hence the cascade of "no such column: mintId" and a wallet with nothing in it.

Concretely: v29 predates onchain_mint_quotes (v31), so it was built already
carrying the mintId that v33 exists to add.

This is the same replay trap that made v26/v28/v29/v31 freeze their column
lists. I fixed it for migrations sharing live constants and missed that
createSchemaQueries does the same thing, on every existing database.

The fix is strictly either/or. Only dbversion is created unconditionally (reading
the version needs it); then the version decides. Fresh install → build at the
latest shape and record it. Existing database → migrations own every shape
change, so each table is created by ITS migration at THAT version's shape, which
is what keeps the later ALTERs valid.

The gap was structural: every db suite starts from a FRESH in-memory database,
where instance.ts builds the latest schema and seeds the version — so migrations
never run at all. The path every user takes had no coverage. dbUpgradePath.test.ts
closes it via a __seedNextDatabase hook on the op-sqlite mock, covering every
version 26→34 through the real instance.ts and asserting the money, the
derivation counter, the added columns, and that the repos work afterwards.
Reverted to the shipped ordering, 16 of its 17 tests fail.

The v26 fixture is VERIFIED against tag v0.4.3-beta.3 — the last released native
bundle, `_dbVersion = 26`, `rootStoreModelVersion = 32`, which is where even a
brand new install starts today before OTA. Its createSchemaQueries builds exactly
those four tables and its column lists match the fixture one for one. It is frozen
on purpose: a fixture that tracks schema.ts describes a device that never existed.

Master mints in SQLite (Stage 1)

Mints were the last core entity persisted by serializing the whole MST tree.
Since postProcessSnapshot already strips proofs and transactions, mints — with
every keyset's `keys` map — were the largest thing left in it, and
JSON.stringify(snapshot) runs on EVERY MST action anywhere, including every proof
mutation during a send. New tables: mints, and mint_keysets keyed by keysetId
(matching mint_counters; keyset and keys stored as whole JSON so fields like
final_expiry, which feeds NUT-02 v2 id derivation, cannot be dropped by an
enumerated column list).

SQLite is the authority, MST the cache — as for proofs and transactions. Reads
and MobX reactivity are unchanged. Persistence is one onSnapshot observer per
mint rather than a write-through in each of ~20 Mint mutators, where forgetting
one is silent staleness; it is equality-guarded on the PERSISTED payload, so a
proofsCounters change cannot churn the row, and attached only after load.

The rename is now ONE transaction across the mint row and its proofs
(mintsRepo.updateMintUrl). The standalone updateProofsMintUrl is deleted so the
non-atomic path cannot come back. Previously the url lived in MMKV and the proofs
in SQLite, so a crash between the two writes left proofs owned by no mint: the
money vanished from every per-mint balance while still counting in the total, and
could not be spent.

postProcessSnapshot strips mints, so ExportBackup had to change in the same
commit: getSnapshot(mintsStore).mints is now ALWAYS empty, and a backup taken
from it would contain zero mints, raise no error, and reveal the loss only on
restore. The build moved onto the store as a tested `backupSnapshot` view.
ImportBackup persists explicitly, since applySnapshot nodes arrive already-formed
and observers fire only on change.

Two bugs the tests caught before the device could

- types.Date rejects an ISO string, so loading threw on typecheck: every launch
  after the migration would have failed to load any mint.
- proofsCounters came back EMPTY, because loading bypasses initKeyset. The
  counter hydrate would have had nothing to fill, the counter would be recreated
  at 0 on first use, and derivation would reuse blinded secrets the mint had
  already signed — the exact fund loss this branch began with, reintroduced by
  its own fix. Neither is SQL; no mirror-style test could have found them.

Sabotage-verified: dropping the counter shells, building the backup from
getSnapshot, and skipping the proofs in the rename each fail the suite. The first
of those did NOT fail until the assertion was added, which is why it was checked.

Tests: 503 pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 08:48:51 +02:00

129 lines
4.7 KiB
JavaScript

/**
* Jest mock for @op-engineering/op-sqlite — a REAL database, backed by node:sqlite.
*
* op-sqlite is native and cannot load under jest. Rather than stub it out, this
* implements its driver surface on top of Node's built-in SQLite, so tests run the
* PRODUCTION code path end to end: connection.ts (its param sanitizing, result
* adaptation and BEGIN/COMMIT batch emulation), instance.ts (schema creation and
* the real migration runner), and every repo — all real.
*
* Why this matters: the db suites used to hand-copy both the DDL and each repo's
* SQL, and those copies drifted from production repeatedly while staying green.
* A test that asserts against its own copy of the schema proves nothing about the
* schema. Mocking at connection.ts's documented seam — "the single seam between
* the rest of the app and the native SQLite library" — removes the copies entirely.
*
* Each test FILE gets its own in-memory database (jest resets the module registry
* per file, so instance.ts re-runs and rebuilds the schema). Tests within a file
* share it; clear the tables you use in beforeEach, or use distinct keys.
*
* NOT covered here: op-sqlite is not SQLite-the-same-build. Node's SQLite may differ
* in version and compile flags, so this proves our SQL and our logic, not the exact
* native binary's behaviour. Device testing still owns that.
*/
const {DatabaseSync} = require('node:sqlite')
/**
* Statements that RETURN rows. Everything else reports changes/insertId instead.
*
* The RETURNING clause matters: walletCountersRepo allocates an index with a single
* `INSERT … ON CONFLICT DO UPDATE … RETURNING`, which leads with INSERT but yields a
* row. Routing it by leading keyword alone hands back nothing and the allocation
* fails.
*/
const returnsRows = sql =>
/^\s*(select|pragma|with|explain)/i.test(sql) || /\breturning\b/i.test(sql)
/** Transaction control cannot be prepared as a statement; exec it directly. */
const isTransactionControl = sql => /^\s*(begin|commit|rollback|savepoint|release)\b/i.test(sql)
/**
* node:sqlite binds a narrower set of types than the native driver.
*
* connection.ts's sanitizeValue runs BEFORE this and is what the app relies on, so
* it has already rejected anything genuinely unbindable. This only bridges the two
* types Node will not take directly — booleans (SQLite has no boolean type; real
* drivers coerce to 0/1) and ArrayBuffer (Node wants a view).
*/
const toBindable = value => {
if (typeof value === 'boolean') return value ? 1 : 0
if (value instanceof ArrayBuffer) return new Uint8Array(value)
return value
}
/**
* Test hook: pre-populate the NEXT database opened.
*
* Lets a test hand instance.ts a database that already exists at some older
* version, which is the only way to exercise the real upgrade path — the one that
* runs on every user's device and that a fresh in-memory database never touches.
* Consumed once, so it cannot leak into the next open.
*/
let _seedNextDatabase = null
const __seedNextDatabase = seed => {
_seedNextDatabase = seed
}
const open = () => {
const db = new DatabaseSync(':memory:')
if (_seedNextDatabase) {
_seedNextDatabase(db)
_seedNextDatabase = null
}
const executeSync = (query, params) => {
if (isTransactionControl(query)) {
db.exec(query)
return {rows: [], rowsAffected: 0}
}
const bound = (params ?? []).map(toBindable)
const statement = db.prepare(query)
if (returnsRows(query)) {
return {rows: statement.all(...bound), rowsAffected: 0}
}
const result = statement.run(...bound)
return {
rows: [],
rowsAffected: Number(result.changes ?? 0),
// Only meaningful for INSERT; harmless elsewhere and matches op-sqlite.
insertId: result.lastInsertRowid != null ? Number(result.lastInsertRowid) : undefined,
}
}
return {
executeSync,
execute: async (query, params) => executeSync(query, params),
// op-sqlite's own batch is async and all-or-nothing. connection.ts does not use
// it for the synchronous path (it emulates that with BEGIN/COMMIT over
// executeSync), so this only serves executeBatchAsync.
executeBatch: async commands => {
let rowsAffected = 0
db.exec('BEGIN')
try {
for (const [query, params] of commands) {
rowsAffected += executeSync(query, params).rowsAffected ?? 0
}
db.exec('COMMIT')
} catch (e) {
db.exec('ROLLBACK')
throw e
}
return {rowsAffected}
},
close: () => db.close(),
delete: () => {},
}
}
module.exports = {
open,
__seedNextDatabase,
IOS_DOCUMENT_PATH: '/mock/ios/documents',
ANDROID_FILES_PATH: '/mock/android/files',
}
module.exports.__esModule = true