diff options
Diffstat (limited to 'migrator/server.js')
| -rw-r--r-- | migrator/server.js | 215 |
1 files changed, 215 insertions, 0 deletions
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}`); |
