aboutsummaryrefslogtreecommitdiffstats
path: root/migrator/server.js
blob: cf654ef30f2d892c3552f71ea2672212888281f6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// 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();
          const b = await newW.startBoard(Number(amountSat));
          (state.boards ||= {})[b.actionId] = { fundingAddress: b.fundingAddress, amountSat: Number(amountSat) };
          persist();
          return json(b);
        }
        // { actionId, txid }: the funding tx may come from any wallet, so find
        // the output paying the board address (exact amount) rather than
        // assuming it's the first.
        if (req.method === 'POST' && p === '/admin/board/complete') {
          const { actionId, txid } = await req.json();
          const b = state.boards?.[actionId];
          if (!b) return json({ error: 'unknown board' }, 404);
          const r = await fetch(`${CFG.new.esplora}/tx/${txid}`);
          if (!r.ok) return json({ error: `funding tx ${txid} not seen by ${CFG.new.esplora} yet — try again shortly` }, 409);
          const tx = await r.json();
          const vout = tx.vout.findIndex((o) => o.scriptpubkey_address === b.fundingAddress && o.value === b.amountSat);
          if (vout < 0) return json({ error: `no output of exactly ${b.amountSat} sat to ${b.fundingAddress} in ${txid}` }, 400);
          const a = await newW.completeBoard(actionId, txid, vout);
          return json({ step: a.step, vout, confs: a.confs ?? null, 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}`);