Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/services/backup/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,12 @@ function vaultSchemeIdentity(scheme: any) {
};
}

function vaultSignerIdentity(signer: any) {
if (!signer || typeof signer !== 'object') return signer;
const { registeredVaults, ...key } = signer;
return key;
}

function identity(kind: keyof BackupImage, record: any) {
if (kind === 'wallets')
return {
Expand All @@ -119,7 +125,11 @@ function identity(kind: keyof BackupImage, record: any) {
return {
networkType: record.networkType,
scheme: vaultSchemeIdentity(record.scheme),
signers: record.signers,
// Registration receipts and device HMACs can change without changing the
// vault's keys or spending policy. They remain in encrypted recovery data.
signers: Array.isArray(record.signers)
? record.signers.map(vaultSignerIdentity)
: record.signers,
scriptType: record.scriptType,
};
if (kind === 'signers')
Expand Down
15 changes: 15 additions & 0 deletions src/services/backup/repair.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,15 @@ const clone = (value: any) => JSON.parse(JSON.stringify(value));

export async function captureBackupImage(checkpoint = () => {}): Promise<BackupImage> {
const image: BackupImage = { wallets: {}, signers: {}, vaults: {}, nodes: {}, labels: {} };
// A VaultSigner is shared across the vaults that use its xpub. Read the
// persisted registration value, including a value whose incremental upload
// failed, and carry it into every affected encrypted vault record.
const registrations = new Map<string, any>();
const vaultSigners = dbManager.getObjectByIndex(RealmSchema.VaultSigner, null, true) as any;
for (const value of vaultSigners) {
checkpoint();
registrations.set(value.xpub, clone(value.registeredVaults));
}
const sources: [keyof BackupImage, RealmSchema][] = [
['wallets', RealmSchema.Wallet],
['wallets', RealmSchema.USDTWallet],
Expand All @@ -77,6 +86,12 @@ export async function captureBackupImage(checkpoint = () => {}): Promise<BackupI
if (text.length * 3 > MAX_RECORD_BYTES)
throw new Error('Backup record exceeds supported size');
const raw = JSON.parse(text);
if (kind === 'vaults')
raw.signers = raw.signers.map((signer) =>
registrations.has(signer.xpub)
? { ...signer, registeredVaults: registrations.get(signer.xpub) }
: signer
);
const record =
kind === 'signers'
? sanitizeSeedKeyForBackup(raw)
Expand Down
2 changes: 1 addition & 1 deletion tests/recovery/helpers.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const image = loadModule('src/services/backup/image.ts', { 'src/utils/service-ut
const makeImage = () => ({ wallets: {}, signers: {}, vaults: {}, nodes: {}, labels: {} });
function harness(options = {}) {
const app = { id: 'disposable', publicId: 'fixture', primarySeed: 'ab'.repeat(32), subscription: { level: 1 }, version: '2.5.16' };
const local = { Wallet: [], USDTWallet: [], Signer: [], Vault: [], NodeConnect: [], Tags: [] };
const local = { Wallet: [], USDTWallet: [], Signer: [], Vault: [], VaultSigner: [], NodeConnect: [], Tags: [] };
const remote = { appId: app.id, wallets: {}, signers: {}, nodes: [], vaults: [], labels: [] };
let vaults = [], labels = [];
const revision = () => require('node:crypto').createHash('sha256').update(JSON.stringify({remote,vaults,labels})).digest('hex');
Expand Down
112 changes: 112 additions & 0 deletions tests/recovery/vaultRegistration.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const { encryption, harness, image, makeImage } = require('./helpers.cjs');

const clone = (value) => JSON.parse(JSON.stringify(value));
const key = {
masterFingerprint: 'AABBCCDD',
xfp: 'AABBCCDD',
xpub: 'disposable-xpub',
derivationPath: "m/48'/1'/0'/2'",
registeredVaults: [{ vaultId: 'first', registered: false }],
};
const vault = (id) => ({
id,
networkType: 'TESTNET',
scriptType: 'P2WSH',
scheme: { m: 1, n: 1 },
signers: [clone(key)],
specs: {},
});

function registrationFixture({ incompleteReadback = false } = {}) {
const state = {
appImage: {
appId: 'disposable', wallets: {}, signers: {}, nodes: [],
vaults: ['first', 'second'], labels: [],
},
allVaultImages: [], labels: [], revision: 'a'.repeat(64),
};
let uploads = 0;
const f = harness({ adapter: async (endpoint, payload) => {
if (endpoint === 'getBackupSnapshot') return { data: clone(state) };
assert.equal(endpoint, 'repairAppBackup');
assert.equal(payload.expectedRevision, state.revision);
assert.equal(payload.replaceCurrentState, true);
uploads++;
Object.assign(state.appImage, {
wallets: payload.walletObject,
signers: payload.signersObject,
nodes: payload.nodes,
vaults: Object.keys(payload.vaultObject),
labels: payload.labels.map((label) => label.id),
});
state.allVaultImages = Object.values(payload.vaultObject);
if (incompleteReadback) state.allVaultImages.pop();
state.labels = payload.labels;
state.revision = 'b'.repeat(64);
return { data: { updated: true } };
} });
const cipherKey = encryption.generateEncryptionKey(f.app.primarySeed);
for (const id of state.appImage.vaults) {
const record = vault(id);
f.local.Vault.push(clone(record));
state.allVaultImages.push({
vaultId: id, vault: encryption.encrypt(cipherKey, JSON.stringify(record)),
isArchived: false,
});
}
const registeredVaults = [
{ vaultId: 'first', registered: true, hmac: 'disposable-hmac' },
{ vaultId: 'second', registered: true, registrationInfo: 'disposable-info' },
];
f.local.VaultSigner.push({ ...clone(key), registeredVaults });
return { f, state, cipherKey, registeredVaults, uploads: () => uploads };
}

test('persisted registration repairs every affected vault only after explicit action and readback', async () => {
const { f, state, cipherKey, registeredVaults, uploads } = registrationFixture();
assert.equal(await f.run(), 'different');
assert.equal(uploads(), 0);
assert.deepEqual(f.calls, ['getBackupSnapshot']);

assert.equal(await f.run(true), 'verified');
assert.equal(uploads(), 1);
assert.deepEqual(f.calls, [
'getBackupSnapshot', 'getBackupSnapshot', 'repairAppBackup', 'getBackupSnapshot',
]);
for (const encrypted of state.allVaultImages) {
const record = JSON.parse(encryption.decrypt(cipherKey, encrypted.vault));
assert.deepEqual(record.signers[0].registeredVaults, registeredVaults);
assert.equal(record.signers[0].xpub, key.xpub);
}
// Repair uses persisted metadata in its image without mutating vault records.
for (const record of f.local.Vault)
assert.deepEqual(record.signers[0].registeredVaults, key.registeredVaults);
});

test('an incomplete registration repair readback cannot be marked verified', async () => {
const { f, uploads } = registrationFixture({ incompleteReadback: true });
assert.equal(await f.run(true), 'unverified');
assert.equal(uploads(), 1);
assert.deepEqual(f.calls, ['getBackupSnapshot', 'repairAppBackup', 'getBackupSnapshot']);
});

test('registration-only drift is a difference while vault key and policy drift remain conflicts', async () => {
const local = makeImage(), remote = makeImage();
local.vaults.first = vault('first');
remote.vaults.first = clone(local.vaults.first);
local.vaults.first.signers[0].registeredVaults[0].registered = true;
assert.equal(await image.compareImages(local, remote), 'different');
for (const mutate of [
(record) => { record.signers[0].xpub = 'changed-xpub'; },
(record) => { record.signers[0].derivationPath = "m/48'/1'/1'/2'"; },
(record) => { record.networkType = 'MAINNET'; },
(record) => { record.scriptType = 'P2SH'; },
(record) => { record.scheme.m = 2; },
]) {
const changed = clone(local);
mutate(changed.vaults.first);
assert.equal(await image.compareImages(changed, remote), 'conflict');
}
});
Loading