Stranger pass of 21 Oct: x402 verify-payments reads all wallet transfers in windows under the endpoint range limit (was UNMEASURED on the live testnet; now VALID), device-operation reputation is byte-identical in JS --canonical and Python, module README figures as measured, .gitignore for the keys the examples write, temporary directories removed by the probes
This commit is contained in:
1 parent
82c5b261ac
commit
fcece14a12
18 files changed
+266
-45
No files matched your search
+14
-2
@@ -35,6 +35,12 @@ Node.js 24 and `ethers` (for EIP-712 and secp256k1: `npm install` here). Payment
|
||||
`verifica-plati.mjs` then proves from the outside that a wallet's on-chain payments were allowed by the agent's policy: the ledger
|
||||
verifies, each payment names an allowed entry, its transaction emits `AuthorizationUsed(wallet, sha256(entry hash))` and the
|
||||
`Transfer` of that amount, and with `--all-transfers` every transfer out of the wallet since a block is one of those payments.
|
||||
The blocks from `fromBlock` to the head read once with `eth_blockNumber` are read in windows of at most `--window` blocks (5,000 by
|
||||
default; public endpoints refuse a long range, and on 2026-10-21 the testnet's refused 10,000 with `Requested range exceeds maximum
|
||||
RPC range limit`), four at a time. A window counts only when the endpoint answers with a list; an error, an answer that is not a list
|
||||
or a failed request leaves the window unread, and then the check is `UNMEASURED` with the count of unread windows, never "no
|
||||
transfers" (a transfer out of the wallet that is not a payment, found in a window that was read, is `INVALID` all the same). Above
|
||||
`--max-requests` windows (2,000 by default) nothing is asked and the check is `UNMEASURED`, saying how many windows it would need.
|
||||
|
||||
## Use
|
||||
|
||||
@@ -90,8 +96,8 @@ Measured on 2026-09-29 (Node.js 24.14.1, ethers 6.16.0):
|
||||
|---|---|
|
||||
| `node proba-wallet.mjs` | 25/25 without a network, real EIP-712 signatures and ML-DSA-65 keys: five paid purchases through a local facilitator, the sixth refused by the policy; attacks by the holder of the agent key (a forged "allowed" entry over the limit, an entry for another amount, the same entry twice, a branch with its equivocation proof, a new ledger under a changed policy, a backdated entry, two branches sent at the same time), the owner's revocation, human approval, a payment for another requirement and a replayed payment at the seller |
|
||||
| `node proba-cosign.mjs` | 16/16 without a network (the contract's ERC-1271 check emulated in the local facilitator): three purchases from a 2-of-2 wallet with both halves in order, the fourth refused by the policy; the agent alone, and the policy signer alone, cannot pay; a compromised wallet service that changes the recipient, the payer, the amount, the nonce, the validity, the digest, or signs with another key: the agent refuses to co-sign; the co-signing service over HTTP |
|
||||
| `node proba-verifica-plati.mjs` | 14/14 without a network, on the chain responses recorded for both testnet runs below, including the contract's code (one byte changed, another signer named, or no code at the wallet: `INVALID`) |
|
||||
| `node control-negativ-wallet.mjs` | 30/30: each guard of the wallet, the client (including the agent's co-signing checks), the seller and the verifier (including the contract code) removed in a copy, and the named check must fail |
|
||||
| `node proba-verifica-plati.mjs` | 24/24 on 2026-10-21 without a network, on the chain responses recorded for the testnet runs below (the latest EOA wallet run and the 2-of-2 run; until that day the pattern of the EOA file also matched the 2-of-2 file, so rows 1-10 judged the 2-of-2 run and no row judged an EOA run), including the contract's code (one byte changed, another signer named, or no code at the wallet: `INVALID`); and `--all-transfers` on an endpoint that refuses long ranges: 3,178,224 blocks read in 636 windows of 5,000 (`VALID`), the transfers found in different windows, a foreign transfer in the last window (`INVALID`), one request over the whole range, a window answering an error, a non-list or HTTP 429, a head below `fromBlock`, a range above the request cap (each `UNMEASURED`, never `VALID`), and a foreign transfer found while another window is unread (`INVALID`) |
|
||||
| `node control-negativ-wallet.mjs` | 36/36 on 2026-10-21: each guard of the wallet, the client (including the agent's co-signing checks), the seller and the verifier (including the contract code, and since 2026-10-21 the windows of `--all-transfers`: one request instead of windows, an unread window or a non-list taken for an empty one, an unread window hiding a foreign transfer, the request cap, a head below `fromBlock`) removed in a copy, and the named check must fail |
|
||||
| `AERE_TESTNET_KEY_FILE=<funded testnet key> node proba-x402-testnet.mjs` | 9/9 on the public testnet 28001 through its x402 facilitator: a fresh wallet funded with 0.05 tUSD, three purchases of 0.01 paid and settled on chain, the fourth refused by the policy, a replayed payment refused, the balances and the used authorization nonces read on chain, and the evidence file verified `VALID` (a changed amount, or a payment removed from the file: `INVALID`) |
|
||||
| `AERE_TESTNET_KEY_FILE=<funded testnet key> node proba-cosign-testnet.mjs` | 13/13 on the public testnet 28001: an `AereAgentWallet2of2` deployed from `AereAgentWallet2of2.json` with two fresh keys, its code on chain exactly the compiled code; `isValidSignature` on chain yes only for agent then policy signer, no for seven other forms; three purchases of 0.01 from it through the testnet facilitator, the fourth refused by the policy; the agent alone and the policy signer alone refused by the facilitator, and by the token itself asked on chain without the facilitator; balances and nonces on chain; the evidence verified `VALID` with the contract code (another policy signer named: `INVALID`) |
|
||||
| `node recompileaza-contract.mjs --solc <solc 0.8.23>` | `IDENTICAL`: 1193 bytes of creation code and 934 of runtime code, with the native solc 0.8.23+commit.f704f362 |
|
||||
@@ -106,5 +112,11 @@ node verifica-plati.mjs dovezi-28001/plati-agent-2026-09-29-20-23-16.json --rpc
|
||||
node verifica-plati.mjs dovezi-28001/plati-agent-2of2-2026-09-29-21-29-48.json --rpc https://testnet-rpc.aere.network --all-transfers
|
||||
```
|
||||
|
||||
Measured on 2026-10-21 against the testnet endpoint: both `VALID` (exit 0), every transfer out of each wallet since its `fromBlock`
|
||||
read in 636 and 635 windows of 5,000 blocks (about 3.2 million blocks each, 3 transfers each, all three payments of the ledger), in
|
||||
8 min 18 s and 6 min 55 s (the endpoint took 3 to 10 seconds per window of old blocks), and again from a fresh clone of the
|
||||
public copy as staged that evening, `VALID` both, in 6 min 6 s and 5 min 34 s. Before that day both commands answered
|
||||
`UNMEASURED` (exit 2): they asked for the whole range in one request, and the endpoint refused it.
|
||||
|
||||
tUSD is the testnet's EIP-3009 token, minted by a faucet and worth nothing. Nothing here has been run on the Aere Network mainnet.
|
||||
Code comments and test names are in Romanian; messages, data and the documentation are in English. No third party has reviewed it.
|
||||
@@ -49,6 +49,16 @@ const PLANTARI = [
|
||||
['verificatorul nu mai cere suma din Transfer', 'verifica-plati.mjs', '&& BigInt(l.data) === BigInt(a.amount)));', '));', '7. CONTROL', V],
|
||||
['verificatorul nu mai cere ca orice Transfer sa fie in registru', 'verifica-plati.mjs', 'straine.length === 0,', 'true,', '8. CONTROL', V],
|
||||
['verificatorul nu mai cere lantul dosarului', 'verifica-plati.mjs', 'lantul === chain,', 'true,', '9. CONTROL', V],
|
||||
// --all-transfers pe o usa care refuza intervalele mari (2026-10-21, trecerea straina): paginarea si clasificarea fiecarei ferestre
|
||||
['verificatorul nu mai pagineaza (o singura cerere de la fromBlock la cap)', 'verifica-plati.mjs', 'for (let a = from; a <= to; a += window) ferestre.push([a, Math.min(a + window - 1, to)]);',
|
||||
"if (process.env.AERE_PLANTA_NICIODATA === 'da') for (let a = from; a <= to; a += window) ferestre.push([a, Math.min(a + window - 1, to)]); else ferestre.push([from, to]);", '15. usa cu limita', V],
|
||||
['o fereastra cu eroare se numara drept goala', 'verifica-plati.mjs', 'if (j && Array.isArray(j.result)) { peFereastra[k] = j.result; return; }',
|
||||
"if ((j && Array.isArray(j.result)) || process.env.AERE_PLANTA_NICIODATA !== 'da') { peFereastra[k] = j && Array.isArray(j.result) ? j.result : []; return; }", '18. CONTROL', V],
|
||||
['un rezultat care nu e lista se numara drept gol', 'verifica-plati.mjs', 'if (j && Array.isArray(j.result)) { peFereastra[k] = j.result; return; }',
|
||||
'if (j && !j.error && !j.transport) { peFereastra[k] = Array.isArray(j.result) ? j.result : []; return; }', '19. CONTROL', V],
|
||||
['o fereastra necitita ascunde un Transfer strain gasit', 'verifica-plati.mjs', 'if (straine.length || !r.unreadable) {', "if ((straine.length && process.env.AERE_PLANTA_NICIODATA === 'da') || !r.unreadable) {", '21. CONTROL', V],
|
||||
['plafonul de cereri nu mai e respectat', 'verifica-plati.mjs', 'if (ferestre.length > maxRequests) return', "if (ferestre.length > maxRequests && process.env.AERE_PLANTA_NICIODATA === 'da') return", '22. CONTROL', V],
|
||||
['un cap sub fromBlock e luat drept interval gol', 'verifica-plati.mjs', '|| to < from) nu(', "|| (to < from && process.env.AERE_PLANTA_NICIODATA === 'da')) nu(", '23. CONTROL', V],
|
||||
// portofelul-contract 2-din-2 in dosar: codul de pe lant
|
||||
['verificatorul nu mai judeca portofelul-contract', 'verifica-plati.mjs', ' if (d.walletContract) {', " if (d.walletContract && process.env.AERE_PLANTA_NICIODATA === 'da') {", '14. CONTROL', V],
|
||||
['verificatorul cere doar lungimea codului, nu codul', 'verifica-plati.mjs', 'cod === asteptat, cod === asteptat ?', 'cod.length === asteptat.length, cod === asteptat ?', '12. CONTROL', V],
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// node inregistreaza-rpc.mjs <dovada.json> --rpc <url> --out <rpc-inregistrat.json>
|
||||
import fs from 'node:fs';
|
||||
import { incarcaEthers } from './wallet.mjs';
|
||||
import { jurnalePaginate } from './verifica-plati.mjs';
|
||||
|
||||
const a = process.argv.slice(2); const get = (f) => { const i = a.indexOf(f); return i >= 0 ? a[i + 1] : undefined; };
|
||||
const f = a[0]; const rpc = get('--rpc'); const out = get('--out');
|
||||
@@ -14,8 +15,16 @@ const apel = async (method, params) => { const r = await fetch(rpc, { method: 'P
|
||||
const chainId = await apel('eth_chainId', []);
|
||||
const receipts = {};
|
||||
for (const p of d.payments) receipts[p.transaction.toLowerCase()] = await apel('eth_getTransactionReceipt', [p.transaction]);
|
||||
const logs = await apel('eth_getLogs', [{ address: d.token, fromBlock: '0x' + Number(d.fromBlock).toString(16), toBlock: 'latest',
|
||||
topics: [ethers.id('Transfer(address,address,uint256)'), '0x' + '0'.repeat(24) + d.wallet.toLowerCase().slice(2)] }]);
|
||||
const code = d.walletContract ? await apel('eth_getCode', [d.wallet, 'latest']) : undefined;
|
||||
fs.writeFileSync(out, JSON.stringify({ v: 1, recordedAt: new Date().toISOString(), rpc, chainId, receipts, transfersOut: logs, ...(code ? { code } : {}) }, null, 1) + '\n');
|
||||
console.log(`recorded chain ${Number(chainId)}: ${Object.keys(receipts).length} receipts, ${logs.length} transfers out of the wallet${code ? `, the wallet code (${(code.length - 2) / 2} bytes)` : ''} -> ${out}`);
|
||||
// 2026-10-21: in ferestre, ca verificatorul (o usa publica refuza un interval lung); o fereastra necitita OPRESTE inregistrarea, fiindca o
|
||||
// inregistrare cu o fereastra lipsa ar fi o lista de transferuri mai scurta decat lantul, pe care proba ar lua-o drept adevar
|
||||
const capul = Number(await apel('eth_blockNumber', []));
|
||||
const apelBrut = async (method, params) => { const r = await fetch(rpc, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }) }); return r.json(); };
|
||||
const citite = await jurnalePaginate(apelBrut, { address: d.token, topics: [ethers.id('Transfer(address,address,uint256)'), '0x' + '0'.repeat(24) + d.wallet.toLowerCase().slice(2)] }, { from: Number(d.fromBlock), to: capul });
|
||||
// process.exitCode, nu process.exit(): dupa un fetch, iesirea imediata cade pe Windows in libuv (UV_HANDLE_CLOSING, lectia din 2026-09-11)
|
||||
if (citite.refused || citite.unreadable) { console.error(`not recorded: ${citite.refused || `${citite.unreadable} of ${citite.windows} windows unread (first: ${citite.first})`}`); process.exitCode = 2; }
|
||||
else {
|
||||
const logs = citite.logs;
|
||||
const code = d.walletContract ? await apel('eth_getCode', [d.wallet, 'latest']) : undefined;
|
||||
fs.writeFileSync(out, JSON.stringify({ v: 1, recordedAt: new Date().toISOString(), rpc, chainId, receipts, transfersOut: logs, ...(code ? { code } : {}) }, null, 1) + '\n');
|
||||
console.log(`recorded chain ${Number(chainId)}: ${Object.keys(receipts).length} receipts, ${logs.length} transfers out of the wallet${code ? `, the wallet code (${(code.length - 2) / 2} bytes)` : ''} -> ${out}`);
|
||||
}
|
||||
@@ -13,8 +13,12 @@ const AICI = path.dirname(fileURLToPath(import.meta.url));
|
||||
const D = path.join(AICI, 'dovezi-28001');
|
||||
// doua rulari pe 28001: portofelul EOA (plati-agent-<data>) si portofelul-contract 2-din-2 (plati-agent-2of2-<data>), fiecare cu inregistrarea ei
|
||||
const ultimul = (re) => fs.readdirSync(D).filter((n) => re.test(n)).sort().pop();
|
||||
const dovadaF = ultimul(/^plati-agent-\d.*\.json$/), inregF = ultimul(/^rpc-inregistrat-\d.*\.json$/);
|
||||
// 2026-10-21: tiparul EOA cere ANUL dupa prefix (\d{4}-); `\d.*` se potrivea si cu "2of2-", care sorteaza ultimul, deci randurile 1-10
|
||||
// judecau tot dosarul 2-din-2 si dosarul portofelului EOA nu era judecat de nicio proba, desi tabelul spunea "both testnet runs"
|
||||
const dovadaF = ultimul(/^plati-agent-\d{4}-.*\.json$/), inregF = ultimul(/^rpc-inregistrat-\d{4}-.*\.json$/);
|
||||
const dovada2F = ultimul(/^plati-agent-2of2-.*\.json$/), inreg2F = ultimul(/^rpc-inregistrat-2of2-.*\.json$/);
|
||||
if (dovadaF && dovadaF === dovada2F) { console.log('NEMASURAT: tiparul dosarului EOA a ales dosarul 2-din-2'); process.exit(2); }
|
||||
console.log(` dosare: EOA ${dovadaF} / ${inregF}; 2-din-2 ${dovada2F} / ${inreg2F}`);
|
||||
let ok = 0, rau = 0;
|
||||
const cer = (c, ce) => { console.log((c ? ' OK ' : ' RAU ') + ce); c ? ok++ : rau++; };
|
||||
if (!dovadaF || !inregF || !dovada2F || !inreg2F) { console.log(`NEMASURAT: lipseste un dosar-dovada sau o inregistrare RPC in ${D}`); process.exit(2); }
|
||||
@@ -25,22 +29,43 @@ const inreg2 = JSON.parse(fs.readFileSync(path.join(D, inreg2F), 'utf8'));
|
||||
const copie = (o) => JSON.parse(JSON.stringify(o));
|
||||
|
||||
// un RPC local peste inregistrare (sau peste o varianta schimbata a ei)
|
||||
async function rpcDin(rec) {
|
||||
// 2026-10-21 (trecerea straina, D1): macheta serveste si eth_blockNumber (implicit cel mai inalt bloc din inregistrare: chitante si
|
||||
// transferuri; `o.cap` il muta), filtreaza transferurile pe [fromBlock, toBlock] ca o usa reala, refuza ca usa testnetului un interval
|
||||
// mai lung de `o.limita` blocuri (-32005), si raspunde stricat pe ferestrele pe care `o.strica(a, b)` le numeste. Numara cererile eth_getLogs.
|
||||
const nrBloc = (x) => parseInt(x.blockNumber, 16);
|
||||
async function rpcDin(rec, o = {}) {
|
||||
const cap = o.cap ?? Math.max(...rec.transfersOut.map(nrBloc), ...Object.values(rec.receipts).filter(Boolean).map(nrBloc));
|
||||
const limita = o.limita ?? Infinity;
|
||||
const stat = { getLogs: 0, maxInterval: 0 };
|
||||
const trimite = (res, corp, cod = 200) => { res.writeHead(cod, { 'content-type': 'application/json' }); res.end(typeof corp === 'string' ? corp : JSON.stringify(corp)); };
|
||||
const srv = http.createServer((req, res) => { let s = ''; req.on('data', (x) => { s += x; }); req.on('end', () => {
|
||||
const q = JSON.parse(s); let result = null;
|
||||
if (q.method === 'eth_chainId') result = rec.chainId;
|
||||
else if (q.method === 'eth_blockNumber') result = '0x' + cap.toString(16);
|
||||
else if (q.method === 'eth_getTransactionReceipt') result = rec.receipts[String(q.params[0]).toLowerCase()] || null;
|
||||
else if (q.method === 'eth_getLogs') result = rec.transfersOut;
|
||||
else if (q.method === 'eth_getLogs') {
|
||||
stat.getLogs++;
|
||||
const f = q.params[0], a = parseInt(f.fromBlock, 16), b = f.toBlock === 'latest' ? cap : parseInt(f.toBlock, 16);
|
||||
stat.maxInterval = Math.max(stat.maxInterval, b - a + 1);
|
||||
if (b - a + 1 > limita) { trimite(res, { jsonrpc: '2.0', id: q.id, error: { code: -32005, message: 'Requested range exceeds maximum RPC range limit' } }); return; }
|
||||
const stricat = o.strica && o.strica(a, b);
|
||||
if (stricat) { trimite(res, stricat.corp(q.id), stricat.cod || 200); return; }
|
||||
result = rec.transfersOut.filter((l) => nrBloc(l) >= a && nrBloc(l) <= b);
|
||||
}
|
||||
// 2026-10-11 (D-FAZA2-04b, R2): macheta serveste numai ce e INREGISTRAT; o inregistrare fara `code` nu devine "fara cod",
|
||||
// ci o eroare JSON-RPC, pe care verificatorul trebuie sa o trateze ca necunoscut (inregistrarile EOA poarta explicit "0x")
|
||||
else if (q.method === 'eth_getCode') { if (rec.code === undefined) { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ jsonrpc: '2.0', id: q.id, error: { code: -32000, message: 'World state unavailable' } })); return; } result = rec.code; }
|
||||
res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ jsonrpc: '2.0', id: q.id, result }));
|
||||
}); });
|
||||
await new Promise((r) => srv.listen(0, '127.0.0.1', r));
|
||||
return { url: `http://127.0.0.1:${srv.address().port}`, close: () => srv.close() };
|
||||
return { url: `http://127.0.0.1:${srv.address().port}`, close: () => srv.close(), stat };
|
||||
}
|
||||
async function judeca(dov, rec, allTransfers = true) { const r = await rpcDin(rec); try { return await verificaPlati(dov, { rpc: r.url, allTransfers }); } finally { r.close(); } }
|
||||
// aceeasi judecata pe o usa cu forma data (o), cu fereastra si plafonul date verificatorului (v); intoarce si ce a numarat macheta
|
||||
async function judecaUsa(dov, rec, o = {}, v = {}) { const r = await rpcDin(rec, o); try { return { ...(await verificaPlati(dov, { rpc: r.url, allTransfers: true, ...v })), stat: r.stat }; } finally { r.close(); } }
|
||||
const pica = (v, re) => v.checks.some((c) => c.pass === false && re.test(c.name));
|
||||
const toate = /all transfers out of the wallet|every Transfer out of the wallet/;
|
||||
const verificarea = (v) => v.checks.find((c) => toate.test(c.name)) || { name: '(lipseste)', pass: undefined, detail: '' };
|
||||
|
||||
try {
|
||||
const v0 = await judeca(dovada, inreg);
|
||||
@@ -78,6 +103,58 @@ try {
|
||||
cer(pica(await judeca(d13, inreg2), e2), '13. CONTROL: dosarul numeste alt semnatar al agentului decat cel din codul de pe lant -> INVALID');
|
||||
const r14 = copie(inreg2); r14.code = '0x'; // 2026-10-11: controlul spune EXPLICIT "cont fara cod"; o inregistrare fara camp e tacere, nu absenta (R2)
|
||||
cer(pica(await judeca(dovada2, r14), e2), '14. CONTROL: la adresa portofelului nu e niciun cod (un cont cu o cheie), dar dosarul spune 2-din-2 -> INVALID');
|
||||
|
||||
// 2026-10-21 (trecerea straina, D1): --all-transfers pe o usa care refuza intervalele mari. Pe 28001 capul era 7.200.317, deci de la
|
||||
// fromBlock-ul dosarului EOA (4.022.094) sunt 3.178.224 de blocuri; usa testnetului accepta 5.001 si refuza 10.000.
|
||||
// Ferestrele si blocurile se DERIVA din dosarul si inregistrarea alese mai sus, nu se scriu fix.
|
||||
const from = Number(dovada.fromBlock), capViu = from + 3178223;
|
||||
const blocuri = inreg.transfersOut.map(nrBloc), capInreg = Math.max(...blocuri, ...Object.values(inreg.receipts).map(nrBloc));
|
||||
const W = 8, nrFerestre = Math.ceil((capInreg - from + 1) / W), ferestreCuTransfer = new Set(blocuri.map((b) => Math.floor((b - from) / W))).size;
|
||||
const transfer = (l, bloc, tx) => ({ ...l, blockNumber: '0x' + bloc.toString(16), transactionHash: tx });
|
||||
const strain = (bloc) => { const r = copie(inreg); r.transfersOut.push(transfer(r.transfersOut[0], bloc, '0x' + 'ee'.repeat(32))); return r; };
|
||||
const v15 = await judecaUsa(dovada, inreg, { cap: capViu, limita: 5000 });
|
||||
const c15 = verificarea(v15);
|
||||
cer(v15.verdict === 'VALID' && c15.pass === true && v15.stat.getLogs === 636 && v15.stat.maxInterval <= 5000 && new RegExp(`${blocuri.length} transfers, 636 windows`).test(c15.name),
|
||||
`15. usa cu limita de 5.000 de blocuri, 3.178.224 de blocuri de citit (ca 28001 pe 2026-10-21): VALID, ${v15.stat.getLogs} cereri, cel mai lung interval ${v15.stat.maxInterval} (${c15.name.slice(0, 110)})`);
|
||||
// ferestre de W blocuri pe [fromBlock, capul inregistrarii]: transferurile cad in mai multe ferestre DIFERITE
|
||||
const v16 = await judecaUsa(dovada, inreg, { limita: 10 }, { window: W });
|
||||
const c16 = verificarea(v16);
|
||||
cer(ferestreCuTransfer >= 2 && v16.verdict === 'VALID' && c16.pass === true && v16.stat.getLogs === nrFerestre
|
||||
&& new RegExp(`${blocuri.length} transfers, ${nrFerestre} windows of at most ${W} blocks\\)`).test(c16.name),
|
||||
`16. ferestre de ${W} blocuri pe o usa cu limita 10: ${blocuri.length} transferuri gasite in ${ferestreCuTransfer} ferestre diferite din ${nrFerestre}, VALID (${c16.name.slice(0, 110)})`);
|
||||
const v16b = await judecaUsa(dovada, strain(capInreg), { limita: 10 }, { window: W });
|
||||
cer(v16b.verdict === 'INVALID' && verificarea(v16b).pass === false, `16b. CONTROL: un Transfer strain in ULTIMA fereastra (blocul capului) -> ${v16b.verdict}`);
|
||||
// fara paginare: o singura cerere peste tot intervalul (fereastra mai mare decat intervalul), pe usa cu limita
|
||||
const v17 = await judecaUsa(dovada, inreg, { cap: capViu, limita: 5000 }, { window: 10000000 });
|
||||
const c17 = verificarea(v17);
|
||||
cer(v17.verdict === 'UNMEASURED' && c17.pass === null && /Requested range exceeds/.test(c17.detail) && !/\d+ transfers/.test(c17.name),
|
||||
`17. CONTROL: fara paginare (o singura cerere de la fromBlock la cap) pe usa cu limita -> ${v17.verdict}, cu refuzul usii, niciodata "0 transferuri"`);
|
||||
// o fereastra cu eroare nu se numara drept goala: Transferul strain sta exact in fereastra necitita (prima, care incepe la fromBlock)
|
||||
const strica1 = (forma) => ({ strica: (a) => a === from ? forma : null, limita: 10 });
|
||||
const eroare = { corp: (id) => ({ jsonrpc: '2.0', id, error: { code: -32000, message: 'internal error' } }) };
|
||||
const unaDin = new RegExp(`1 of ${nrFerestre} windows`);
|
||||
const v18 = await judecaUsa(dovada, strain(from + 1), strica1(eroare), { window: W });
|
||||
const c18 = verificarea(v18);
|
||||
cer(v18.verdict === 'UNMEASURED' && c18.pass === null && unaDin.test(c18.detail),
|
||||
`18. CONTROL: fereastra cu Transferul strain raspunde cu o eroare JSON-RPC -> ${v18.verdict} (${String(c18.detail).slice(0, 70)}), nu VALID`);
|
||||
const v19 = await judecaUsa(dovada, strain(from + 1), strica1({ corp: (id) => ({ jsonrpc: '2.0', id, result: null }) }), { window: W });
|
||||
cer(v19.verdict === 'UNMEASURED' && unaDin.test(verificarea(v19).detail) && /not a list/.test(verificarea(v19).detail),
|
||||
`19. CONTROL: aceeasi fereastra raspunde cu un rezultat care nu e lista (null) -> ${v19.verdict}, nu "goala"`);
|
||||
const v20 = await judecaUsa(dovada, strain(from + 1), strica1({ cod: 429, corp: () => 'Too Many Requests' }), { window: W });
|
||||
cer(v20.verdict === 'UNMEASURED' && unaDin.test(verificarea(v20).detail),
|
||||
`20. CONTROL: aceeasi fereastra raspunde HTTP 429 cu text, nu JSON -> ${v20.verdict}`);
|
||||
// un Transfer strain intr-o fereastra CITITA da INVALID chiar daca alta fereastra e necitita
|
||||
const v21 = await judecaUsa(dovada, strain(capInreg), strica1(eroare), { window: W });
|
||||
cer(v21.verdict === 'INVALID' && verificarea(v21).pass === false && /1 unreadable/.test(verificarea(v21).name),
|
||||
`21. CONTROL: Transfer strain in ultima fereastra, prima fereastra necitita -> ${v21.verdict} (INVALID bate NEMASURAT)`);
|
||||
// plafonul de cereri: 20 de milioane de blocuri la 5.000 cer 4.001 ferestre, peste plafonul implicit de 2.000 -> nu se cere nimic
|
||||
const v22 = await judecaUsa(dovada, inreg, { cap: from + 20000000, limita: 5000 });
|
||||
cer(v22.verdict === 'UNMEASURED' && v22.stat.getLogs === 0 && /4001 requests .* above the cap of 2000/.test(verificarea(v22).detail),
|
||||
`22. CONTROL: intervalul cere 4.001 ferestre, peste plafonul de 2.000 -> ${v22.verdict}, ${v22.stat.getLogs} cereri eth_getLogs`);
|
||||
// un cap SUB fromBlock (o usa ramasa in urma) nu e un interval gol
|
||||
const v23 = await judecaUsa(dovada, inreg, { cap: from - 1 });
|
||||
cer(v23.verdict === 'UNMEASURED' && v23.stat.getLogs === 0 && /is not at or above the evidence's fromBlock/.test(verificarea(v23).detail),
|
||||
`23. CONTROL: capul usii e sub fromBlock-ul dosarului -> ${v23.verdict}, nu "0 transferuri"`);
|
||||
} catch (e) { cer(false, `proba s-a oprit: ${String(e.message || e).slice(0, 160)}`); }
|
||||
console.log(`\nverifica-plati: ${ok}/${ok + rau} ${rau ? 'CU ESECURI' : 'cum trebuia'}`);
|
||||
process.exitCode = rau ? 1 : 0;
|
||||
@@ -7,23 +7,61 @@
|
||||
// 3. pe lant, tranzactia platii are status 1 si emite, din contractul activului, AuthorizationUsed(portofel, nonce) cu nonce =
|
||||
// sha256(hash-ul intrarii) si Transfer(portofel, destinatar, suma) - deci plata de pe lant e chiar cea din registru;
|
||||
// 4. cu --all-transfers: ORICE Transfer din portofel in intervalul de blocuri e una din platile de mai sus (nicio plata fara intrare);
|
||||
// intervalul [fromBlock, capul citit o data cu eth_blockNumber] se citeste in FERESTRE de cel mult --window blocuri (implicit 5000),
|
||||
// fiindca usile publice refuza un interval mare (2026-10-21, trecerea straina: un singur eth_getLogs de la 4.022.094 la varful lui
|
||||
// 28001 a primit `-32005 Requested range exceeds maximum RPC range limit`; usa testnetului accepta 5.001 de blocuri si refuza 10.000).
|
||||
// Un raspuns e MASURAT numai cand `result` e o lista; orice altceva (eroare JSON-RPC, transport, rezultat care nu e lista) e o fereastra
|
||||
// NECITITA, numarata separat, si verificarea iese NEMASURAT, niciodata "0 transferuri" (lectia din 2026-10-15 a lui CLAUDE.md). Un
|
||||
// Transfer strain gasit intr-o fereastra citita da INVALID oricum. Peste --max-requests ferestre (implicit 2000) nu se cere nimic:
|
||||
// verificarea iese NEMASURAT si spune cate ar fi trebuit;
|
||||
// 5. cand dosarul numeste un portofel-contract 2-din-2 (walletContract: {agentSigner, policySigner}): codul de pe lant al portofelului e
|
||||
// EXACT codul compilat din AereAgentWallet2of2.sol (artefactul de langa verificator) cu cei doi semnatari in locul imutabilelor, deci
|
||||
// din portofel nu a putut plati nici agentul singur, nici serviciul de politica singur.
|
||||
// Ce nu dovedeste: ca serviciul cumparat a fost livrat; ca portofelul nu a semnat si autorizari nedecontate (acelea nu misca bani).
|
||||
// node verifica-plati.mjs <dovada.json> --rpc <url> [--all-transfers] iesire 0 VALID, 1 INVALID, 2 NEMASURAT
|
||||
// node verifica-plati.mjs <dovada.json> --rpc <url> [--all-transfers [--window <blocuri>] [--max-requests <n>]]
|
||||
// iesire 0 VALID, 1 INVALID, 2 NEMASURAT
|
||||
import fs from 'node:fs';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { verifyLedger } from '../agent-ledger.mjs';
|
||||
import { incarcaEthers, nonceForEntry, assetId } from './wallet.mjs';
|
||||
import { incarcaArtefact, codulAsteptat, amprentaSursei } from './contract-2of2.mjs';
|
||||
|
||||
export async function verificaPlati(d, { rpc, allTransfers = false, fetchImpl = fetch } = {}) {
|
||||
// fereastra implicita: limita masurata a lui rpc2 (5.000, CLAUDE.md 2026-10-15) si sub cea a usii testnetului (refuza 10.000);
|
||||
// plafonul: 2000 de ferestre = 10 milioane de blocuri la fereastra implicita (28001 avea 7,2 milioane pe 2026-10-21)
|
||||
export const FEREASTRA_IMPLICITA = 5000, CERERI_MAXIME = 2000;
|
||||
// cate ferestre se cer deodata: putine, ca usa publica sa nu le refuze pentru ritm (un refuz pentru ritm ar iesi NEMASURAT, nu fals)
|
||||
const PARALEL = 4;
|
||||
const hex = (n) => '0x' + n.toString(16);
|
||||
|
||||
// citeste un filtru de jurnale pe [from, to] in ferestre de cel mult `window` blocuri. apelBrut(method, params) intoarce raspunsul JSON
|
||||
// intreg (sau arunca la transport); o fereastra e masurata NUMAI daca `result` e o lista. Intoarce { logs, windows, unreadable, first }
|
||||
// sau { refused } cand intervalul cere mai mult de `maxRequests` ferestre (atunci nu se cere nimic).
|
||||
export async function jurnalePaginate(apelBrut, filtru, { from, to, window = FEREASTRA_IMPLICITA, maxRequests = CERERI_MAXIME }) {
|
||||
const ferestre = [];
|
||||
for (let a = from; a <= to; a += window) ferestre.push([a, Math.min(a + window - 1, to)]);
|
||||
if (ferestre.length > maxRequests) return { refused: `blocks ${from}..${to} need ${ferestre.length} requests of ${window} blocks, above the cap of ${maxRequests} (--max-requests); nothing was asked` };
|
||||
// fiecare fereastra isi tine rezultatul pe pozitia ei, deci jurnalele ies in ordinea lantului oricum ar sosi raspunsurile
|
||||
const peFereastra = new Array(ferestre.length).fill(null), erori = []; let i = 0;
|
||||
const citeste = async (k) => {
|
||||
const [a, b] = ferestre[k];
|
||||
let j; try { j = await apelBrut('eth_getLogs', [{ ...filtru, fromBlock: hex(a), toBlock: hex(b) }]); } catch (e) { j = { transport: String(e.message || e) }; }
|
||||
if (j && Array.isArray(j.result)) { peFereastra[k] = j.result; return; }
|
||||
erori.push([k, `${a}..${b}: ${j && j.error ? String(j.error.message).slice(0, 80) : j && j.transport ? j.transport.slice(0, 80) : 'the result is not a list'}`]);
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(PARALEL, ferestre.length) }, async () => { while (i < ferestre.length) await citeste(i++); }));
|
||||
erori.sort((x, y) => x[0] - y[0]);
|
||||
return { logs: peFereastra.filter(Boolean).flat(), windows: ferestre.length, unreadable: erori.length, first: erori.length ? erori[0][1] : null };
|
||||
}
|
||||
|
||||
export async function verificaPlati(d, { rpc, allTransfers = false, fetchImpl = fetch, window = FEREASTRA_IMPLICITA, maxRequests = CERERI_MAXIME } = {}) {
|
||||
const ethers = incarcaEthers();
|
||||
const rez = []; const ok = (name, pass, detail = '') => { rez.push({ name, pass, detail }); return pass; };
|
||||
const apel = async (method, params) => {
|
||||
const apelBrut = async (method, params) => {
|
||||
const r = await fetchImpl(rpc, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }) });
|
||||
const j = await r.json(); if (j.error) throw new Error(`${method}: ${String(j.error.message).slice(0, 80)}`); return j.result;
|
||||
return r.json();
|
||||
};
|
||||
const apel = async (method, params) => {
|
||||
const j = await apelBrut(method, params); if (j.error) throw new Error(`${method}: ${String(j.error.message).slice(0, 80)}`); return j.result;
|
||||
};
|
||||
const chain = Number(String(d.network).split(':')[1]);
|
||||
let lantul;
|
||||
@@ -51,11 +89,24 @@ export async function verificaPlati(d, { rpc, allTransfers = false, fetchImpl =
|
||||
&& l.topics[2].toLowerCase() === topicAdresa(a.to) && BigInt(l.data) === BigInt(a.amount)));
|
||||
}
|
||||
if (allTransfers) {
|
||||
const nu = (detail) => rez.push({ name: 'all transfers out of the wallet', pass: null, detail });
|
||||
try {
|
||||
const logs = await apel('eth_getLogs', [{ address: token, fromBlock: '0x' + Number(d.fromBlock || 0).toString(16), toBlock: 'latest', topics: [T_TRANSFER, topicAdresa(wallet)] }]);
|
||||
const straine = logs.filter((l) => !txPlati.has(l.transactionHash.toLowerCase()));
|
||||
ok(`every Transfer out of the wallet since block ${d.fromBlock || 0} is a payment in the ledger (${logs.length} transfers)`, straine.length === 0, straine.map((l) => l.transactionHash.slice(0, 12)).join(', '));
|
||||
} catch (x) { rez.push({ name: 'all transfers out of the wallet', pass: null, detail: x.message }); }
|
||||
const from = Number(d.fromBlock || 0), to = Number(await apel('eth_blockNumber', []));
|
||||
if (!Number.isSafeInteger(from) || from < 0) nu(`the evidence's fromBlock is not a block number (${d.fromBlock})`);
|
||||
else if (!Number.isSafeInteger(to) || to < from) nu(`the RPC's head ${to} is not at or above the evidence's fromBlock ${from}`);
|
||||
else {
|
||||
const r = await jurnalePaginate(apelBrut, { address: token, topics: [T_TRANSFER, topicAdresa(wallet)] }, { from, to, window, maxRequests });
|
||||
if (r.refused) nu(r.refused);
|
||||
else {
|
||||
const straine = r.logs.filter((l) => !txPlati.has(String(l.transactionHash).toLowerCase()));
|
||||
// un Transfer strain gasit e INVALID oricum; altfel, o singura fereastra necitita face verificarea NEMASURAT, nu "goala"
|
||||
if (straine.length || !r.unreadable) {
|
||||
ok(`every Transfer out of the wallet from block ${from} to ${to} is a payment in the ledger (${r.logs.length} transfers, ${r.windows} windows of at most ${window} blocks${r.unreadable ? `, ${r.unreadable} unreadable` : ''})`,
|
||||
straine.length === 0, straine.map((l) => String(l.transactionHash).slice(0, 12)).join(', '));
|
||||
} else nu(`${r.unreadable} of ${r.windows} windows of at most ${window} blocks could not be read and are not counted as empty (first: ${r.first})`);
|
||||
}
|
||||
}
|
||||
} catch (x) { nu(x.message); }
|
||||
}
|
||||
if (d.walletContract) {
|
||||
const wc = d.walletContract; let art = null, asteptat = null;
|
||||
@@ -74,10 +125,14 @@ export async function verificaPlati(d, { rpc, allTransfers = false, fetchImpl =
|
||||
|
||||
if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
|
||||
const a = process.argv.slice(2); const get = (f) => { const i = a.indexOf(f); return i >= 0 ? a[i + 1] : undefined; };
|
||||
const f = a.find((x) => !x.startsWith('--') && x !== get('--rpc'));
|
||||
if (!f || !get('--rpc')) { console.error('usage: node verifica-plati.mjs <evidence.json> --rpc <url> [--all-transfers]'); process.exitCode = 2; }
|
||||
else {
|
||||
const r = await verificaPlati(JSON.parse(fs.readFileSync(f, 'utf8')), { rpc: get('--rpc'), allTransfers: a.includes('--all-transfers') });
|
||||
const valori = ['--rpc', '--window', '--max-requests'].map(get);
|
||||
const f = a.find((x) => !x.startsWith('--') && !valori.includes(x));
|
||||
const intreg = (x, implicit) => x === undefined ? implicit : /^[1-9][0-9]*$/.test(x) ? Number(x) : NaN;
|
||||
const window = intreg(get('--window'), FEREASTRA_IMPLICITA), maxRequests = intreg(get('--max-requests'), CERERI_MAXIME);
|
||||
if (!f || !get('--rpc') || !Number.isSafeInteger(window) || !Number.isSafeInteger(maxRequests)) {
|
||||
console.error('usage: node verifica-plati.mjs <evidence.json> --rpc <url> [--all-transfers [--window <blocks, default 5000>] [--max-requests <n, default 2000>]]'); process.exitCode = 2;
|
||||
} else {
|
||||
const r = await verificaPlati(JSON.parse(fs.readFileSync(f, 'utf8')), { rpc: get('--rpc'), allTransfers: a.includes('--all-transfers'), window, maxRequests });
|
||||
for (const c of r.checks) console.log(` ${c.pass === true ? 'OK ' : c.pass === false ? 'FAIL' : '-- '} ${c.name}${c.detail ? ' (' + c.detail + ')' : ''}`);
|
||||
console.log(r.verdict);
|
||||
process.exitCode = r.verdict === 'VALID' ? 0 : r.verdict === 'INVALID' ? 1 : 2;
|
||||
|
||||
Reference in new issue
Block a user