// Durable, already-encrypted and signed wallet snapshots. No signing keys or // plaintext wallet state enter storage. Keep the last acknowledged copy too: // it is a local recovery source when an account cache has been cleared. // // A record may carry a sealed BLOB (an oversized domain bound for Blossom // storage) beside its pointer event: the blob uploads first, to at least one // server, then the event publishes. Its upload/delete authorizations are // signed at enqueue time (kind 24242 with an expiry), so delivery after // logout still needs no key. const PREFIX = 'btc-wallet-sync-outbox:'; export class SyncOutbox { constructor({ storage, send, upload = async () => false, remove = async () => false, now = Date.now, schedule = (fn, ms) => setTimeout(fn, ms), cancel = id => clearTimeout(id), warn = (...args) => console.warn(...args) }) { Object.assign(this, { storage, send, upload, remove, now, schedule, cancel, warn }); this.timer = null; this.running = false; this.retryMs = 5000; } records() { const out = []; for (let i = 0; i < this.storage.length; i++) { const key = this.storage.key(i); if (!key?.startsWith(PREFIX)) continue; try { const record = JSON.parse(this.storage.getItem(key)); if (record?.event?.kind === 30078 && Array.isArray(record.relays)) out.push({ key, ...record }); } catch {} } return out; } events(pubkey) { return this.records().filter(r => r.event.pubkey === pubkey).map(r => r.event); } // The sealed bytes behind one of our own pointer events — local recovery // needs no server round trip. localBlob(sha256) { const r = this.records().find(r => r.blob?.sha256 === sha256 && r.blob.data); return r ? b64decode(r.blob.data) : null; } clear() { if (this.timer != null) this.cancel(this.timer); this.timer = null; for (const { key } of this.records()) this.storage.removeItem(key); } // blob: { sha256, size, data (base64), servers, auth (upload authorization), // deleteAuthFor?: sha => authorization } — the last lets a superseded // blob be removed from its servers once the new one is acknowledged. enqueue({ pubkey, dtag, digest, relays, sign, blob = null }) { const key = PREFIX + pubkey + ':' + dtag; let previous; try { previous = JSON.parse(this.storage.getItem(key)); } catch {} // Same content, same route: nothing to do. A record that changed route // (an oversized domain now bound for Blossom, or back inline) is replaced // even for identical content — the stuck relay-only copy must go. if (previous?.digest === digest && !!previous.blob === !!blob) { this.wake(); return; } // A pending, never-sent event can be replaced within the same second. // Once attempted, use a later timestamp: Nostr resolves equal timestamps // by event id, which can otherwise leave the OLD snapshot in the relay. const createdAt = Math.max(Math.floor(this.now() / 1000), (previous?.event?.created_at || 0) + (previous?.attempted ? 1 : 0)); const event = sign(createdAt); if (!event || event.pubkey !== pubkey) throw new Error('Cannot sign wallet sync snapshot'); // Superseded blobs still sitting on servers: carry their cleanup forward. const cleanup = (previous?.cleanup || []).slice(); const prevBlob = previous?.blob; if (prevBlob?.sha256 && prevBlob.sha256 !== blob?.sha256 && (previous.uploaded || []).length && blob?.deleteAuthFor) { try { cleanup.push({ sha256: prevBlob.sha256, servers: previous.uploaded, auth: blob.deleteAuthFor(prevBlob.sha256) }); } catch {} } const stored = blob ? { sha256: blob.sha256, size: blob.size, data: blob.data, servers: blob.servers, auth: blob.auth } : undefined; // The same blob re-enqueued (e.g. only the pointer changed) keeps its uploads. const uploaded = blob && prevBlob?.sha256 === blob.sha256 ? (previous.uploaded || []) : []; this.storage.setItem(key, JSON.stringify({ event, digest, relays, blob: stored, uploaded, cleanup, attempted: false, acknowledged: false })); this.wake(); } wake(delay = 0) { if (this.timer != null) this.cancel(this.timer); this.timer = this.schedule(() => { this.timer = null; this.flush(); }, delay); } async flush() { if (this.running) return; this.running = true; let failed = false; try { // Independent domains must not wait for the slowest relay request. await Promise.all(this.records().filter(r => !r.acknowledged && r.event.created_at * 1000 <= this.now()).map(async r => { try { // Re-read before writing: another tab may have queued a newer copy. const current = JSON.parse(this.storage.getItem(r.key)); if (current?.event?.id !== r.event.id) return; // The blob must land on at least one server before its pointer goes out. if (current.blob && !(current.uploaded || []).length) { const bytes = b64decode(current.blob.data); const ok = []; await Promise.all((current.blob.servers || []).map(async s => { try { if (await this.upload(s, bytes, current.blob.auth)) ok.push(s); } catch {} })); const again = JSON.parse(this.storage.getItem(r.key)); if (again?.event?.id !== r.event.id) return; if (!ok.length) { failed = true; this.warn('wallet sync blob upload will retry'); return; } again.uploaded = ok; this.storage.setItem(r.key, JSON.stringify(again)); Object.assign(current, again); } current.attempted = true; this.storage.setItem(r.key, JSON.stringify(current)); const ok = await this.send(r.event, r.relays); if (!ok) { failed = true; return; } const latest = JSON.parse(this.storage.getItem(r.key)); if (latest?.event?.id === r.event.id) { latest.acknowledged = true; this.storage.setItem(r.key, JSON.stringify(latest)); } } catch (e) { failed = true; this.warn('wallet sync will retry:', e.message); } })); await this.cleanup(); } finally { this.running = f
{
"name": "coinos",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"dependencies": {
"@aws-sdk/client-ses": "^3.295.0",
"@fastify/multipart": "^7.1.2",
"@fastify/passport": "^2.2.0",
"@fastify/secure-session": "^5.2.0",
"@fastify/static": "^6.5.0",
"@fastify/websocket": "^7.2.0",
"bcrypt": "^5.0.0",
"bech32": "^2.0.0",
"clightning-client": "github:SimonVrouwe/lightning-client-js#2022-11-04_improve_doc",
"date-fns": "^2.21.3",
"fastify": "^4.5.3",
"file-type": "^18.0.0",
"got": "^12.5.3",
"jsonwebtoken": "^9.0.0",
"lnurl": "^0.24.2",
"nodemon": "^2.0.7",
"nostr": "^0.2.7",
"otplib": "^12.0.1",
"passport-jwt": "^4.0.0",
"passport-local": "1.0.0",
"pino": "8",
"pino-pretty": "^7.0.0",
"pump": "^3.0.0",
"query-string": "^6.13.1",
"readable-stream-clone": "^0.0.7",
"redis": "^4.3.1",
"sharp": "^0.31.1",
"uuid": "8",
"web-push": "^3.4.4",
"ws": "^7.4.6"
},
"devDependencies": {
"prettier": "^1.19.1"
},
"apidoc": {
"title": "CoinOS Server API Documentation",
"url": "https://coinos.io/api"
},
"type": "module"
}