Files
linkspin/hubsync.js
T

332 lines
25 KiB
JavaScript

// Network hub link (2026-11-12, Marty 2026-11-06: one membership from any door; the hub is the single identity; the contract
// sponsor is the truth; with no binding, the earliest join wins). Two directions, both OFF unless HUB_ENABLED=1:
// IN POST /api/hub/events body {events:[{seq, at, type, personId, data}]}, headers X-Hub-Ts (ms) + X-Hub-Sig = hex
// HMAC-SHA256(ts + "\n" + rawBody) with HUB_SECRET (network-hub lib/signing.js). Older than 5 minutes = refused. The hub
// only moves its cursor on a 2xx, so events can arrive twice: each seq is applied once (DATA_DIR/hubsync.json lastSeq).
// member.joined from another door: /v1/resolve {id} for the person, then the SAME waiting (shell) account the InstantAdPay
// registry sync makes (/api/partner/registry in server.js): accounts.ensure(email, '', 'carried', 'network'), then only
// EMPTY fields are filled (username, sponsor, wallet last, while carry.hold keeps activation off). The sponsor is placed
// first (up to 25 levels up) so the line exists. A sponsor already set here is never moved: a disagreement is logged.
// wallet.connected: fills an empty wallet here, same as the registry sync. Every other event is acknowledged and ignored
// (sponsor.changed included, on purpose). 2026-11-14: the sponsor written is person.locks.linkspin's sponsor when that lock
// exists (rule 2), and a wallet filled from the hub never switches payouts on (isQuiet): no gas, no lock, no mail.
// OUT accounts.onChange -> touch(email): a persisted outbox (DATA_DIR/hubsync.json) reports LinkSpin's own joins
// (/v1/join, sponsor named by email) and wallet links (/v1/wallet). Never blocks sign-up; failures retry with backoff.
// Gaps closed 2026-11-13 (Marty: "let's get the gaps report built"), still one way: a DELIBERATE sponsor change
// (sponsorfollow: adopt, rescue, release, expiry, admin) also goes to /v1/sponsor-change; BTC4Hits accounts (carried
// here with joinedRef 'btc4hits', no other door reports them) are reported like LinkSpin's own; every MemberActivated on
// the LinkSpin contract goes to /v1/contract-bind (contract 'linkspin', sponsor by wallet) from its own queue (binds).
// 2026-11-14: every paid Purchase goes to /v1/contract-spend (queue spends, after the binds) for the hub's rule 2.
// The InstantAdPay<->LinkSpin sync (iapsync.js, /api/partner/registry) is not touched by any of this.
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
let R = null, state = null, timer = null, flushing = false, inbound = Promise.resolve();
const ENABLED = () => /^(1|true|on|yes)$/i.test(String(process.env.HUB_ENABLED || '').trim());
const URL_ = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
const SECRET = () => String(process.env.HUB_SECRET || '').trim();
const SITE = () => String(process.env.HUB_SITE || 'linkspin').trim().toLowerCase();
const on = () => ENABLED() && SECRET().length >= 32 && /^https?:\/\//.test(URL_());
const WINDOW_MS = 5 * 60 * 1000;
const MAX_UP = 25; // how far up a sponsor line is placed for one event (bad data must not hang a request)
const FILE = () => path.join(R.dataDir, 'hubsync.json');
const norm = v => String(v || '').trim().toLowerCase();
const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2'); // logs and the admin view never show a full address
function load() {
if (state) return state;
try { state = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { state = null; }
if (!state || typeof state !== 'object') state = {};
state.lastSeq = Number(state.lastSeq) || 0; state.outbox = state.outbox || {}; state.sent = state.sent || {};
state.disagree = state.disagree || {}; state.made = state.made || {}; /* made: waiting copies created here from hub events, email -> door */ state.stats = state.stats || { events: 0, shells: 0, filled: 0, joins: 0, wallets: 0, dropped: 0, errors: 0 };
return state;
}
function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) {} }
function init(deps) { R = deps; state = null; load(); } // { dataDir, accounts, registry, carry, follow (sponsorfollow store) }
const sign = (ts, raw) => crypto.createHmac('sha256', SECRET()).update(String(ts) + '\n' + raw).digest('hex');
async function call(route, body, timeout) {
const raw = JSON.stringify(body); const ts = String(Date.now());
let r;
try { r = await fetch(URL_() + route, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Site': SITE(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sign(ts, raw) }, body: raw, signal: AbortSignal.timeout(timeout || 15000) }); }
catch (e) { throw new Error('hub ' + route + ' unreachable'); }
let out = null; try { out = await r.json(); } catch (e) {}
if (r.status >= 500 || r.status === 401) throw new Error('hub ' + route + ' ' + r.status); // down, redeploying (503) or misconfigured: try again later
return { status: r.status, body: out || {} };
}
async function resolveId(id) {
if (!id) return null;
const r = await call('/v1/resolve', { id });
return r.status === 200 && r.body.person ? r.body.person : null;
}
const refEmail = async ref => { if (!ref) return null; const a = (await R.accounts.byUsername(ref)) || (await R.accounts.byCode(ref)); return a ? norm(a.email) : null; };
function noteDisagree(e, hubSponsor, here, how) {
load().disagree[e] = { at: Date.now(), hub: hubSponsor || null, here: here || null, how }; save();
console.log('hubsync sponsor differs', how, mask(e));
}
// ---- inbound -------------------------------------------------------------------------------------------------------------
// Rule 2 (Marty 2026-11-14): the sponsor written here is the one the LinkSpin CONTRACT holds for them when it holds them
// (person.locks.linkspin, null = the top of that tree), never the plain network sponsor, which may come from another
// contract where they spent money. Each contract pays whoever it holds.
const CONTRACT = 'linkspin';
const sponsorFor = p => { const l = p && p.locks && p.locks[CONTRACT]; return l ? (l.sponsor || null) : ((p && p.sponsor) || null); };
// QUIET wallet fills (Marty 2026-11-14): accounts.onWalletLinked would have the engine switch payouts on for a wallet that lands
// here (carry.ensureOnChain: gas, a lock on the LinkSpin contract, the 'Your LinkSpin payouts are switched on' email and the
// chain-event mail and posts). A wallet filled from a hub event does none of that: server.js's wallet hook skips an email
// while isQuiet(email). The switch-on happens later the usual ways (the member's own Switch on payouts, or a purchase below).
const quiet = new Set(); const isQuiet = email => quiet.has(norm(email));
// a hub person gets a LinkSpin account the way an InstantAdPay person does: a waiting shell, empty fields filled, nothing moved.
// QUIET (Marty 2026-11-14, "join one = join all"): nothing here sends mail, a notice or a post; qa/hubsync.test.cjs checks it.
async function place(p, depth, seen) {
const e = norm(p.email); if (!e || p.blocked || seen.has(e)) return null; seen.add(e);
const ps = sponsorFor(p);
let sp = ps && ps.email ? await R.accounts.byEmail(ps.email) : null;
if (!sp && ps && ps.id && depth < MAX_UP) { // the sponsor is new here too: their line first
const up = await resolveId(ps.id);
if (up && up.email) { await place(up, depth + 1, seen); sp = await R.accounts.byEmail(up.email); }
}
R.carry.hold([e]);
try {
if (!(await R.registry.get(e))) { // a new row only: the registry is what InstantAdPay told us, iapsync's loop guard reads it
try { await R.registry.upsert({ email: e, username: p.username || null, wallet: p.wallet || null, sponsorEmail: sp ? sp.email : null, joinedAt: p.firstDoor && p.firstDoor.at, firstProperty: (p.firstDoor && p.firstDoor.site) || 'network' }); } catch (err) {}
}
let a = await R.accounts.byEmail(e);
if (!a) { const x = await R.accounts.ensure(e, '', 'carried', 'network'); if (x.created) { const st = load(); st.stats.shells++; st.made[e] = (p.firstDoor && p.firstDoor.site) || 'network'; } a = await R.accounts.byEmail(e); }
if (!a) return null;
if (p.username && !a.username) { try { const r = await R.accounts.setUsername(e, p.username); if (r && !r.error) load().stats.filled++; } catch (err) {} }
if (sp && norm(sp.email) !== e) {
if (!a.sponsorRef) {
const pv = R.follow && R.follow.get(e); // emptied on purpose here (released / rescued): an ordinary fill does not refill it
const deliberate = pv && pv.by && ['adopt', 'rescue', 'release', 'expiry', 'admin'].includes(pv.by) && !pv.sponsorEmail;
if (!deliberate && (sp.username || sp.code)) { try { await R.accounts.setSponsorRef(e, sp.username || sp.code); load().stats.filled++; } catch (err) {} }
} else {
const here = await refEmail(a.sponsorRef);
if (here !== norm(sp.email)) noteDisagree(e, sp.email, here, 'inbound'); // LinkSpin's line stands; TODO(Marty): who settles these
}
}
if (p.wallet && !a.address) { quiet.add(e); try { const r = await R.accounts.linkWallet(e, p.wallet); if (r && !r.error) load().stats.filled++; } catch (err) {} finally { quiet.delete(e); } }
return a;
} finally { R.carry.unhold([e]); }
}
async function apply(ev) {
const type = String(ev.type || '');
if (type === 'member.joined') {
if (norm(ev.data && ev.data.site) === SITE()) return; // our own join coming back
const p = await resolveId(ev.personId);
if (p && p.email) await place(p, 0, new Set());
} else if (type === 'wallet.connected') { // fill an empty wallet only, same rule as the InstantAdPay registry sync
const p = await resolveId(ev.personId); if (!p || !p.email || !p.wallet || p.blocked) return;
const a = await R.accounts.byEmail(p.email);
if (a && !a.address) { const k = norm(a.email); R.carry.hold([k]); quiet.add(k); try { await R.accounts.linkWallet(a.email, p.wallet); } finally { quiet.delete(k); R.carry.unhold([k]); } }
}
// sponsor.changed is IGNORED on purpose (checked 2026-11-14 for the switch-on): it would need the sponsorfollow.js decision
// (chain binding, window, provenance), and a member locked on the LinkSpin contract must never move anyway (the contract pays
// whoever it holds). qa/hubsync.test.cjs proves a locked member stays put.
// TODO(hub): member.blocked / unblocked, entitlement.changed, wallet.changed and the wallet-change events: ignored for now.
}
function verify(headers, raw) {
const ts = String(headers['x-hub-ts'] || ''), sig = String(headers['x-hub-sig'] || '');
if (!/^\d{10,16}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > WINDOW_MS) return false;
const want = sign(ts, raw);
return want.length === sig.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig));
}
// -> {status, body}. One batch at a time, in seq order; a seq already applied is skipped. A hub that cannot be reached
// answers 503 so the hub sends the batch again; a bad event is counted and passed (it must not stop every later one).
function receive(headers, raw) {
const run = inbound.then(async () => {
if (!on()) return { status: 404, body: { error: 'not_found' } };
if (!verify(headers, raw)) return { status: 401, body: { error: 'unauthorized' } };
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return { status: 400, body: { error: 'bad_json' } }; }
const st = load(); const events = (Array.isArray(b.events) ? b.events : []).slice().sort((x, y) => Number(x.seq) - Number(y.seq));
let applied = 0, skipped = 0;
for (const ev of events) {
const seq = Number(ev && ev.seq) || 0;
if (!seq || seq <= st.lastSeq) { skipped++; continue; }
try { await apply(ev); applied++; st.stats.events++; }
catch (e) {
if (/^hub /.test(e.message)) { save(); return { status: 503, body: { error: 'retry', seq } }; }
st.stats.errors++; st.lastError = { at: Date.now(), seq, error: String(e.message).slice(0, 160) }; console.error('hubsync event', seq, e.message);
}
st.lastSeq = seq; save();
}
return { status: 200, body: { ok: true, applied, skipped, lastSeq: st.lastSeq } };
});
inbound = run.catch(() => {});
return run;
}
// ---- outbound ------------------------------------------------------------------------------------------------------------
function touch(email) {
if (!on() || !email) return;
const e = norm(email); const st = load();
if (!st.outbox[e]) { st.outbox[e] = { at: Date.now(), tries: 0, next: 0 }; save(); }
if (!timer) timer = setTimeout(() => { timer = null; flush().catch(err => console.error('hubsync flush', err.message)); }, 3000);
}
async function report(e) {
const a = await R.accounts.byEmail(e); if (!a) return;
const st = load(); const s = st.sent[e] || {};
if (a.joinedVia !== 'carried' || a.joinedRef === 'btc4hits') { // a waiting copy of someone from another door: that door reports them (BTC4Hits has no door of its own)
const sp = a.sponsorRef ? await R.accounts.sponsorOf(e) : null;
const ref = sp ? norm(sp.email) : (a.sponsorRef || null);
const key = (a.username || '') + '|' + (ref || '');
if (s.j !== key) {
const r = await call('/v1/join', { email: e, ref: ref || undefined, username: a.username || undefined });
if (r.status === 200) {
st.stats.joins++;
const hubSp = r.body.person && r.body.person.sponsor ? norm(r.body.person.sponsor.email) : null;
if (sp && hubSp && hubSp !== norm(sp.email)) noteDisagree(e, hubSp, sp.email, 'join'); // TODO(Marty): hub says earliest join elsewhere
} else { st.stats.dropped++; console.log('hubsync join refused', r.status, r.body.error || '', mask(e)); }
s.j = key;
}
}
const w = norm(a.address);
if (w && s.w !== w) {
const r = await call('/v1/wallet', { email: e, wallet: w });
if (r.status === 200) st.stats.wallets++;
else { // 404: a waiting copy the hub has not heard of (its own door reports it); 409: the hub holds another wallet
st.stats.dropped++; console.log('hubsync wallet refused', r.status, r.body.error || '', mask(e)); }
s.w = w;
}
const rec = R.follow && R.follow.get ? R.follow.get(e) : null;
const spNow = a.sponsorRef ? await R.accounts.sponsorOf(e) : null;
if (rec && DELIBERATE.has(rec.by) && Number(rec.at) > 0 && norm(rec.sponsorEmail) === (spNow ? norm(spNow.email) : '') && s.sc !== Number(rec.at)) {
const r = await call('/v1/sponsor-change', { email: e, sponsorEmail: spNow ? spNow.email : null, by: rec.by });
if (r.status === 200) st.stats.sponsorChanges = (st.stats.sponsorChanges || 0) + 1;
else { st.stats.dropped++; noteDisagree(e, '(hub refused: ' + (r.body.error || r.status) + ')', spNow ? spNow.email : '', 'sponsor-change'); console.log('hubsync sponsor-change refused', r.status, r.body.error || '', mask(e)); }
s.sc = Number(rec.at);
}
st.sent[e] = s;
}
const DELIBERATE = new Set(['adopt', 'rescue', 'release', 'expiry', 'admin']); // sponsorfollow.js kinds the hub accepts
// chain.onEvent: a payout switch-on on the LinkSpin contract -> /v1/contract-bind (queued, retried with backoff)
function onChain(ev) {
if (ev && ev.type === 'Purchase') return onPurchase(ev);
if (!R || !on() || !ev || ev.type !== 'MemberActivated' || !ev.account) return;
(async () => {
let spW = null; try { const m = ev.sponsorId ? await R.chain.member(ev.sponsorId) : null; spW = m && m.account ? norm(m.account) : null; } catch (e) {}
const st = load(); st.binds = st.binds || [];
if (st.binds.length < 20000 && !st.binds.some(b => b.wallet === norm(ev.account))) { st.binds.push({ wallet: norm(ev.account), sponsorWallet: spW, tries: 0, next: 0 }); save(); }
})().catch(err => console.error('hubsync onChain', err.message));
}
// chain.onEvent: money paid into the LinkSpin contract (a Purchase with POL in; activation alone is not a spend) -> the hub's
// /v1/contract-spend (Marty 2026-11-14, rule 2: when two contracts hold different sponsors, the one with money spent decides
// the network sponsor). Sent after the binds in each flush; the tx hash makes a resend count once; a 404 (bind not there yet)
// waits and retries.
function onPurchase(ev) {
if (!R || !on() || !ev.buyerId || !(Number(ev.priceCents) > 0)) return;
try { if (BigInt(ev.paidWei || '0') <= 0n) return; } catch (e) { return; }
(async () => {
const m = await R.chain.member(ev.buyerId); const w = m && m.account ? norm(m.account) : null; if (!w) return;
const st = load(); st.spends = st.spends || [];
if (st.spends.length < 20000 && !st.spends.some(x => x.tx && x.tx === ev.tx)) { st.spends.push({ wallet: w, cents: Number(ev.priceCents), tx: ev.tx || null, paidAt: Number(ev.ts) || Date.now(), tries: 0, next: 0 }); save(); }
})().catch(err => console.error('hubsync onPurchase', err.message));
}
async function flushSpends() {
const st = load(); st.spends = st.spends || []; const now = Date.now();
const waitingBind = new Set((st.binds || []).map(b => b.wallet));
for (const x of st.spends.slice()) {
if (x.next > now || waitingBind.has(x.wallet)) continue; // its bind goes first
let owner = null; try { owner = await R.accounts.byAddress(x.wallet); } catch (e) {}
let r; try { r = await call('/v1/contract-spend', { contract: 'linkspin', email: owner && owner.email ? owner.email : undefined, wallet: x.wallet, cents: x.cents, tx: x.tx || undefined, at: x.paidAt }); }
catch (e) { r = { status: 0, body: { error: e.message } }; }
if (r.status === 200) { st.spends.splice(st.spends.indexOf(x), 1); st.stats.spends = (st.stats.spends || 0) + 1; }
else if (r.status === 400 || r.status === 409) { st.spends.splice(st.spends.indexOf(x), 1); st.stats.dropped++; console.log('hubsync spend refused', r.status, r.body.error || '', x.wallet); }
else { x.tries++; if (x.tries >= 20) { st.spends.splice(st.spends.indexOf(x), 1); st.stats.dropped++; } else x.next = now + Math.min(3600000, 30000 * 2 ** Math.min(x.tries, 7)); }
save();
}
}
async function flushBinds() {
const st = load(); st.binds = st.binds || []; const now = Date.now();
for (const b of st.binds.slice()) {
if (b.next > now) continue;
let owner = null; try { owner = await R.accounts.byAddress(b.wallet); } catch (e) {}
let r; try { r = await call('/v1/contract-bind', { contract: 'linkspin', email: owner && owner.email ? owner.email : undefined, wallet: b.wallet, sponsorRef: b.sponsorWallet || '' }); }
catch (e) { r = { status: 0, body: { error: e.message } }; }
if (r.status === 200) { st.binds.splice(st.binds.indexOf(b), 1); st.stats.binds = (st.stats.binds || 0) + 1; }
else if (r.status === 400 || r.status === 409) { st.binds.splice(st.binds.indexOf(b), 1); st.stats.dropped++; console.log('hubsync bind refused', r.status, r.body.error || '', b.wallet); }
else { b.tries++; if (b.tries >= 20) { st.binds.splice(st.binds.indexOf(b), 1); st.stats.dropped++; } else b.next = now + Math.min(3600000, 30000 * 2 ** Math.min(b.tries, 7)); }
save();
}
}
async function flush() {
if (!on() || flushing) return { skipped: true };
flushing = true; let done = 0, failed = 0;
try {
const st = load(); const now = Date.now();
await flushBinds(); await flushSpends();
for (const [e, o] of Object.entries(st.outbox)) {
if (o.next > now) continue;
try { await report(e); delete st.outbox[e]; done++; }
catch (err) { o.tries++; o.next = Date.now() + Math.min(3600000, 30000 * 2 ** Math.min(o.tries, 7)); o.error = String(err.message).slice(0, 120); failed++; st.stats.errors++; }
save();
}
} finally { flushing = false; }
return { done, failed };
}
const tick = () => flush();
// ---- rule 3: the holding tank asks the hub (Marty 2026-11-14) -------------------------------------------------------------
// The tank never offers anyone locked on ANY network contract, or anyone the hub already knows a sponsor for, nor a waiting
// copy made here from a hub event for someone who never signed in here (their own door's tank has them; announcing them in
// the shared topic or adopting them here would not be quiet). tank.js asks through its hooks (networkHeld, networkLocked,
// network); server.js wires them only with HUB_ENABLED, so with the flag off the tank works exactly as before. One
// /v1/locked {emails, detail} call per 2,000 emails, cached per email: fresh for 10 minutes. CONSERVATIVE when the hub cannot
// be reached: the last answer stands for up to 1 hour, after that the person is held ('unknown': not offered, not moved to
// the tank, not auto-assigned) until the hub answers again. After a failed call the hub is left alone for 2 minutes.
const HELD_FRESH_MS = 10 * 60000, HELD_STALE_MS = 60 * 60000, HELD_DOWN_MS = 2 * 60000, HELD_CHUNK = 2000;
const held = new Map(); let heldDownUntil = 0, heldBusy = Promise.resolve();
async function refreshHeld(emails, timeout) {
const run = heldBusy.then(async () => {
const now = Date.now(); const miss = emails.filter(e => { const c = held.get(e); return !c || now - c.at > HELD_FRESH_MS; });
if (!miss.length || now < heldDownUntil) return;
try {
for (let i = 0; i < miss.length; i += HELD_CHUNK) {
const part = miss.slice(i, i + HELD_CHUNK);
const r = await call('/v1/locked', { emails: part, detail: true }, timeout || 5000);
if (r.status !== 200 || !r.body || !r.body.found || typeof r.body.found !== 'object') throw new Error('hub locked ' + r.status);
if (held.size > 60000) held.clear();
const at = Date.now(); for (const e of part) held.set(e, { at, row: r.body.found[e] || null });
}
} catch (e) { heldDownUntil = Date.now() + HELD_DOWN_MS; load().stats.heldErrors = (load().stats.heldErrors || 0) + 1; console.log('hubsync: hub /v1/locked unreachable:', e.message); }
});
heldBusy = run.catch(() => {}); return run;
}
const whyHeld = (c, now) => (!c || now - c.at > HELD_STALE_MS ? 'unknown' : c.row && c.row.locked ? 'locked' : c.row && c.row.sponsored ? 'sponsored' : null);
// accounts -> Map email -> 'locked' | 'sponsored' | 'unknown' | 'hub-shell' for the ones the tank must not offer
async function heldAmong(accts, opts) {
const out = new Map(); if (!R || !on()) return out;
const list = (accts || []).filter(a => a && a.email); const emails = [...new Set(list.map(a => norm(a.email)))]; if (!emails.length) return out;
await refreshHeld(emails, opts && opts.timeout);
const now = Date.now(); const made = load().made;
for (const e of emails) { const w = whyHeld(held.get(e), now); if (w) out.set(e, w); }
for (const a of list) { const e = norm(a.email); if (!out.has(e) && made[e] && !a.lastSeen && !(Number(a.memberId) > 0)) out.set(e, 'hub-shell'); }
return out;
}
// release, rescue and expiry moves: 'locked' (on any network contract) | 'unknown' (hub not answering) | null
async function lockedAnywhere(email) {
if (!R || !on()) return null; const e = norm(email); if (!e) return null;
await refreshHeld([e]); const w = whyHeld(held.get(e), Date.now());
return w === 'locked' || w === 'unknown' ? w : null;
}
// the sponsor the hub knows for a tank member, for tank.alignToNetwork: this contract's lock first, else the network sponsor
// OFF unless HUB_TANK_ALIGN=on: aligning moves sponsors (and on LinkSpin a linked wallet then has its payouts switched on, which
// locks that sponsor on the contract), so the first run over a full tank is Marty's deliberate step, not a side effect of the
// deploy. While it is off the people the hub knows a sponsor for are simply held out of the tank (rule 3).
const alignOn = () => /^(1|true|on|yes)$/i.test(String(process.env.HUB_TANK_ALIGN || '').trim());
async function hubSponsor(email) {
if (!R || !on() || !alignOn()) return null; const e = norm(email); if (!e) return null;
await refreshHeld([e]); const c = held.get(e); if (!c || !c.row || Date.now() - c.at > HELD_STALE_MS) return null;
const l = c.row.locks && Object.prototype.hasOwnProperty.call(c.row.locks, CONTRACT) ? c.row.locks[CONTRACT] : undefined;
const sp = norm(l !== undefined ? l : c.row.sponsorEmail);
return sp && sp !== e ? { sponsorEmail: sp, via: l !== undefined ? 'network hub, LinkSpin contract' : 'network hub' } : null;
}
function adminView() {
const st = load();
return { on: on(), url: URL_(), site: SITE(), lastSeq: st.lastSeq, outbox: Object.keys(st.outbox).length, stats: st.stats, lastError: st.lastError || null,
made: Object.keys(st.made || {}).length, tankCache: held.size, tankHubDownUntil: heldDownUntil || null,
disagree: Object.entries(st.disagree).slice(-50).map(([e, d]) => ({ member: mask(e), hub: mask(d.hub), here: mask(d.here), how: d.how, at: d.at })), disagreeTotal: Object.keys(st.disagree).length };
}
module.exports = { init, on, receive, touch, onChain, flush, tick, adminView, isQuiet, heldAmong, lockedAnywhere, hubSponsor, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } };