diff --git a/carry.js b/carry.js index 7ec83e2..f6d3952 100644 --- a/carry.js +++ b/carry.js @@ -21,6 +21,18 @@ const ABI = ['function activateFor(address account, uint32 sponsorId) returns (u const norm = e => String(e || '').trim().toLowerCase(); function init(opts) { X = opts; } + +// ---- sponsor-follow guards (2026-10-22, sponsorfollow.js) ---- +// hold(emails): an InstantAdPay registry batch is being applied for these people; an activation that starts meanwhile +// (a wallet arriving in the same batch fires onWalletLinked) waits until the batch is done and then re-reads the account, +// so it binds the sponsor the batch settled on, never the one from before it. +// isBinding(email): an engine activation for this person is in flight; the follow rule treats them as binding (bound). +const holds = new Map(); const inflight = new Set(); +function hold(emails) { for (const e of emails || []) { const k = norm(e); if (k) holds.set(k, (holds.get(k) || 0) + 1); } } +function unhold(emails) { for (const e of emails || []) { const k = norm(e); const c = (holds.get(k) || 0) - 1; if (c > 0) holds.set(k, c); else holds.delete(k); } } +const isHeld = email => holds.has(norm(email)); +const isBinding = email => inflight.has(norm(email)); +async function waitUnheld(email, maxMs) { const t0 = Date.now(); while (isHeld(email) && Date.now() - t0 < (maxMs || 20000)) await sleep(250); } function claimDays() { const n = Number((X.siteConfig && X.siteConfig().carryClaimDays) || 3); return n > 0 ? n : 3; } const STATE = () => path.join(X.dataDir, 'carry-state.json'); function state() { try { return JSON.parse(fs.readFileSync(STATE(), 'utf8')); } catch (e) { return { claims: {}, log: [] }; } } @@ -129,8 +141,13 @@ async function nearestWithWallet(email) { // activate `acct` on this contract via the engine, after its own sponsor is there (recursive, bounded) async function ensureOnChain(acct, depth, why) { if (!acct || !acct.address) return 0; + // a registry batch is still settling this person's sponsor: wait for it, then use the account as it is NOW + if (acct.email && isHeld(acct.email)) await waitUnheld(acct.email); + if (acct.email) { try { const fresh = await X.accounts.byEmail(acct.email); if (fresh && fresh.address) acct = fresh; } catch (e) {} } try { const id = await X.chain.memberIdByAccount(acct.address); if (id) { if (Number(acct.memberId) !== Number(id)) await X.accounts.setMemberId(acct.email, id).catch(() => {}); return id; } } catch (e) {} if (!engineReady() || depth > 25) return 0; + const me = norm(acct.email); inflight.add(me); let id = 0; // binding from here: the sponsor read below is the one the contract gets + try { let sponsorId = 0; if (acct.sponsorRef) { let sp = await X.accounts.byCode(acct.sponsorRef); if (!sp) sp = await X.accounts.byUsername(acct.sponsorRef); @@ -140,7 +157,7 @@ async function ensureOnChain(acct, depth, why) { try { if (sponsorId > await X.chain.memberCount()) sponsorId = 0; } catch (e) {} // first member on a fresh contract: no catch position exists yet // send with provider rotation; after ANY error re-read the chain first (2026-10-15 seed: six activations // mined while a 403 on the follow-up read logged them as failures and skipped their notices) - let id = 0, txHash = null, lastErr = null; + let txHash = null, lastErr = null; for (let attempt = 0; attempt < 3 && !id; attempt++) { try { const w = signer(attempt); const ctr = new ethers.Contract(X.chain.getConfig().contract, ABI, w); @@ -149,11 +166,13 @@ async function ensureOnChain(acct, depth, why) { } catch (e) { lastErr = e; } for (let k = 0; k < 4 && !id; k++) { try { id = Number(await X.chain.memberIdByAccount(acct.address)) || 0; } catch (e) {} if (!id) await sleep(3000); } } + } finally { if (!id) inflight.delete(me); } // on success the flag stays until the member number is saved below if (!id) { logEvent({ type: 'activateFailed', email: acct.email, error: String((lastErr && (lastErr.shortMessage || lastErr.message)) || 'not on-chain after send').slice(0, 160) }); return 0; } logEvent({ type: 'activated', email: acct.email, id, sponsorId, tx: txHash }); // keep the member number on the account: the ledger and every name lookup go by it (2026-10-18: 340 engine // activations had none, so the live ledger showed "member #352" instead of the username) await X.accounts.setMemberId(acct.email, id).catch(() => {}); + inflight.delete(me); await noticeActivated(acct, why); return id; } @@ -205,4 +224,4 @@ async function seedAll(limit) { } function status() { const s = state(); return { engine: engineReady(), claims: Object.values(s.claims || {}), log: (s.log || []).slice(-50).reverse(), claimDays: claimDays() }; } -module.exports = { init, onJoin, resolveForChain, ensureOnChain, seedAll, status, engineReady, backfillMemberIds }; +module.exports = { init, onJoin, resolveForChain, ensureOnChain, seedAll, status, engineReady, backfillMemberIds, hold, unhold, isHeld, isBinding }; diff --git a/iapsync.js b/iapsync.js index 726edc5..c343f14 100644 --- a/iapsync.js +++ b/iapsync.js @@ -22,7 +22,14 @@ // 4. InstantAdPay ignores no-op rows, records its own lssync hash for rows whose result equals what we sent (so it does // not echo them), and at most echoes ONCE where its facts differ (kept sponsor, skipped wallet). LinkSpin's inbound // handler only fills empty fields, so that echo changes no LinkSpin account, and rule 1 stops a resend. +// +// SPONSOR FOLLOW (2026-10-22, sponsorfollow.js): a row also carries sponsorSetAt / sponsorSetBy / sponsorPrevEmail / +// sponsorSetOrigin while the sponsor is the result of a deliberate change (tank adoption, rescue, release, window expiry, +// admin edit), and `tank` (LinkSpin's own adoptions of the person, or null). Rows without them hash as before (no resend +// on deploy). Rule 2 also compares the follow facts, so a change InstantAdPay made and we applied is not sent back. +// Until InstantAdPay answers proto 2, the hash of a row carrying the new facts is not recorded (sent again later). 'use strict'; +const SF = require('./sponsorfollow'); const crypto = require('crypto'); const fs = require('fs'); const path = require('path'); @@ -42,7 +49,7 @@ function load() { } function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) {} } -function init(deps) { R = deps; load(); } // { dataDir, accounts, registry, host } +function init(deps) { R = deps; load(); } // { dataDir, accounts, registry, host, follow (sponsorfollow store), tank: () => tank } const PUBLIC = () => String(process.env.PUBLIC_URL || ('https://' + (R.host || 'linkspin.app'))).replace(/\/+$/, ''); function profileOf(a) { let socials = null; try { socials = a.socials ? (typeof a.socials === 'string' ? JSON.parse(a.socials) : a.socials) : null; } catch (e) { socials = null; } @@ -52,13 +59,18 @@ function profileOf(a) { if (!avatarUrl && !bio && !(socials && Object.keys(socials).length)) return null; return { avatarUrl, bio, socials: socials && Object.keys(socials).length ? socials : null }; } -async function rowFor(acct, byRef) { +async function rowFor(acct, byRef, tankMap) { const ref = norm(acct.sponsorRef); let sponsorEmail = null; if (ref) { const sp = byRef ? byRef.get(ref) : (await R.accounts.byUsername(ref) || await R.accounts.byCode(ref)); if (sp && sp.email !== acct.email) sponsorEmail = sp.email; } - return { email: norm(acct.email), username: acct.username || null, wallet: acct.address ? norm(acct.address) : null, sponsorEmail, joinedAt: Number(acct.created) || null, profile: profileOf(acct) }; + const row = { email: norm(acct.email), username: acct.username || null, wallet: acct.address ? norm(acct.address) : null, sponsorEmail, joinedAt: Number(acct.created) || null, profile: profileOf(acct) }; + if (R.follow) Object.assign(row, SF.rowFields(R.follow.get(acct.email), sponsorEmail) || {}); + const T = R.tank && R.tank(); + if (T) { try { row.tank = (tankMap ? tankMap.get(norm(acct.email)) : await T.summaryFor(acct.email)) || null; } catch (e) {} } + return row; } +const carriesNew = r => !!(r.sponsorSetBy || r.tank); const canon = o => { if (!o || typeof o !== 'object') return JSON.stringify(o == null ? null : o); return '{' + Object.keys(o).sort().filter(k => o[k] != null).map(k => JSON.stringify(k) + ':' + canon(o[k])).join(',') + '}'; }; -const hashOf = r => crypto.createHash('sha1').update([r.username || '', r.wallet || '', r.sponsorEmail || '', r.joinedAt || '', r.profile ? canon(r.profile) : ''].join('|')).digest('hex').slice(0, 16); +const hashOf = r => crypto.createHash('sha1').update([r.username || '', r.wallet || '', r.sponsorEmail || '', r.joinedAt || '', r.profile ? canon(r.profile) : ''].join('|') + SF.hashExtra(r)).digest('hex').slice(0, 16); // does the registry (= what InstantAdPay told us) already say everything this row says? function sameAsRegistry(r, reg) { if (!reg) return false; @@ -66,6 +78,9 @@ function sameAsRegistry(r, reg) { if (r.wallet && norm(r.wallet) !== norm(reg.wallet)) return false; if (r.sponsorEmail && norm(r.sponsorEmail) !== norm(reg.sponsorEmail)) return false; if (r.profile && canon(r.profile) !== canon(reg.profile)) return false; + // a deliberate change travels unless the registry (= InstantAdPay) already holds that very change + if (r.sponsorSetBy && (Number(r.sponsorSetAt) !== Number(reg.sponsorSetAt) || norm(r.sponsorEmail) !== norm(reg.sponsorEmail))) return false; + if (r.tank) return false; // our own adoptions are news to InstantAdPay (the registry holds only its side); the hash stops a resend return true; } // rows worth sending: changed since our last push and not just InstantAdPay's own facts coming back @@ -91,8 +106,9 @@ async function push(rows) { const st = load(); let sent = 0; let result = null; for (let i = 0; i < rows.length; i += 100) { const chunk = rows.slice(i, i + 100); result = await post(chunk); sent += chunk.length; + const peerNew = Number(result && result.proto) >= SF.PROTO; if (R.follow) R.follow.setPeer(peerNew ? SF.PROTO : 1); for (const r of chunk) { - st.hashes[r.email] = hashOf(r); + if (peerNew || !carriesNew(r)) st.hashes[r.email] = hashOf(r); // an old InstantAdPay ignored the new facts: send again later // a LinkSpin-first member becomes part of the network registry, labelled as such (rule 3 above) if (!(await R.registry.get(r.email))) { try { await R.registry.upsert({ email: r.email, username: r.username, wallet: r.wallet, sponsorEmail: r.sponsorEmail, joinedAt: r.joinedAt, profile: r.profile, firstProperty: 'linkspin' }); } catch (e) {} } } @@ -114,7 +130,8 @@ async function tick(force) { try { const all = await R.accounts.listAll(50000); const st = load(); const byRef = new Map(); for (const a of all) { if (a.username) byRef.set(norm(a.username), a); if (a.code) byRef.set(norm(a.code), a); } - const rows = []; for (const a of all) { if (!a.email) continue; rows.push(await rowFor(a, byRef)); } + const T = R.tank && R.tank(); let tankMap = null; if (T) { try { tankMap = await T.summaryMap(); } catch (e) { tankMap = null; } } + const rows = []; for (const a of all) { if (!a.email) continue; rows.push(await rowFor(a, byRef, tankMap || (T ? new Map() : null))); } if (force) for (const r of rows) delete st.hashes[r.email]; const go = await select(rows); const sent = go.length ? await push(go) : 0; diff --git a/public/admin.html b/public/admin.html index 131f620..c74abb3 100644 --- a/public/admin.html +++ b/public/admin.html @@ -210,6 +210,13 @@
Adoptions (newest first)
Deliberate changes (a tank adoption, a rescue, a release, the end of an adoption window, an admin edit) follow to the other site until the member is bound on that site's contract. Everything else keeps the first sponsor. To settle a difference, pick the side whose sponsor is right: it is applied on the other site, unless the member is already bound there.
+ +