mirror of
https://github.com/minibits-cash/minibits_wallet.git
synced 2026-07-22 07:48:28 +00:00
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>
148 lines
4.9 KiB
TypeScript
148 lines
4.9 KiB
TypeScript
/**
|
|
* Repeatable migration tests for SQLite migration 35.
|
|
*
|
|
* Migration 35 creates the `mints` and `mint_keysets` tables, moving the mints out
|
|
* of the MST/MMKV snapshot and into SQLite.
|
|
*
|
|
* WHY: postProcessSnapshot already strips proofs and transactions, so mints — with
|
|
* every keyset's `keys` map — had become the largest thing left in the persisted
|
|
* tree, and `JSON.stringify(snapshot)` runs on EVERY MST action anywhere, including
|
|
* every proof mutation during a send. It also puts mints in the same engine as the
|
|
* proofs, so a mint-url edit can commit atomically with the proofs it renames.
|
|
*
|
|
* The tables are created EMPTY: mints live in the snapshot, so nothing in SQL can
|
|
* read them. The v39 seed copies them once the store is hydrated.
|
|
*
|
|
* Uses Node.js built-in node:sqlite (requires Node 22.5+).
|
|
* @jest-environment node
|
|
*/
|
|
jest.mock('../src/services/logService', () => ({
|
|
log: {debug: jest.fn(), error: jest.fn(), info: jest.fn(), trace: jest.fn(), warn: jest.fn()},
|
|
}))
|
|
|
|
import {DatabaseSync} from 'node:sqlite'
|
|
import {MIGRATIONS} from '../src/services/db/migrations'
|
|
|
|
// ── The REAL migration, taken from the registry ─────────────────────────────
|
|
//
|
|
// Imported rather than copied: a copy of the SQL proves nothing about the SQL that
|
|
// actually runs on a device.
|
|
|
|
const MIGRATION_35 = MIGRATIONS.find(m => m.version === 35)!.queries.map(([sql]) => sql)
|
|
|
|
function runMigration35(db: DatabaseSync) {
|
|
db.exec('BEGIN')
|
|
try {
|
|
for (const sql of MIGRATION_35) db.exec(sql)
|
|
db.exec('COMMIT')
|
|
} catch (e) {
|
|
db.exec('ROLLBACK')
|
|
throw e
|
|
}
|
|
}
|
|
|
|
function columns(db: DatabaseSync, table: string): string[] {
|
|
const rows = db.prepare(`PRAGMA table_info(${table})`).all() as unknown as Array<{name: string}>
|
|
return rows.map(r => r.name)
|
|
}
|
|
|
|
function tables(db: DatabaseSync): string[] {
|
|
return (
|
|
db.prepare(`SELECT name FROM sqlite_master WHERE type='table' ORDER BY name`).all() as unknown as Array<{
|
|
name: string
|
|
}>
|
|
).map(r => r.name)
|
|
}
|
|
|
|
/** A pre-35 database: no mints tables at all. */
|
|
const freshDb = () => new DatabaseSync(':memory:')
|
|
|
|
describe('SQLite migration 35 — mints move into SQLite', () => {
|
|
test('creates both tables', () => {
|
|
const db = freshDb()
|
|
expect(tables(db)).not.toContain('mints')
|
|
|
|
runMigration35(db)
|
|
|
|
expect(tables(db)).toContain('mints')
|
|
expect(tables(db)).toContain('mint_keysets')
|
|
db.close()
|
|
})
|
|
|
|
test('mints carries the identity, the url and the JSON payloads', () => {
|
|
const db = freshDb()
|
|
runMigration35(db)
|
|
|
|
expect(columns(db, 'mints').sort()).toEqual(
|
|
['color', 'createdAt', 'hostname', 'id', 'mintInfo', 'mintUrl', 'shortname', 'status', 'units'].sort(),
|
|
)
|
|
db.close()
|
|
})
|
|
|
|
test('mint_keysets is keyed by keysetId and owned by mintId', () => {
|
|
const db = freshDb()
|
|
runMigration35(db)
|
|
|
|
expect(columns(db, 'mint_keysets').sort()).toEqual(['keys', 'keyset', 'keysetId', 'mintId', 'unit'].sort())
|
|
db.close()
|
|
})
|
|
|
|
test('starts empty — the v39 seed fills it, because SQL cannot read the MMKV snapshot', () => {
|
|
const db = freshDb()
|
|
runMigration35(db)
|
|
|
|
expect(db.prepare('SELECT * FROM mints').all()).toEqual([])
|
|
expect(db.prepare('SELECT * FROM mint_keysets').all()).toEqual([])
|
|
db.close()
|
|
})
|
|
|
|
describe('keys', () => {
|
|
test('a mint id is unique', () => {
|
|
const db = freshDb()
|
|
runMigration35(db)
|
|
const insert = () =>
|
|
db
|
|
.prepare(`INSERT INTO mints (id, mintUrl) VALUES (?, ?)`)
|
|
.run('mint1', 'https://a.test')
|
|
|
|
insert()
|
|
expect(insert).toThrow()
|
|
db.close()
|
|
})
|
|
|
|
// Matches mint_counters, which is also keyed by keysetId alone: the two agree on
|
|
// what a keyset is, and a keyset id is unique wallet-wide (isCollidingKeysetId).
|
|
test('a keyset id is unique across mints, not just within one', () => {
|
|
const db = freshDb()
|
|
runMigration35(db)
|
|
|
|
db.prepare(`INSERT INTO mint_keysets (keysetId, mintId, keyset) VALUES (?, ?, ?)`).run(
|
|
'k1',
|
|
'mint1',
|
|
'{}',
|
|
)
|
|
|
|
expect(() =>
|
|
db
|
|
.prepare(`INSERT INTO mint_keysets (keysetId, mintId, keyset) VALUES (?, ?, ?)`)
|
|
.run('k1', 'mint2', '{}'),
|
|
).toThrow()
|
|
db.close()
|
|
})
|
|
|
|
test('mints.mintUrl is NOT unique — the schema does not decide mint identity', () => {
|
|
// Identity is Mint.id. Two rows could legitimately share a url mid-rename, and
|
|
// the constraint that matters (one real mint, one Mint node) is enforced by
|
|
// keyset collision detection, not by a url index.
|
|
const db = freshDb()
|
|
runMigration35(db)
|
|
|
|
db.prepare(`INSERT INTO mints (id, mintUrl) VALUES (?, ?)`).run('mint1', 'https://a.test')
|
|
expect(() =>
|
|
db.prepare(`INSERT INTO mints (id, mintUrl) VALUES (?, ?)`).run('mint2', 'https://a.test'),
|
|
).not.toThrow()
|
|
db.close()
|
|
})
|
|
})
|
|
})
|