aboutsummaryrefslogtreecommitdiffstats
path: root/migrator/e2e-test.js
diff options
context:
space:
mode:
Diffstat (limited to 'migrator/e2e-test.js')
-rw-r--r--migrator/e2e-test.js147
1 files changed, 147 insertions, 0 deletions
diff --git a/migrator/e2e-test.js b/migrator/e2e-test.js
new file mode 100644
index 0000000..714e7a4
--- /dev/null
+++ b/migrator/e2e-test.js
@@ -0,0 +1,147 @@
+// End-to-end test of the migrator on regtest. Needs two captainds (old on
+// :3575, new on :3585), esplora on :30002 and the `bc` regtest bitcoind
+// (docker exec bc bitcoin-cli -rpcwallet=coinos). Run: bun migrator/e2e-test.js
+import { execSync, spawn } from 'node:child_process';
+import { mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { wordlist } from '@scure/bip39/wordlists/english';
+import { generateMnemonic, mnemonicToSeedSync } from '@scure/bip39';
+import { HDKey } from '@scure/bip32';
+import { ArkManager } from '../coinosv3/src/ark/manager.js';
+
+const OLD = process.env.OLD_ARK || 'http://127.0.0.1:3575';
+const NEW = process.env.NEW_ARK || 'http://127.0.0.1:3585';
+const ESPLORA = process.env.ESPLORA_URL || 'http://127.0.0.1:30002';
+const BCLI = 'docker exec bc bitcoin-cli -rpcwallet=coinos';
+const PORT = 8812;
+const API = `http://127.0.0.1:${PORT}/migrate`;
+const ADMIN = 'test-admin-token';
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const sh = (cmd) => execSync(cmd, { shell: '/bin/bash' }).toString().trim();
+const mine = (n = 1) => sh(`${BCLI} generatetoaddress ${n} $(${BCLI} getnewaddress) >/dev/null`);
+let ok = true;
+const check = (name, cond, detail = '') => { console.log(` ${cond ? '✓' : '✗'} ${name}${detail ? ' — ' + detail : ''}`); if (!cond) ok = false; };
+const api = async (path, body, admin) => {
+ const r = await fetch(API + path, { method: body ? 'POST' : 'GET', headers: { 'content-type': 'application/json', ...(admin ? { 'x-admin-token': ADMIN } : {}) }, body: body ? JSON.stringify(body) : undefined });
+ return { status: r.status, ...(await r.json()) };
+};
+const memStore = () => { const s = { raw: null }; return { load: () => (s.raw ? JSON.parse(s.raw) : null), save: (x) => { s.raw = JSON.stringify(x); } }; };
+async function board(mgr, sat) {
+ const { actionId, fundingAddress, feeSat } = await mgr.startBoard(sat);
+ const raw = sh(`${BCLI} createrawtransaction '[]' '[{"${fundingAddress}":${(sat / 1e8).toFixed(8)}}]'`);
+ const funded = JSON.parse(sh(`${BCLI} fundrawtransaction ${raw} '{"changePosition":1}'`));
+ const signed = JSON.parse(sh(`${BCLI} signrawtransactionwithwallet ${funded.hex}`));
+ const txid = sh(`${BCLI} sendrawtransaction ${signed.hex}`);
+ return { actionId, txid, feeSat };
+}
+async function settleBoard(mgr, actionId, txid) {
+ await mgr.completeBoard(actionId, txid);
+ mine(3);
+ for (let i = 0; i < 30 && mgr.pendingActions().length; i++) { await sleep(2000); await mgr.sync(); }
+}
+
+// --- the migrator under test ---
+const dir = mkdtempSync(join(tmpdir(), 'migrator-'));
+const cfgPath = join(dir, 'config.json');
+writeFileSync(cfgPath, JSON.stringify({
+ port: PORT, mnemonic: generateMnemonic(wordlist), adminToken: ADMIN, maxSat: 200000, dailySat: 1000000,
+ stateFile: join(dir, 'state.json'),
+ old: { ark: OLD, esplora: ESPLORA, network: 'regtest', honorsExpired: true },
+ new: { ark: NEW, esplora: ESPLORA, network: 'regtest', honorsExpired: true },
+}));
+let proc;
+const startMigrator = async () => {
+ proc = spawn('bun', ['migrator/server.js'], { env: { ...process.env, MIGRATOR_CONFIG: cfgPath }, stdio: ['ignore', 'pipe', 'pipe'] });
+ proc.stdout.on('data', (d) => process.stdout.write(' [migrator] ' + d));
+ proc.stderr.on('data', (d) => process.stdout.write(' [migrator!] ' + d));
+ for (let i = 0; i < 60; i++) { try { if ((await api('/info')).newServerPubkey) return; } catch {} await sleep(500); }
+ throw new Error('migrator did not start');
+};
+await startMigrator();
+const info = await api('/info');
+check('info names both servers', info.oldServerPubkey && info.newServerPubkey && info.oldServerPubkey !== info.newServerPubkey);
+
+console.log('\n[1] fund the migrator float on the new server');
+const fb = await api('/admin/board', { amountSat: 500000 }, true);
+check('admin board returns a funding address', !!fb.fundingAddress, fb.error || '');
+const raw = sh(`${BCLI} createrawtransaction '[]' '[{"${fb.fundingAddress}":0.00500000}]'`);
+const funded = JSON.parse(sh(`${BCLI} fundrawtransaction ${raw} '{"changePosition":1}'`));
+const signed = JSON.parse(sh(`${BCLI} signrawtransactionwithwallet ${funded.hex}`));
+const ftx = sh(`${BCLI} sendrawtransaction ${signed.hex}`);
+await api('/admin/board/complete', { actionId: fb.actionId, txid: ftx }, true);
+mine(3);
+let sum;
+for (let i = 0; i < 30; i++) { await sleep(2000); await api('/admin/board/complete', { actionId: fb.actionId, txid: ftx }, true); sum = await api('/admin/summary', null, true); if (sum.float.spendableSat > 0) break; }
+check('float is spendable on the new server', sum.float.spendableSat > 400000, JSON.stringify(sum.float));
+
+console.log('\n[2] a user wallet with coins on the old server');
+const account = HDKey.fromMasterSeed(mnemonicToSeedSync(generateMnemonic(wordlist))).derive("m/84'/1'/0'");
+const oldM = await new ArkManager({ account, storage: memStore(), arkUrl: OLD, esploraUrl: ESPLORA, network: 'regtest', honorsExpired: true }).init();
+const newM = await new ArkManager({ account, storage: memStore(), arkUrl: NEW, esploraUrl: ESPLORA, network: 'regtest', honorsExpired: true }).init();
+const b = await board(oldM, 150000);
+await settleBoard(oldM, b.actionId, b.txid);
+const have = oldM.balance().spendableSat;
+check('user has old-server coins', have > 0, String(have));
+
+console.log('\n[3] destination checks');
+const bad = await api('/start', { dest: oldM.address() });
+check('an old-server address is refused as destination', bad.status === 400, bad.error);
+
+console.log('\n[4] migrate');
+const s = await api('/start', { dest: newM.address() });
+check('start returns a deposit address on the old server', !!s.depositAddress && s.id, s.error || '');
+const again = await api('/start', { dest: newM.address() });
+check('starting again before paying reuses the same deposit', again.id === s.id);
+await oldM.send(s.depositAddress, have);
+check('user old balance is now 0', oldM.balance().spendableSat === 0, JSON.stringify(oldM.balance()));
+let st;
+for (let i = 0; i < 30; i++) { await sleep(2000); st = await api('/status/' + s.id); if (st.status === 'done') break; }
+check('migration done', st.status === 'done', JSON.stringify(st));
+for (let i = 0; i < 15 && newM.balance().spendableSat < have; i++) { await sleep(1000); await newM.sync(); }
+check('user received exactly the same amount on the new server', newM.balance().spendableSat === have, `${newM.balance().spendableSat} vs ${have}`);
+
+console.log('\n[5] cap: a migration over maxSat waits for an admin');
+const account2 = HDKey.fromMasterSeed(mnemonicToSeedSync(generateMnemonic(wordlist))).derive("m/84'/1'/0'");
+const oldM2 = await new ArkManager({ account: account2, storage: memStore(), arkUrl: OLD, esploraUrl: ESPLORA, network: 'regtest', honorsExpired: true }).init();
+const newM2 = await new ArkManager({ account: account2, storage: memStore(), arkUrl: NEW, esploraUrl: ESPLORA, network: 'regtest', honorsExpired: true }).init();
+const b2 = await board(oldM2, 260000);
+await settleBoard(oldM2, b2.actionId, b2.txid);
+const have2 = oldM2.balance().spendableSat;
+const s2 = await api('/start', { dest: newM2.address() });
+await oldM2.send(s2.depositAddress, have2);
+for (let i = 0; i < 20; i++) { await sleep(2000); st = await api('/status/' + s2.id); if (st.status.startsWith('held')) break; }
+check('over-cap migration is held, nothing paid', st.status === 'held' && st.paidSat === 0, JSON.stringify(st));
+
+console.log('\n[6] restart the migrator, then release: paid once, not twice');
+proc.kill(); await sleep(1500); await startMigrator();
+const rel = await api('/admin/release/' + s2.id, {}, true);
+check('release accepted', rel.id === s2.id, rel.error || '');
+for (let i = 0; i < 30; i++) { await sleep(2000); st = await api('/status/' + s2.id); if (st.status === 'done') break; }
+check('released migration paid', st.status === 'done' && st.paidSat === have2, JSON.stringify(st));
+for (let i = 0; i < 15 && newM2.balance().spendableSat < have2; i++) { await sleep(1000); await newM2.sync(); }
+await sleep(15000); await newM2.sync();
+check('second user got exactly their amount, once', newM2.balance().spendableSat === have2, `${newM2.balance().spendableSat} vs ${have2}`);
+const first = await api('/status/' + s.id);
+check('first migration still paid exactly once', first.paidSat === have, JSON.stringify(first));
+
+console.log('\n[7] the app side (src/ark/migrate.js): several coins, sent in batches, no user action');
+const { migrateWallet, awaitMigration } = await import('../coinosv3/src/ark/migrate.js');
+const account3 = HDKey.fromMasterSeed(mnemonicToSeedSync(generateMnemonic(wordlist))).derive("m/84'/1'/0'");
+const oldM3 = await new ArkManager({ account: account3, storage: memStore(), arkUrl: OLD, esploraUrl: ESPLORA, network: 'regtest', honorsExpired: true }).init();
+const newM3 = await new ArkManager({ account: account3, storage: memStore(), arkUrl: NEW, esploraUrl: ESPLORA, network: 'regtest', honorsExpired: true }).init();
+for (const sat of [40000, 25000, 21000]) { const bb = await board(oldM3, sat); await settleBoard(oldM3, bb.actionId, bb.txid); }
+const have3 = oldM3.balance().spendableSat;
+const coins3 = oldM3.vtxos().filter((v) => v.state === 'spendable').length;
+check('third user holds several coins on the old server', coins3 >= 3, `${coins3} coins, ${have3} sat`);
+const res = await migrateWallet(oldM3, { migratorUrl: API, dest: newM3.address(), maxInputs: 2, log: (m) => console.log(' ' + m) });
+check('everything sent, nothing left behind', res.sentSat === have3 && res.leftSat === 0, JSON.stringify(res));
+const fin = await awaitMigration(API, res.id, { timeoutMs: 60000 });
+check('migrator paid the whole amount', fin.status === 'done' && fin.paidSat === have3, JSON.stringify(fin));
+for (let i = 0; i < 15 && newM3.balance().spendableSat < have3; i++) { await sleep(1000); await newM3.sync(); }
+check('the wallet holds the same amount on the new server', newM3.balance().spendableSat === have3, `${newM3.balance().spendableSat} vs ${have3}`);
+
+proc.kill();
+console.log(ok ? '\nALL PASSED' : '\nFAILURES');
+process.exit(ok ? 0 : 1);