diff --git a/docs/r4-submitted-wallet-label-coverage.md b/docs/r4-submitted-wallet-label-coverage.md new file mode 100644 index 000000000..9728a6f9d --- /dev/null +++ b/docs/r4-submitted-wallet-label-coverage.md @@ -0,0 +1,57 @@ +# Submitted R4: additive wallet and label caller proofs + +Baseline is exactly submitted R4 source +`1d8a86a7462d935cbd0e28b857934b5718c152fc` (PR #7045). +This candidate adds only two test files and this coverage map. It imports no R5 +runtime, native, dependency, configuration or fixture changes. It does not alter +or rebuild the existing signed iOS620/Android627 artifacts. + +The earlier app #7150/control #190 candidate was based on #7091 b572, which +inherits the combined R5 candidate #7082. That separate run is preserved only +for its actual source and supplies no submitted-R4 acceptance. Existing 32 +queue/bootstrap ports on that source likewise require independent exact-R4 +validation before their evidence can transfer. + +## Original obligations retained (20) + +- Wallet/vault callers (11): atomic two-wallet commit before HTTP; second insert + rollback; rename conflict preserves local success/pending backup; Hide/readback + gates Delete; lost Hide ACK keeps local state and withholds Delete without + replay; stale factory A-to-B-to-A; stale encrypted presentation; vault Hide and + Delete; shared signer registrations/private material; archive-before-new-vault + migration success; partial migration conflict with own-ACK/no-peer-rebase. +- Label/send/coin-choice callers (9): add/import/edit readback; grouped transaction + note/change/inherited labels; invalid second import rollback; persisted manual + coin choice; actual409, actual404, malformed ACK and lost-reply uncertainty + (four cases); stale A-to-B-to-A worker cannot modify the returning account. + +Actual production workers, explicit opt-in, native encrypted Realm, production +backup authority/crypto, signed HTTP, original revision/generation/authEpoch, +complete readback and current transactional Relay remain real. Only the existing +unspendable public factory/descriptor adapters and bounded real-failure/reply +scheduling boundaries are used. No successful backup/DB result is fabricated. + +Selected wallet/UTXO workers, ManageWallets gate and both fixture files are +byte-identical between submitted1d8 and the earlier b572 source. Their called +APIs are checked against the submitted source. Any genuine R4 failure remains a +failure; this test package does not backport a product correction. + +## Execution boundary and remaining coverage + +Syntax/source compatibility review precedes any genuine execution. Current Relay +is fixed at `29597b27eeeb299205bf7d0555db0a90c38cc4be`. A private CI-only admission +preload follows the existing reviewed submitted-R4 #161 approach; the historical +public app proof runner/pins and all private source boundaries stay unchanged. + +Until an actual exact-source receipt exists, none of these20 cases is passed. +A later20/20 would verify these20 obligations only on the test-only descendant +of submitted1d8. It would not change signed artifact bytes or establish native, +physical, store or complete295-case parity. The original2 PASS/293 FAIL public +lane stays unchanged. The other275 original obligations still need exact-R4 +mapping/validation; R5-derived receipts are not subtracted. + +Production Relay14-request acceptance, submitted-R443+3 proof and R5 43+1+3 +proof stay separate and are not repeated for this batch. #155 stays unapplied +while legacy writers are fenced. Sonar connectivity and current store/artifact +access remain separate blockers. No production, index, merge, deployment, +signing, store/publication or personal Mac action is included. diff --git a/tests/recovery/protectedLabelProducers.proof.cjs b/tests/recovery/protectedLabelProducers.proof.cjs new file mode 100644 index 000000000..bb18d8b1d --- /dev/null +++ b/tests/recovery/protectedLabelProducers.proof.cjs @@ -0,0 +1,233 @@ +// Additive signed-v3 port of all nine automaticLabelProducers invariants. +// Actual selected label/spendability workers, native encrypted Realm, production +// authority/AES/HTTP/CAS/readback and the current transactional Relay remain real. +// Only public descriptor formatting is adapted for the intentionally unspendable +// wallet. Faults affect genuine replies or disposable database state, never forge +// a successful ACK. This is not rendered UI or broadcast/coin-control acceptance. +const assert = require('node:assert/strict'); +const crypto = require('node:crypto'); +const { test: nodeTest, beforeEach, afterEach, after } = require('node:test'); +const { declarations, evaluate, plain, Realm } = require('./automaticWriteRealmRelay.fixture.cjs'); +const { createProtectedServer, createProtectedRealmClient } = require('./protectedWriteRealmRelay.fixture.cjs'); + +const mnemonic = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; +const seed = require('bip39').mnemonicToSeedSync(mnemonic); +const appId = crypto.createHash('sha256').update(seed).digest('hex'); +let server; +beforeEach(async () => { server = await createProtectedServer(); }); +afterEach(async () => { await server?.close(); server = undefined; }); +after(() => Realm.shutdown()); +const test = (name, body) => nodeTest(name, { timeout: 20_000 }, body); +const label = (ref, name) => ({ id: `${ref}${name}`, ref, label: name, type: 'TXN', origin: 'disposable-public-origin', isSystem: false }); +const writes = () => server.trace.filter(event => event.path === '/backup/v3/mutate'); +const labelWrites = () => writes().filter(event => event.operation === 'modifyLabels'); + +async function setup(t, initialTags = []) { + await server.reset(); + const f = await createProtectedRealmClient(server.url, { + appId, primarySeed: seed.toString('hex'), primaryMnemonic: mnemonic, + }); + t.after(() => f.close()); + f.automatic = f.load('src/services/backup/automatic'); + f.installProductionStoreObservers(f.automatic); + f.store.dispatch(f.bhr.setAutomaticCloudBackup({ appId: f.appId, enabled: true })); + const wallet = f.defaults(f.RealmSchema.Wallet, { + id: 'producer-wallet', entityKind: f.enums.EntityKind.WALLET, type: f.enums.WalletType.DEFAULT, + networkType: f.enums.NetworkType.TESTNET, scriptType: 'P2WPKH', + derivationDetails: f.defaults(f.RealmSchema.WalletDerivationDetails, { instanceNum: 0, xDerivationPath: "m/84'/1'/0'" }), + presentationData: f.defaults(f.RealmSchema.WalletPresentationData, { name: 'Producer fixture', visibility: 'DEFAULT' }), + specs: f.defaults(f.RealmSchema.WalletSpecs, { + xpub: 'disposable-public-wallet-xpub', nextFreeAddressIndex: 1, + addresses: { external: {}, internal: { 0: 'change-address' } }, + confirmedUTXOs: [f.defaults(f.RealmSchema.UTXO, { + txId: 'input', vout: 0, spendability: 'spendable', isManualOverride: false, + })], + }), + }); + assert.equal(f.dbManager.createObject(f.RealmSchema.Wallet, wallet), true); + for (const tag of initialTags) assert.equal(f.dbManager.createObject(f.RealmSchema.Tags, tag), true); + const utxos = f.load('src/store/reducers/utxos'); + const sagas = f.productionSagas([ + 'currentBackupAppId', 'setServerBackupFailed', + 'buildAutomaticAppMutation', 'buildAutomaticVaultMutation', 'queueCommittedBackupWorker', + 'updateAppImageWorker', 'updateVaultImageWorker', 'backupInspectionOwners', 'runBackupInspection', + ], { + ...f.automatic, ...utxos, + // Public label metadata only; no fabricated wallet identity, encrypted + // record, native commit, protected authority or network success. + generateAbbreviatedOutputDescriptors: () => 'disposable-public-origin', + }); + assert.equal(await sagas.run('runBackupInspection', true, f.appId, true), true, + 'Actual production opt-in must enroll, repair and verify the signed namespace'); + assert.ok(f.transport.captureBackupWriteIntent(f.appId)?.protectedBase); + evaluate(declarations('src/store/sagas/utxos.ts', [ + 'currentOriginApp', 'originUiAction', 'persistTagsForOrigin', 'persistSpendabilityForOrigin', + 'backupCommittedLabels', 'addLabelsWorker', 'bulkUpdateLabelsWorker', 'importLabelsWorker', + 'transactionLabelsWorker', 'markUTXOSpendabilityWorker', + ]), sagas.scope, 'production-protected-label-producers.ts'); + f.run = (name, payload, metadata = {}) => sagas.run(name, { + payload, originAppId: f.appId, + originBackupAccountSession: f.transport.currentBackupAccountSession(), + originBackupWriteIntent: f.transport.captureBackupWriteIntent(f.appId), + ...metadata, + }); + f.wallet = () => plain(f.dbManager.getObjectById(f.RealmSchema.Wallet, wallet.id)); + f.read = () => f.protected.readProtectedBackup(mnemonic, undefined, f.appId); + f.remoteImage = async () => { + const result = await f.read(); + assert.equal(result.state, 'present'); + return f.image.decodeImage(f.encryption.generateEncryptionKey(f.seed), + result.snapshot, result.namespaceId, () => {}, true); + }; + f.initial = (await f.read()).snapshot; + server.clearTrace(); + return f; +} + +async function assertConfirmed(f, operation) { + assert.equal(writes().length, 1); + const write = writes()[0]; + assert.equal(write.operation, operation); + assert.equal(write.committed, true); + assert.equal(write.status, 200); + const result = await f.read(); + assert.equal(result.state, 'present'); + assert.notEqual(result.snapshot.revision, f.initial.revision); + assert.equal(result.snapshot.revision, write.serverRevision); + assert.equal(result.snapshot.generation, write.serverGeneration); + assert.equal(result.snapshot.authEpoch, write.serverAuthEpoch); + assert.equal(await f.image.compareImages(await f.repair.captureBackupImage(), await f.remoteImage()), 'matched'); + assert.equal(f.automatic.isBackupVerificationCurrent(f.appId), true); + assert.equal(f.store.getState().bhr.pendingAllBackupByAppId[f.appId], false); + assert.equal(f.store.getState().bhr.backupRepairStateByAppId[f.appId], 'verified'); +} + +// Historical case 1: add/import/edit each has one committed mutation/readback. +test('protected native add/import/edit label producers each use one committed HTTP mutation and final readback', async t => { + const f = await setup(t); + await f.run('addLabelsWorker', { + txId: 'first', wallet: f.wallet(), labels: [{ name: 'original', isSystem: false }], type: 'TXN', + }); + await assertConfirmed(f, 'modifyLabels'); + assert.equal((await f.remoteImage()).labels.firstoriginal.label, 'original'); + server.clearTrace(); + await f.run('importLabelsWorker', { labels: [ + { type: 'tx', ref: 'second', label: 'import one', origin: 'disposable-public-origin' }, + { type: 'tx', ref: 'third', label: 'import two', origin: 'disposable-public-origin' }, + ] }); + await assertConfirmed(f, 'modifyLabels'); + assert.equal(Object.keys((await f.remoteImage()).labels).length, 3); + server.clearTrace(); + await f.run('bulkUpdateLabelsWorker', { + txId: 'first', wallet: f.wallet(), + labelChanges: { added: [{ name: 'edited', isSystem: false }], deleted: [{ name: 'original', isSystem: false }] }, + }); + await assertConfirmed(f, 'modifyLabels'); + const image = await f.remoteImage(); + assert.equal(image.labels.firstoriginal, undefined); + assert.equal(image.labels.firstedited.label, 'edited'); +}); + +// Historical case 2: note plus every inherited change label is one operation. +test('protected native send labels group the transaction note and all change labels into one HTTP mutation', async t => { + const f = await setup(t, [label('input:0', 'inherited')]); + await f.run('transactionLabelsWorker', { + txId: 'sent', wallet: f.wallet(), note: 'send note', + finalOutputs: [{ address: 'recipient-address' }, { address: 'change-address' }], inputs: [{ txId: 'input', vout: 0 }], + }); + await assertConfirmed(f, 'modifyLabels'); + const image = await f.remoteImage(); + for (const id of ['sentsend note', 'sent:1Change', 'sent:1inherited']) + assert.deepEqual(plain(image.labels[id]), plain(f.dbManager.getObjectById(f.RealmSchema.Tags, id))); +}); + +// Historical case 3: the native transaction rolls back before any HTTP mutation. +test('protected native invalid second imported tag rolls back the first and generates no HTTP writes', async t => { + const f = await setup(t); + await f.run('importLabelsWorker', { labels: [ + { type: 'tx', ref: 'first', label: 'must roll back', origin: 'disposable-public-origin' }, + { type: 'tx', ref: 'second', label: null, origin: 'disposable-public-origin' }, + ] }); + assert.equal(f.dbManager.getCollection(f.RealmSchema.Tags).length, 0); + assert.equal(writes().length, 0); + assert.equal(Object.keys((await f.remoteImage()).labels).length, 0); + assert.equal((await f.read()).snapshot.revision, f.initial.revision); + assert.equal(f.store.getState().bhr.pendingAllBackupByAppId[f.appId], true); + assert.equal(f.transport.captureBackupWriteIntent(f.appId), undefined); +}); + +// Historical case 4: the encrypted backup reflects the committed coin choice. +test('protected native manual coin choice is committed before the encrypted wallet reaches HTTP', async t => { + const f = await setup(t); + await f.run('markUTXOSpendabilityWorker', { + wallet: f.wallet(), txId: 'input', vout: 0, spendability: 'doNotSpend', + }); + assert.equal(f.wallet().specs.confirmedUTXOs[0].spendability, 'doNotSpend'); + await assertConfirmed(f, 'updateAppImage'); + const image = await f.remoteImage(); + assert.equal(image.wallets['producer-wallet'].specs.confirmedUTXOs[0].spendability, 'doNotSpend'); + assert.equal(image.wallets['producer-wallet'].specs.confirmedUTXOs[0].isManualOverride, true); +}); + +// Historical cases 5–8: one label mutation; local data survives uncertainty. +for (const mode of ['409', '404', 'malformed', 'lost-reply']) + test(`protected native combined send labels survive ${mode} and keep backup pending after one request`, async t => { + const f = await setup(t); + const base = f.transport.captureBackupWriteIntent(f.appId).protectedBase; + if (mode === '409') { + server.armFault({ path: '/backup/v3/snapshot', async beforeReply() { + // Actual competing signed CAS after the original snapshot, no fake409. + await f.protected.protectedBackupMutation(mnemonic, base, 'updateAppImage', { + nodes: [], replaceNodes: true, + }); + } }); + } else if (mode === '404') { + server.armFault({ path: '/backup/v3/snapshot', async beforeReply() { + // Model disappearance only in this task-owned disposable database after + // the real read. The unchanged signed mutation route must return404. + const database = server.backend.connection.db; + await database.collection('protectedBackupRecords').deleteMany({ namespaceId: base.namespaceId }); + const removed = await database.collection('protectedBackupNamespaces').deleteOne({ _id: base.namespaceId }); + assert.equal(removed.deletedCount, 1); + } }); + } else server.armFault({ path: '/backup/v3/mutate', operation: 'modifyLabels', + mode: mode === 'malformed' ? 'malformed-json' : mode }); + await f.run('transactionLabelsWorker', { + txId: 'sent', wallet: f.wallet(), note: 'send note', + finalOutputs: [{ address: 'change-address' }], inputs: [], + }); + assert.equal(labelWrites().length, 1, 'The label producer must not retry or borrow new authority'); + if (mode === '409') { + assert.equal(writes().length, 2, 'One independently committed peer CAS plus one original label request'); + assert.equal(writes()[0].operation, 'updateAppImage'); + assert.equal(writes()[0].committed, true); + assert.equal(labelWrites()[0].status, 409); + assert.equal(labelWrites()[0].committed, false); + assert.equal(labelWrites()[0].expectedRevision, base.revision); + assert.notEqual(labelWrites()[0].expectedRevision, writes()[0].serverRevision); + } else { + assert.equal(writes().length, 1); + assert.equal(labelWrites()[0].committed, mode !== '404'); + assert.equal(labelWrites()[0].status, mode === '404' ? 404 : 200); + } + for (const id of ['sentsend note', 'sent:0Change']) + assert.ok(f.dbManager.getObjectById(f.RealmSchema.Tags, id)); + assert.equal(f.store.getState().bhr.pendingAllBackupByAppId[f.appId], true); + assert.equal(f.automatic.isBackupVerificationCurrent(f.appId), false); + assert.equal(f.transport.captureBackupWriteIntent(f.appId), undefined); + }); + +// Historical case 9: stale A→B→A work cannot touch the new session or namespace. +test('protected native old-session transaction labels cannot commit after A to B to A', async t => { + const f = await setup(t); + const old = { + originBackupAccountSession: f.transport.currentBackupAccountSession(), + originBackupWriteIntent: f.transport.captureBackupWriteIntent(f.appId), + }; + const originalWallet = f.wallet(); + await f.selectAccount('disposable-other-account'); + await f.selectAccount(f.appId); + await f.run('transactionLabelsWorker', { txId: 'sent', wallet: originalWallet, note: 'old session' }, old); + assert.equal(f.dbManager.getCollection(f.RealmSchema.Tags).length, 0); + assert.equal(writes().length, 0); +}); diff --git a/tests/recovery/protectedWalletProducer.proof.cjs b/tests/recovery/protectedWalletProducer.proof.cjs new file mode 100644 index 000000000..a6132c037 --- /dev/null +++ b/tests/recovery/protectedWalletProducer.proof.cjs @@ -0,0 +1,341 @@ +// Additive signed-v3 port of all 11 historical wallet/vault caller obligations. +// Actual production workers, encrypted native Realm, authority/crypto, original +// CAS tuples and transactional loopback Relay remain real. Factory adapters only +// supply intentionally unspendable records; no backup/DB commit is fabricated. +// Original public-v2 coverage and its failed result remain unchanged. +const assert = require('node:assert/strict'); +const crypto = require('node:crypto'); +const { test, beforeEach, afterEach, after } = require('node:test'); +const { createRealmClient, declarations, componentDeclarations, evaluate, plain, Realm } = require('./automaticWriteRealmRelay.fixture.cjs'); +const { createProtectedServer, createProtectedRealmClient } = require('./protectedWriteRealmRelay.fixture.cjs'); +const mnemonic = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; +const seed = require('bip39').mnemonicToSeedSync(mnemonic); +const appId = crypto.createHash('sha256').update(seed).digest('hex'); +let server; +// Preserve production admission buckets: each independent case has a new router. +beforeEach(async () => { server = await createProtectedServer(); }); +afterEach(async () => { await server?.close(); server = undefined; }); +after(() => Realm.shutdown()); +const writes = () => server.trace.filter(event => event.path === '/backup/v3/mutate'); + +function wallet(f, id = 'wallet') { + return f.defaults(f.RealmSchema.Wallet, { + id, entityKind: f.enums.EntityKind.WALLET, type: f.enums.WalletType.DEFAULT, + networkType: f.enums.NetworkType.TESTNET, scriptType: 'P2WPKH', + derivationDetails: f.defaults(f.RealmSchema.WalletDerivationDetails, { instanceNum: 0, xDerivationPath: "m/84'/1'/0'" }), + presentationData: f.defaults(f.RealmSchema.WalletPresentationData, { name: 'Initial wallet', visibility: 'DEFAULT' }), + specs: f.defaults(f.RealmSchema.WalletSpecs, { xpub: `disposable-public-${id}`, nextFreeAddressIndex: 1 }), + }); +} + +function signer(f) { + const record = f.defaults(f.RealmSchema.Signer, { + masterFingerprint: 'aaaa0001', type: f.enums.SignerType.COLDCARD, storageType: f.enums.SignerStorage.COLD, + signerName: 'Disposable public key', networkType: f.enums.NetworkType.TESTNET, + signerXpubs: f.defaults(f.RealmSchema.SignerXpubs, { + [f.enums.XpubTypes.P2WSH]: [{ xpub: 'disposable-vault-public-key', xpriv: null, derivationPath: "m/48'/1'/0'/2'" }], + }), + }); + record.id = f.utilities.getKeyUID(record); + return record; +} + +function vault(f, id, key) { + return f.defaults(f.RealmSchema.Vault, { + id, entityKind: f.enums.EntityKind.VAULT, type: f.enums.VaultType.DEFAULT, + networkType: f.enums.NetworkType.TESTNET, isMultiSig: true, scriptType: 'P2WSH', + scheme: f.defaults(f.RealmSchema.VaultScheme, { m: 1, n: 1 }), signers: [key], + presentationData: f.defaults(f.RealmSchema.VaultPresentationData, { name: id, visibility: 'DEFAULT' }), + specs: f.defaults(f.RealmSchema.VaultSpecs, { xpubs: [key.xpub], nextFreeAddressIndex: 1 }), + }); +} + +async function setup(t, prepare = () => {}) { + await server.reset(); + const f = await createProtectedRealmClient(server.url, { appId, primarySeed: seed.toString('hex'), primaryMnemonic: mnemonic }); + t.after(() => f.close()); + f.automatic = f.load('src/services/backup/automatic'); + f.installProductionStoreObservers(f.automatic); + f.store.dispatch(f.bhr.setAutomaticCloudBackup({ appId: f.appId, enabled: true })); + prepare(f); + const inspection = f.productionSagas(['currentBackupAppId', 'backupInspectionOwners', 'runBackupInspection']); + assert.equal(await inspection.run('runBackupInspection', true, f.appId, true), true, + 'Explicit production opt-in must enroll, repair and verify the protected copy'); + assert.ok(f.transport.captureBackupWriteIntent(f.appId)?.protectedBase); + server.clearTrace(); + const sagas = f.productionSagas([ + 'currentBackupAppId', 'buildAutomaticAppMutation', 'buildAutomaticVaultMutation', + 'queueCommittedBackupWorker', 'updateAppImageWorker', 'updateVaultImageWorker', + 'deleteAppImageEntityWorker', 'deleteVaultImageWorker', + ], { + ...f.automatic, + addNewWallet: async (_type, details) => details.fixture, + generateVault: async ({ signers }) => vault(f, 'new-vault', signers[0]), + uaiChecks: payload => ({ type: 'fixture-uai', payload }), + uaiType: { SECURE_VAULT: 'SECURE_VAULT' }, + initiateVaultMigration: payload => ({ type: 'fixture-migration', payload }), + vaultCreated: payload => ({ type: 'fixture-vault-created', payload }), + setIsCloudBsmsBackupRequired: payload => ({ type: 'fixture-bsms-required', payload }), + backupBsmsOnCloud: () => ({ type: 'fixture-bsms-queue' }), + }); + evaluate(declarations('src/store/sagas/wallets.ts', [ + 'currentWalletAccountId', 'assertWalletAccount', 'addNewWalletsWorker', + 'updateWalletDetailsWorker', 'updateRecoveryVisibilityWorker', 'addNewVaultWorker', + 'deleteVaultWorker', + ]), sagas.scope, 'production-wallet-producers.ts'); + const uiScope = { + ...sagas.scope, + activeRealmAppId: () => f.appId, + isBackupVerificationCurrent: f.automatic.isBackupVerificationCurrent, + }; + evaluate(componentDeclarations( + 'src/screens/AppSettings/ManageWallets.tsx', 'ManageWallets', ['canDeleteRecoveryEntity'] + ), uiScope, 'production-manage-wallets-delete-gate.tsx'); + f.scope = sagas.scope; + f.canDeleteRecoveryEntity = uiScope.canDeleteRecoveryEntity; + f.run = (name, payload, metadata = {}) => sagas.run(name, { + payload, originAppId: f.appId, + originBackupAccountSession: f.transport.currentBackupAccountSession(), + originBackupWriteIntent: f.transport.captureBackupWriteIntent(f.appId), ...metadata, + }); + f.remoteImage = async () => { + const found = await f.protected.readProtectedBackup(mnemonic, undefined, f.appId); + assert.equal(found.state, 'present'); + return f.image.decodeImage(f.encryption.generateEncryptionKey(f.seed), + found.snapshot, found.namespaceId, () => {}, true); + }; + return f; +} + +const newWallets = (f, ...records) => records.map(record => ({ + walletType: f.enums.WalletType.DEFAULT, walletDetails: { fixture: record }, +})); + +test('actual wallet creation atomically saves both wallets before the first genuine HTTP mutation', async t => { + const f = await setup(t); + const original = f.protected.protectedBackupMutation; + let observed = false; + f.protected.protectedBackupMutation = (...args) => { + assert.equal(args[2], 'updateAppImage'); + // Observe the actual production transport boundary; invoke it unchanged. + for (const id of ['first', 'second']) assert.ok(f.dbManager.getObjectById(f.RealmSchema.Wallet, id)); + observed = true; + return original(...args); + }; + t.after(() => { f.protected.protectedBackupMutation = original; }); + assert.equal(await f.run('addNewWalletsWorker', newWallets(f, wallet(f, 'first'), wallet(f, 'second'))), true); + assert.equal(observed, true); + assert.equal(writes().length, 1); + assert.equal(writes()[0].committed, true); + assert.deepEqual(Object.keys((await f.remoteImage()).wallets).sort(), ['first', 'second']); + assert.equal(f.store.getState().bhr.pendingAllBackupByAppId[f.appId], false); +}); + +test('actual second wallet insertion failure rolls back the first wallet and never reaches HTTP', async t => { + const f = await setup(t); + assert.equal(await f.run('addNewWalletsWorker', newWallets(f, wallet(f, 'duplicate'), wallet(f, 'duplicate'))), false); + assert.equal(f.dbManager.getCollection(f.RealmSchema.Wallet).length, 0); + assert.equal(writes().length, 0); + assert.equal(f.store.getState().bhr.pendingAllBackupByAppId[f.appId], true); +}); + +test('actual wallet rename survives HTTP conflict and reports local success with backup pending', async t => { + const f = await setup(t, f => assert.equal(f.dbManager.createObject(f.RealmSchema.Wallet, wallet(f)), true)); + const base = f.transport.captureBackupWriteIntent(f.appId).protectedBase; + server.armFault({ path: '/backup/v3/snapshot', async beforeReply() { + assert.equal(f.dbManager.getObjectById(f.RealmSchema.Wallet, 'wallet').presentationData.name, 'Committed rename'); + const result = await f.protected.protectedBackupMutation(mnemonic, base, 'updateAppImage', { nodes: [], replaceNodes: true }); + assert.notEqual(result.base.revision, base.revision, 'A real competing signed mutation creates the conflict'); + } }); + assert.equal(await f.run('updateWalletDetailsWorker', { + wallet: wallet(f), details: { name: 'Committed rename', description: 'Local description' }, + }), true); + assert.equal(writes().length, 2); + assert.equal(writes()[0].committed, true); + assert.equal(writes()[1].status, 409); + assert.equal(writes()[1].committed, false); + assert.equal(f.dbManager.getObjectById(f.RealmSchema.Wallet, 'wallet').presentationData.name, 'Committed rename'); + assert.equal(f.store.getState().bhr.pendingAllBackupByAppId[f.appId], true); + assert.equal((await f.remoteImage()).wallets.wallet.presentationData.name, 'Initial wallet'); +}); + +test('native Hide holds Delete until readback, then managed wallet deletion can use the new revision', async t => { + const f = await setup(t, f => assert.equal(f.dbManager.createObject(f.RealmSchema.Wallet, wallet(f)), true)); + let entered; + const mutationStarted = new Promise(resolve => { entered = resolve; }); + let release; + const heldReply = new Promise(resolve => { release = resolve; }); + t.after(() => release()); + server.armFault({ path: '/backup/v3/mutate', operation: 'updateAppImage', + beforeReply() { entered(); return heldReply; } }); + let localCommit; + const hiding = f.run('updateRecoveryVisibilityWorker', { + entityId: 'wallet', entityKind: f.enums.EntityKind.WALLET, + visibility: f.enums.VisibilityType.HIDDEN, + }, { onLocalComplete: updated => { localCommit = updated; } }); + await mutationStarted; + assert.equal(localCommit, true); + assert.equal(f.dbManager.getObjectById(f.RealmSchema.Wallet, 'wallet').presentationData.visibility, 'HIDDEN'); + assert.equal(f.canDeleteRecoveryEntity(wallet(f)), false); + assert.equal(writes()[0].committed, true, 'Actual backend CAS is held before its ACK'); + release(); + assert.equal(await hiding, true); + assert.equal(f.canDeleteRecoveryEntity(wallet(f)), true); + assert.equal((await f.remoteImage()).wallets.wallet.presentationData.visibility, 'HIDDEN'); + assert.equal(writes().length, 1); + const removed = await f.run('deleteAppImageEntityWorker', { walletIds: ['wallet'] }); + assert.equal(removed.updated, true); + assert.equal(removed.backupConfirmed, true); + assert.equal(f.dbManager.getObjectById(f.RealmSchema.Wallet, 'wallet'), undefined); + assert.deepEqual(Object.keys((await f.remoteImage()).wallets), []); + assert.equal(writes().length, 2); +}); + +test('lost Hide acknowledgement keeps the local change but withholds Delete and does not replay it', async t => { + const f = await setup(t, f => assert.equal(f.dbManager.createObject(f.RealmSchema.Wallet, wallet(f)), true)); + server.armFault({ path: '/backup/v3/mutate', mode: 'lost-reply', operation: 'updateAppImage' }); + let localCommit; + assert.equal(await f.run('updateRecoveryVisibilityWorker', { + entityId: 'wallet', entityKind: f.enums.EntityKind.WALLET, + visibility: f.enums.VisibilityType.HIDDEN, + }, { onLocalComplete: updated => { localCommit = updated; } }), true); + assert.equal(localCommit, true); + assert.equal(f.dbManager.getObjectById(f.RealmSchema.Wallet, 'wallet').presentationData.visibility, 'HIDDEN'); + assert.equal(f.canDeleteRecoveryEntity(wallet(f)), false); + assert.equal(f.store.getState().bhr.pendingAllBackupByAppId[f.appId], true); + assert.equal(writes().length, 1); + assert.equal((await f.remoteImage()).wallets.wallet.presentationData.visibility, 'HIDDEN'); + assert.equal(writes().length, 1); +}); + +test('actual old-session wallet factory completion cannot save after A to B to A', async t => { + const f = await setup(t); + let entered, release; + const started = new Promise(resolve => { entered = resolve; }); + const gate = new Promise(resolve => { release = resolve; }); + f.scope.addNewWallet = async (_type, details) => { entered(); await gate; return details.fixture; }; + const running = f.run('addNewWalletsWorker', newWallets(f, wallet(f))); + await started; + await f.selectAccount('disposable-other-account'); + await f.selectAccount(f.appId); + release(); + assert.equal(await running, false); + assert.equal(f.dbManager.getCollection(f.RealmSchema.Wallet).length, 0); + assert.equal(writes().length, 0); +}); + +test('a current wallet receipt cannot send stale encrypted presentation data', async t => { + const f = await setup(t, f => assert.equal(f.dbManager.createObject(f.RealmSchema.Wallet, wallet(f)), true)); + const operation = f.automatic.beginBackupLocalOperation(f.appId, f.transport.captureBackupWriteIntent(f.appId)); + const receipt = f.automatic.commitBackupLocalOperation(operation, realm => { + realm.objectForPrimaryKey('Wallet', 'wallet').presentationData.name = 'Committed rename'; + }); + const body = { appId: f.appId, walletsObject: { + wallet: await f.image.encryptRecord(f.encryption.generateEncryptionKey(f.seed), wallet(f)), + } }; + const result = await f.automatic.enqueueAutomaticBackupOperation(receipt, [{ operation: 'updateAppImage', body }]); + assert.equal(result.backupPending, true); + assert.equal(writes().length, 0); + assert.equal(f.dbManager.getObjectById(f.RealmSchema.Wallet, 'wallet').presentationData.name, 'Committed rename'); +}); + +async function vaultSetup(t) { + return setup(t, f => { + const parent = signer(f); + const key = f.defaults(f.RealmSchema.VaultSigner, { + ...parent.signerXpubs[f.enums.XpubTypes.P2WSH][0], masterFingerprint: parent.masterFingerprint, xfp: parent.masterFingerprint, + xpriv: 'unspendable-disposable-private-material', + registeredVaults: [{ vaultId: 'old-vault', registered: true, hmac: 'disposable-hmac' }], + }); + assert.equal(f.dbManager.createObject(f.RealmSchema.Signer, parent), true); + assert.equal(f.dbManager.createObject(f.RealmSchema.Vault, vault(f, 'old-vault', key)), true); + }); +} + +test('native vault Hide and managed Delete both advance the verified remote image', async t => { + const f = await vaultSetup(t); + const hiding = await f.run('updateRecoveryVisibilityWorker', { + entityId: 'old-vault', entityKind: f.enums.EntityKind.VAULT, + visibility: f.enums.VisibilityType.HIDDEN, + }); + assert.equal(hiding, true); + assert.equal(f.dbManager.getObjectById(f.RealmSchema.Vault, 'old-vault').presentationData.visibility, 'HIDDEN'); + assert.equal(f.canDeleteRecoveryEntity({ entityKind: f.enums.EntityKind.VAULT }), true); + assert.equal((await f.remoteImage()).vaults['old-vault'].presentationData.visibility, 'HIDDEN'); + assert.equal(writes().length, 1); + assert.equal(await f.run('deleteVaultWorker', { vaultId: 'old-vault' }), true); + assert.equal(f.dbManager.getObjectById(f.RealmSchema.Vault, 'old-vault'), undefined); + assert.deepEqual(Object.keys((await f.remoteImage()).vaults), []); + assert.equal(writes().length, 2); +}); + +function newVaultPayload(f, migrated = false) { + const key = plain(f.dbManager.getObjectByPrimaryId(f.RealmSchema.VaultSigner, 'xpub', 'disposable-vault-public-key')); + return { isMigrated: migrated, oldVaultId: migrated ? 'old-vault' : undefined, newVaultInfo: { + vaultType: f.enums.VaultType.DEFAULT, vaultScheme: { m: 1, n: 1 }, + vaultSigners: [{ ...key, registeredVaults: [], xpriv: null }], + vaultDetails: { name: 'New vault', description: '' }, + } }; +} + +test('actual vault creation preserves shared signer registrations and remembered private material', async t => { + const f = await vaultSetup(t); + assert.equal(await f.run('addNewVaultWorker', newVaultPayload(f)), true); + assert.equal(writes().length, 1); + assert.equal(writes()[0].committed, true); + const stored = f.dbManager.getObjectByPrimaryId(f.RealmSchema.VaultSigner, 'xpub', 'disposable-vault-public-key'); + assert.equal(stored.xpriv, 'unspendable-disposable-private-material'); + assert.equal(stored.registeredVaults[0].vaultId, 'old-vault'); + assert.equal(stored.registeredVaults[0].hmac, 'disposable-hmac'); + const image = await f.remoteImage(); + assert.ok(image.vaults['old-vault']); + assert.ok(image.vaults['new-vault']); + assert.equal(f.store.getState().bhr.pendingAllBackupByAppId[f.appId], false); +}); + +for (const failSecond of [false, true]) test(`actual vault migration commits both local effects then sends old archive before new vault (second fails=${failSecond})`, async t => { + const f = await vaultSetup(t); + const sent = []; + const original = f.protected.protectedBackupMutation; + f.protected.protectedBackupMutation = (...args) => { + if (args[2] !== 'updateVaultImage') return original(...args); + sent.push(args[3].vaultId); + assert.equal(f.dbManager.getObjectById(f.RealmSchema.Vault, 'old-vault').archived, true); + assert.ok(f.dbManager.getObjectById(f.RealmSchema.Vault, 'new-vault')); + return original(...args); + }; + t.after(() => { f.protected.protectedBackupMutation = original; }); + const archiveBase = f.transport.captureBackupWriteIntent(f.appId).protectedBase; + server.armFault({ path: '/backup/v3/mutate', operation: 'updateVaultImage', async beforeReply({ body, event }) { + assert.equal(f.dbManager.getObjectById(f.RealmSchema.Vault, 'old-vault').archived, true); + assert.ok(f.dbManager.getObjectById(f.RealmSchema.Vault, 'new-vault')); + assert.equal(event.committed, true); + if (failSecond) { + const base = { ...archiveBase, revision: body.newRevision, + generation: body.newGeneration, authEpoch: body.authEpoch }; + const competitor = await f.protected.protectedBackupMutation(mnemonic, base, + 'updateAppImage', { nodes: [], replaceNodes: true }); + assert.notEqual(competitor.base.revision, base.revision, 'A real committed competitor invalidates the next fanout CAS'); + } + } }); + assert.equal(await f.run('addNewVaultWorker', newVaultPayload(f, true)), true); + assert.deepEqual(sent, ['old-vault', 'new-vault'], 'Archive transport precedes new-vault transport'); + assert.equal(writes().length, failSecond ? 3 : 2); + assert.equal(writes()[0].operation, 'updateVaultImage'); + assert.equal(writes()[0].committed, true); + assert.equal(writes().at(-1).operation, 'updateVaultImage'); + assert.equal(writes().at(-1).committed, !failSecond); + assert.equal(writes().at(-1).expectedRevision, writes()[0].serverRevision, + 'Fanout must retain only its own previous acknowledged revision'); + if (failSecond) { + assert.equal(writes().at(-1).status, 409); + assert.notEqual(writes().at(-1).expectedRevision, writes()[1].serverRevision, + 'A competing commit must not become borrowed upload authority'); + } + assert.equal(f.dbManager.getObjectById(f.RealmSchema.Vault, 'old-vault').archived, true); + assert.ok(f.dbManager.getObjectById(f.RealmSchema.Vault, 'new-vault')); + const image = await f.remoteImage(); + assert.equal(image.vaults['old-vault'].archived, true); + assert.equal(!!image.vaults['new-vault'], !failSecond); + assert.equal(f.store.getState().bhr.pendingAllBackupByAppId[f.appId], failSecond); +});