Files
webworthit/jobs.js
T

158 lines
12 KiB
JavaScript

// The check pipeline, run in a small in-process queue (2 at a time): website -> contract -> chain -> scoring -> fact check.
// Everything here only READS public data. No wallet, no key, no transaction.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { spawn } = require('child_process');
const db = require('./db');
const website = require('./website');
const report = require('./report');
const CHAINS = { bsc: { name: 'BNB Chain', rpc: ['https://bsc-dataseed.bnbchain.org', 'https://bsc-rpc.publicnode.com'] },
polygon: { name: 'Polygon', rpc: ['https://polygon-bor-rpc.publicnode.com', 'https://polygon.drpc.org'] },
eth: { name: 'Ethereum', rpc: ['https://ethereum-rpc.publicnode.com', 'https://eth.drpc.org'] },
base: { name: 'Base', rpc: ['https://base-rpc.publicnode.com', 'https://mainnet.base.org'] } };
const STEPS = ['website', 'contract', 'chain', 'scoring', 'factcheck'];
const STEP_NAMES = { website: 'Reading the website', contract: 'Finding the contract', chain: 'Reading the chain', scoring: 'Scoring', factcheck: 'Fact-checking' };
const CONCURRENCY = Number(process.env.JOBS || 2);
const CHAIN_BUDGET = Number(process.env.CHAIN_BUDGET_S || 420);
// Scratch for chain scans lives OUTSIDE DATA_DIR: docstore.js routes every *.json read/write under DATA_DIR to MySQL,
// so evidence.json written there by scan.py was invisible to fs.readFileSync (ENOENT on staging, 2026-11-16).
const WORK = () => path.join(require('os').tmpdir(), 'wwi-work');
let running = 0; const queue = [];
async function getCode(chain, a) {
for (const u of CHAINS[chain].rpc) {
try {
const r = await fetch(u, { method: 'POST', headers: { 'Content-Type': 'application/json' }, signal: AbortSignal.timeout(12000), body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_getCode', params: [a, 'latest'] }) });
const j = await r.json(); if (j && typeof j.result === 'string') return j.result;
} catch (e) {}
}
return null;
}
function enqueue(id) { queue.push(id); pump(); }
function pump() { while (running < CONCURRENCY && queue.length) { const id = queue.shift(); running++; run(id).catch(e => console.error('job', id, e)).finally(() => { running--; pump(); }); } }
const qpos = id => queue.indexOf(id);
async function setStep(id, steps, name, state, note) {
steps[name] = Object.assign(steps[name] || {}, { state, note: note || (steps[name] || {}).note || null, at: Date.now() });
await db.q('UPDATE checks SET step = ?, steps_json = ? WHERE id = ?', [name, JSON.stringify(steps), id]);
}
function runScan(chain, address, dir, abiFile, onStep) {
return new Promise((resolve, reject) => {
const args = [path.join(__dirname, 'chain', 'scan.py'), chain, address, dir, '--budget', String(CHAIN_BUDGET)];
if (abiFile) args.push('--hint-abi', abiFile);
const p = spawn(process.env.PYTHON || 'python3', args, { cwd: path.join(__dirname, 'chain'), env: Object.assign({}, process.env, { PYTHONUNBUFFERED: '1' }) });
let err = ''; let buf = '';
const kill = setTimeout(() => { try { p.kill('SIGKILL'); } catch (e) {} }, (CHAIN_BUDGET + 240) * 1000);
p.stdout.on('data', d => { buf += d; let i; while ((i = buf.indexOf('\n')) >= 0) { const line = buf.slice(0, i); buf = buf.slice(i + 1); try { const j = JSON.parse(line); if (j.step) onStep(j); } catch (e) {} } });
p.stderr.on('data', d => { err += d; if (err.length > 20000) err = err.slice(-20000); });
p.on('close', code => { clearTimeout(kill); if (code === 0) resolve(); else reject(new Error('chain scan exited ' + code + ': ' + err.slice(-600))); });
});
}
async function run(id) {
const c = await db.one('SELECT * FROM checks WHERE id = ?', [id]); if (!c) return;
const steps = {}; const t = { start: Date.now() };
await db.q("UPDATE checks SET status = 'running', started = ? WHERE id = ?", [Date.now(), id]);
let siteRes = null; let chain = c.chain; let address = c.address ? c.address.toLowerCase() : null; let pickedNote = null;
try {
// 1. website
if (c.website) {
await setStep(id, steps, 'website', 'running');
try {
siteRes = await website.scan(c.website);
if (siteRes.screenshot) await db.q('REPLACE INTO screenshots (check_id, mime, bytes, created) VALUES (?,?,?,?)', [id, 'image/jpeg', siteRes.screenshot, Date.now()]);
await setStep(id, steps, 'website', siteRes.ok ? 'done' : 'failed', siteRes.ok ? 'Read "' + (siteRes.title || siteRes.finalUrl || c.website) + '"' : (siteRes.notes[0] || 'The page could not be read.'));
} catch (e) { siteRes = { ok: false, notes: ['The page could not be read: ' + String(e.message).split('\n')[0].slice(0, 160)], addresses: [], chainHints: {}, abi: [] }; await setStep(id, steps, 'website', 'failed', siteRes.notes[0]); }
} else await setStep(id, steps, 'website', 'skipped', 'No website entered.');
t.website = Date.now();
// 2. contract
await setStep(id, steps, 'contract', 'running');
if (address) {
pickedNote = 'Contract address entered by you.';
} else if (siteRes && siteRes.addresses && siteRes.addresses.length) {
const hints = Object.entries(siteRes.chainHints || {}).sort((a, b) => b[1] - a[1]).map(x => x[0]);
const order = [chain].concat(hints.filter(h => h !== chain));
let found = null;
for (const cand of siteRes.addresses.slice(0, 8)) {
for (const ch of order) {
const code = await getCode(ch, cand.address);
if (code && code.length > 2 && !code.startsWith('0xef0100')) { found = { cand, ch }; break; }
}
if (found) break;
}
if (found) {
address = found.cand.address; const switched = found.ch !== chain; chain = found.ch;
pickedNote = 'No contract was entered. We found ' + siteRes.addresses.length + ' address' + (siteRes.addresses.length === 1 ? '' : 'es') + ' on the website and used ' + address +
' because it appears in: ' + found.cand.seen.join(', ') + ', and it has contract code on ' + CHAINS[chain].name + '.' + (switched ? ' It has no code on the chain you picked, so we read it on ' + CHAINS[chain].name + ' instead.' : '');
} else pickedNote = 'No contract was entered, and none of the ' + siteRes.addresses.length + ' addresses on the website has contract code on the chains we checked.';
} else {
pickedNote = c.website ? 'No contract was entered, and we found no contract address on the website.' : 'No contract address.';
}
await db.q('UPDATE checks SET address = ?, chain = ?, picked_note = ? WHERE id = ?', [address, chain, pickedNote, id]);
await setStep(id, steps, 'contract', address ? 'done' : 'failed', pickedNote);
t.contract = Date.now();
let E = null, pack = null, facts = [];
if (address) {
// 3. chain (reuse a scan of the same contract from the last 30 minutes: free check, then deep report)
await setStep(id, steps, 'chain', 'running', 'Reading roles, upgrades, events, token flows and approvals.');
const prev = await db.one("SELECT evidence_json, pack_md, facts_json, finished FROM checks WHERE chain = ? AND address = ? AND evidence_json IS NOT NULL AND finished > ? AND id <> ? ORDER BY finished DESC LIMIT 1",
[chain, address, Date.now() - 30 * 60000, id]);
if (prev) { E = JSON.parse(prev.evidence_json); pack = prev.pack_md; facts = JSON.parse(prev.facts_json || '[]'); await setStep(id, steps, 'chain', 'done', 'Reused the chain read from ' + Math.round((Date.now() - prev.finished) / 60000) + ' min ago (block ' + E.read_at.block + ').'); }
else {
const dir = path.join(WORK(), id); fs.mkdirSync(dir, { recursive: true });
let abiFile = null;
if (siteRes && siteRes.abi && siteRes.abi.length) { abiFile = path.join(dir, 'site-abi.json'); fs.writeFileSync(abiFile, JSON.stringify(siteRes.abi)); }
await runScan(chain, address, dir, abiFile, j => setStep(id, steps, 'chain', 'running', 'Chain read: ' + j.step + (j.blocks ? ' (' + j.blocks.toLocaleString('en-US') + ' blocks)' : '')).catch(() => {}));
E = JSON.parse(fs.readFileSync(path.join(dir, 'evidence.json'), 'utf8'));
pack = fs.readFileSync(path.join(dir, 'pack.md'), 'utf8');
facts = JSON.parse(fs.readFileSync(path.join(dir, 'facts.json'), 'utf8'));
fs.rmSync(dir, { recursive: true, force: true });
await setStep(id, steps, 'chain', 'done', 'Read blocks ' + E.window.from + ' to ' + E.window.to + (E.window.complete_history ? ' (complete history)' : ' (partial window)') + '.');
}
facts = report.deepClean(facts);
} else await setStep(id, steps, 'chain', 'skipped', 'No contract to read.');
t.chain = Date.now();
await db.q('UPDATE checks SET evidence_json = ?, pack_md = ?, facts_json = ?, pack_chars = ?, site_json = ? WHERE id = ?',
[E ? JSON.stringify(E) : null, pack, JSON.stringify(facts), pack ? pack.length : 0,
siteRes ? JSON.stringify({ ok: siteRes.ok, title: siteRes.title, finalUrl: siteRes.finalUrl, status: siteRes.status, notes: siteRes.notes, addresses: siteRes.addresses, chainHints: siteRes.chainHints, explorerLinks: siteRes.explorerLinks, abiCount: (siteRes.abi || []).length, textChars: (siteRes.text || '').length }) : null, id]);
// 4 + 5. scoring and fact check
if (!E && !(siteRes && siteRes.ok)) throw new Error(pickedNote || 'Nothing to check.');
await setStep(id, steps, 'scoring', 'running', c.kind === 'deep' ? 'Writing the deep report.' : 'Writing the scorecard.');
const key = String(process.env.OPENROUTER_API_KEY || '').trim();
let out;
if (!E) {
out = { ok: false, report: null, grade: null, factcheck: { passed: false, runs: [], note: 'There is no contract to score. A score needs a contract to read: add the address, or a website that shows it.' }, cost: 0, tin: 0, tout: 0, model: null };
} else if (!E.is_contract) {
out = { ok: false, report: null, grade: null, factcheck: { passed: false, runs: [], note: 'This address is a personal wallet, not a contract, so there is no code to score.' }, cost: 0, tin: 0, tout: 0, model: null };
} else if (!key) throw new Error('OPENROUTER_API_KEY is not set');
else {
out = await report.write({ kind: c.kind, pack, siteText: siteRes && siteRes.ok ? siteRes.text : '', facts, evidence: E, key });
}
await setStep(id, steps, 'scoring', out.report ? 'done' : (E && E.is_contract ? 'failed' : 'skipped'), out.report ? 'Scored with the published rubric.' : out.factcheck.note);
await setStep(id, steps, 'factcheck', out.factcheck.passed ? 'done' : (out.report === null && E && E.is_contract ? 'failed' : 'skipped'),
out.factcheck.passed ? 'Every address, transaction and number matched the evidence.' : out.factcheck.note);
t.done = Date.now();
const timings = { website_s: (t.website - t.start) / 1000, contract_s: (t.contract - t.website) / 1000, chain_s: (t.chain - t.contract) / 1000, report_s: (t.done - t.chain) / 1000, total_s: (t.done - t.start) / 1000 };
await db.q("UPDATE checks SET status = 'done', finished = ?, timings_json = ?, model = ?, cost_usd = ?, tokens_in = ?, tokens_out = ?, report_json = ?, factcheck_json = ? WHERE id = ?",
[Date.now(), JSON.stringify(timings), out.model, out.cost, out.tin, out.tout, out.report ? JSON.stringify({ report: out.report, grade: out.grade }) : null, JSON.stringify(out.factcheck), id]);
} catch (e) {
console.error('check', id, e.message);
await db.q("UPDATE checks SET status = 'failed', finished = ?, error = ? WHERE id = ?", [Date.now(), String(e.message).slice(0, 800), id]);
}
}
async function resume() {
const rows = await db.q("SELECT id FROM checks WHERE status IN ('queued','running') ORDER BY created");
for (const r of rows) { await db.q("UPDATE checks SET status = 'queued' WHERE id = ?", [r.id]); enqueue(r.id); }
}
const newId = () => crypto.randomBytes(9).toString('base64').replace(/[+/=]/g, '').slice(0, 12).padEnd(12, 'x');
module.exports = { enqueue, resume, newId, qpos, CHAINS, STEPS, STEP_NAMES, running: () => running, queued: () => queue.length };