diff options
| author | Adam Soltys <[email protected]> | 2026-12-04 13:19:32 -0700 |
|---|---|---|
| committer | Adam Soltys <[email protected]> | 2026-12-04 13:19:32 -0700 |
| commit | c13388dc345f74b194eb106680a0cf9cf6da013f (patch) | |
| tree | cf9364494ab455124b45be191904698dd957f196 /migrator | |
| parent | d18cf2b2db74a9eb8b2a62708e8158428bb90a15 (diff) | |
| download | coinosv3-server-c13388dc345f74b194eb106680a0cf9cf6da013f.tar.gz coinosv3-server-c13388dc345f74b194eb106680a0cf9cf6da013f.zip | |
migrator: moves wallets' Spending coins off the retired ark.coinos.io to ark2.coinos.io.
ark.coinos.io's server key was stolen in the 2026-12-04 breach. The app (coinosv3 5bf43a1) now points "coinos" at ark2.coinos.io and, for a wallet still holding coins on the old server, asks this service for a deposit address there (a key of its own per migration, so each payer is known), sends the coins, and gets the same amount paid on ark2 from this service's float. Payouts are crash-safe the way the names forwarder's are (in-flight record before the send, the float wallet's own send record decides on retry).
Bounded against the stolen key (whoever holds it can co-sign a second spend of their own old coins): boarding is off on the old server, each migration over maxSat and all of them past dailySat per UTC day wait for an admin release. Admin: summary, release, and boarding on-chain coins into the ark2 float.
migrator/e2e-test.js runs it on regtest against two captaind 0.8.0-coinos servers: happy path, wrong-server destination refused, cap hold + release, restart without double payment, and the app's migrate.js sending several coins in batches — all 19 checks pass.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VMan6WoqaQDYdpWkatPCar
Diffstat (limited to 'migrator')
| -rw-r--r-- | migrator/e2e-test.js | 147 | ||||
| -rw-r--r-- | migrator/server.js | 215 |
2 files changed, 362 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); diff --git a/migrator/server.js b/migrator/server.js new file mode 100644 index 0000000..8b1f8fe --- /dev/null +++ b/migrator/server.js @@ -0,0 +1,215 @@ +// migrator: moves wallets' Spending coins from the retiring coinos Ark server +// (ark.coinos.io — its server key was stolen in the 2026-12-04 breach) to its +// successor (ark2.coinos.io), so nobody has to do anything by hand. +// +// A wallet asks for a migration naming its own ark2 address. It gets back a +// deposit address on the old server, on a key used for nothing else, and +// sends its old coins there. Once they arrive here, the same amount is paid +// to its ark2 address from this service's ark2 float. Arkoor carries no fee, +// so the wallet ends up with exactly what it had. coinos gets the old coins +// back when their rounds expire (the old server's sweep). +// +// The one attack this has to bound: whoever holds the stolen server key can +// co-sign a second spend of any old coin of their own, so coins they send here +// can be exited on-chain behind our back after we have paid out. Boarding is +// off on the old server (nobody can mint new old coins), the wallets whose +// seeds were exposed are swept first, and every migration is capped +// (maxSat each, dailySat for all of them per UTC day) — anything over waits +// for an admin release. +// +// Config (MIGRATOR_CONFIG, JSON): +// { port, mnemonic, adminToken, maxSat, dailySat, stateFile?, +// old: { ark, esplora, network, honorsExpired }, +// new: { ark, esplora, network, honorsExpired } } + +import { readFileSync, writeFileSync, renameSync, existsSync } from 'node:fs'; +import { randomBytes } from 'node:crypto'; +import { HDKey } from '@scure/bip32'; +import { mnemonicToSeedSync } from '@scure/bip39'; +import { hex } from '@scure/base'; +import { ArkManager } from '../coinosv3/src/ark/manager.js'; +import { decodeAddress, arkIdFromServerPubkey } from '../coinosv3/src/ark/proto.js'; + +const CFG = JSON.parse(readFileSync(process.env.MIGRATOR_CONFIG || '/etc/coinosv3/config.json', 'utf8')); +const STATE_FILE = CFG.stateFile || '/data/migrator.json'; +const MAX_SAT = CFG.maxSat ?? 1_000_000; +const DAILY_SAT = CFG.dailySat ?? 20_000_000; +const log = (...a) => console.log(new Date().toISOString(), ...a); + +const state = existsSync(STATE_FILE) + ? JSON.parse(readFileSync(STATE_FILE, 'utf8')) + : { old: null, new: null, sessions: {}, days: {} }; +function persist() { + const tmp = STATE_FILE + '.tmp'; + writeFileSync(tmp, JSON.stringify(state)); + renameSync(tmp, STATE_FILE); +} + +const root = HDKey.fromMasterSeed(mnemonicToSeedSync(CFG.mnemonic)); +async function openWallet(side, path) { + const c = CFG[side]; + return new ArkManager({ + account: root.derive(path), + storage: { load: () => state[side] || null, save: (s) => { state[side] = s; persist(); } }, + arkUrl: c.ark, esploraUrl: c.esplora, network: c.network || 'mainnet', honorsExpired: !!c.honorsExpired, + }).init(); +} +const oldW = await openWallet('old', "m/86'/0'/20'"); +const newW = await openWallet('new', "m/86'/0'/21'"); +await oldW.sync().catch((e) => log('old sync: ' + e.message)); +await newW.sync().catch((e) => log('new sync: ' + e.message)); +log(`migrator ready — old ${CFG.old.ark} (deposits ${oldW.balance().spendableSat} sat), new ${CFG.new.ark} (float ${newW.balance().spendableSat} sat)`); + +const isNewServerAddress = (addr) => { + try { return decodeAddress(addr).arkId === hex.encode(arkIdFromServerPubkey(newW.serverPub)); } catch { return false; } +}; +const today = () => new Date().toISOString().slice(0, 10); +const json = (body, status = 200) => new Response(JSON.stringify(body), { + status, headers: { 'content-type': 'application/json', 'access-control-allow-origin': '*', 'access-control-allow-headers': 'content-type, x-admin-token' }, +}); +const view = (s) => ({ id: s.id, dest: s.dest, depositAddress: s.depositAddress, receivedSat: s.receivedSat, paidSat: s.paidSat, status: s.status, created: s.created }); + +// Count what each migration's deposit key has received. Coins are counted once +// each, by id, whatever happens to them in the deposit wallet afterwards. +function credit() { + const byKey = new Map(Object.values(state.sessions).map((s) => [s.keyIndex, s])); + let changed = false; + for (const v of oldW.state.vtxos) { + const s = byKey.get(v.keyIndex); + if (!s || s.vtxoIds.includes(v.id)) continue; + s.vtxoIds.push(v.id); + s.receivedSat += v.amountSat; + s.updated = Date.now(); + changed = true; + log(`migration ${s.id}: received ${v.amountSat} sat (${s.receivedSat} total)`); + } + if (changed) persist(); +} + +// Pay what a migration is owed on the new server. Crash-safe the way the names +// forwarder is: the send is written down as in flight before it starts, and a +// retry asks the float wallet's own record of that send before paying again. +async function settle(s) { + if (s.inflight) { + const f = s.inflight; + const acts = (newW.state.actions || []).filter((a) => a.type === 'send' && a.destAddress === s.dest + && a.amountSat === f.sat && Number(String(a.id).slice(5).replace(/-+$/, '')) >= f.after); + const refused = acts.find((a) => a.step === 'registered' && /PostArkoorMessage: status 3\b/.test(a.lastError || '')); + if (refused) { refused.step = 'done'; refused.undelivered = refused.lastError; newW._save(); } + if (acts.some((a) => a.step === 'done')) { + s.paidSat += f.sat; s.payouts.push({ sat: f.sat, ts: Date.now() }); s.inflight = null; + persist(); + log(`migration ${s.id}: payout of ${f.sat} sat completed`); + } else if (acts.some((a) => a.step !== 'failed')) { + await newW.resumePending?.().catch((e) => log(`migration ${s.id}: resume: ${e.message}`)); + return; + } else { + s.inflight = null; persist(); + } + } + const due = s.receivedSat - s.paidSat; + if (due <= 0) { s.status = s.receivedSat > 0 ? 'done' : 'waiting'; return; } + if (s.receivedSat > MAX_SAT && !s.released) { s.status = 'held'; persist(); return; } + const day = today(); + if ((state.days[day] || 0) + due > DAILY_SAT && !s.released) { s.status = 'held-daily'; persist(); return; } + if (newW.balance().spendableSat < due) { s.status = 'waiting-liquidity'; persist(); return; } + s.inflight = { sat: due, after: Date.now() }; + s.status = 'paying'; + persist(); + try { + await newW.send(s.dest, due); + } catch (e) { + log(`migration ${s.id}: payout of ${due} sat failed: ${e.message}`); + return; // the in-flight record decides on the next pass + } + s.paidSat += due; s.payouts.push({ sat: due, ts: Date.now() }); s.inflight = null; s.status = 'done'; + state.days[day] = (state.days[day] || 0) + due; + persist(); + log(`migration ${s.id}: paid ${due} sat to ${s.dest.slice(0, 20)}…`); +} + +let ticking = false; +async function tick() { + if (ticking) return; + ticking = true; + try { + await oldW.sync().catch((e) => log('old sync: ' + e.message)); + await newW.sync().catch((e) => log('new sync: ' + e.message)); + credit(); + for (const s of Object.values(state.sessions)) { + if (s.receivedSat > s.paidSat || s.inflight) await settle(s).catch((e) => log(`migration ${s.id}: ${e.message}`)); + } + } finally { ticking = false; } +} +setInterval(tick, 10_000); + +const admin = (req) => CFG.adminToken && req.headers.get('x-admin-token') === CFG.adminToken; + +Bun.serve({ + port: CFG.port || 8802, + async fetch(req) { + const url = new URL(req.url); + const p = url.pathname.replace(/^\/migrate/, '') || '/'; + if (req.method === 'OPTIONS') return json({}); + try { + if (req.method === 'GET' && p === '/info') { + return json({ old: CFG.old.ark, new: CFG.new.ark, oldServerPubkey: hex.encode(oldW.serverPub), newServerPubkey: hex.encode(newW.serverPub), maxSat: MAX_SAT }); + } + // { dest: an ark2 address of the migrating wallet } → a deposit address on the old server + if (req.method === 'POST' && p === '/start') { + const { dest } = await req.json(); + if (typeof dest !== 'string' || !isNewServerAddress(dest)) return json({ error: 'dest must be an address on ' + CFG.new.ark }, 400); + const existing = Object.values(state.sessions).find((s) => s.dest === dest && s.receivedSat === 0); + if (existing) return json(view(existing)); + const { keyIndex, address } = oldW.freshAddress(); + const s = { id: randomBytes(8).toString('hex'), dest, keyIndex, depositAddress: address, created: Date.now(), receivedSat: 0, paidSat: 0, vtxoIds: [], payouts: [], status: 'waiting' }; + state.sessions[s.id] = s; + persist(); + log(`migration ${s.id}: started for ${dest.slice(0, 20)}… (deposit key ${keyIndex})`); + return json(view(s)); + } + const m = p.match(/^\/status\/([0-9a-f]{16})$/); + if (req.method === 'GET' && m) { + const s = state.sessions[m[1]]; + if (!s) return json({ error: 'unknown migration' }, 404); + tick(); + return json(view(s)); + } + // ---- admin ---- + if (p.startsWith('/admin/')) { + if (!admin(req)) return json({ error: 'unauthorized' }, 401); + if (req.method === 'GET' && p === '/admin/summary') { + const ss = Object.values(state.sessions); + return json({ + deposits: oldW.balance(), float: newW.balance(), days: state.days, + sessions: ss.length, receivedSat: ss.reduce((t, s) => t + s.receivedSat, 0), paidSat: ss.reduce((t, s) => t + s.paidSat, 0), + held: ss.filter((s) => s.status.startsWith('held')).map(view), + }); + } + const rel = p.match(/^\/admin\/release\/([0-9a-f]{16})$/); + if (req.method === 'POST' && rel) { + const s = state.sessions[rel[1]]; + if (!s) return json({ error: 'unknown migration' }, 404); + s.released = true; persist(); tick(); + return json(view(s)); + } + // float liquidity on the new server: board on-chain coins into it + if (req.method === 'POST' && p === '/admin/board') { + const { amountSat } = await req.json(); + return json(await newW.startBoard(Number(amountSat))); + } + if (req.method === 'POST' && p === '/admin/board/complete') { + const { actionId, txid } = await req.json(); + const a = await newW.completeBoard(actionId, txid); + return json({ step: a.step, error: a.lastError || null }); + } + if (req.method === 'GET' && p === '/admin/float-address') return json({ address: newW.address() }); + } + return json({ error: 'not found' }, 404); + } catch (e) { + log(`${req.method} ${url.pathname}: ${e.message}`); + return json({ error: e.message }, 500); + } + }, +}); +log(`migrator listening on :${CFG.port || 8802}`); |
