Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -601,7 +601,7 @@ Everything below runs offline, with no deployed contracts, except three fork sui
| Suite | Count | Command |
|---|---|---|
| Contracts: unit, fuzz, E2E, upgrade, deploy-script, handover and 22 invariants | 796 | `forge test` |
| Oracle | 1500 | `cd oracle && node --test` |
| Oracle | 1514 | `cd oracle && node --test` |
| SDK | 381 | `cd packages/sdk && npx vitest run` |

Counts are individual tests, so each of the 22 invariants counts once. The contracts were counted on 10 November 2026 and have not changed since; the SDK on 13 November and the oracle on 14 November. Without a fork URL, 784 of the contract tests run and 12 skip. Run after `npm run build`, 372 of the SDK's 381 pass and 9 skip: the 8 integration tests, which need a live deployment, and one check that runs only in CI. Without a build, the 9 built-package tests skip too. Vitest strips types without checking them, so `npm run typecheck` in `packages/sdk` checks the tests against the SDK's types as well as the sources. [`scripts/mutation`](scripts/mutation/README.md) holds the harnesses that measure whether these tests would catch a deliberate break in the contracts or deploy scripts.
Expand Down
2 changes: 1 addition & 1 deletion docs/whitepaper.md
Original file line number Diff line number Diff line change
Expand Up @@ -635,7 +635,7 @@ apply to a fresh deployment, not to the testnet.

**Test coverage**, as of 14 November 2026: 796 contract tests across 36 Foundry test files
including fuzz and invariant tests (the two slash drill suites fork Arc testnet themselves, and
the twelve in `SplitAuthorityFork` skip without `--fork-url`), 1500 oracle tests and 381 in the SDK (9 skip
the twelve in `SplitAuthorityFork` skip without `--fork-url`), 1514 oracle tests and 381 in the SDK (9 skip
outside CI and without a live deployment; every test that runs passes). CI runs Foundry, the oracle and
SDK suites, and Slither static analysis on every push, plus a documentation check that
fails when the site states something the contracts do not.
Expand Down
17 changes: 11 additions & 6 deletions oracle/chain.js
Original file line number Diff line number Diff line change
Expand Up @@ -452,9 +452,13 @@ async function getReputationData(didHash) {
};
}

async function getAgentScore(address) {
/**
* A counterparty's standing, at `blockTag` when given (the scoring snapshot's block) and at the latest
* block otherwise.
*/
async function getAgentScore(address, blockTag) {
try {
return await readWithBackoff('payer standing', () => readStanding(address));
return await readWithBackoff('payer standing', () => readStanding(address, blockTag));
} catch (err) {
// A failure of the node says nothing about the counterparty. Read as "no standing" it lowers the
// score this oracle proposes, and the checker, whose own reads succeeded, then records a divergence
Expand All @@ -466,7 +470,8 @@ async function getAgentScore(address) {
}
}

async function readStanding(address) {
async function readStanding(address, blockTag) {
const at = blockTag === undefined ? [] : [{ blockTag }];
// Was three serial round trips per counterparty. The first is now arithmetic when
// the derivation has been verified, so it is two, and those two are genuinely
// dependent. At ~124 ms a call on Arc that is a third off every payer lookup, and
Expand All @@ -475,7 +480,7 @@ async function readStanding(address) {
? didHashOf(address, localDidHash.chainId)
: await identityContract.computeDidHash(address);

const id = await identityContract.getIdentity(didHash);
const id = await identityContract.getIdentity(didHash, ...at);
if (Number(id.registeredAt) === 0) return 0;
if (Number(id.status) === STATUS_SLASHED) return 0;

Expand All @@ -492,8 +497,8 @@ async function readStanding(address) {
// propagate it the same epoch, and a handover restarts maturity, so bought standing
// is not instantly spendable through counterparties either.
const [rep, matured] = await Promise.all([
reputationContract.getReputation(didHash),
reputationContract.getTotalScore(didHash),
reputationContract.getReputation(didHash, ...at),
reputationContract.getTotalScore(didHash, ...at),
]);
return Math.min(Number(rep.externalScore), Number(matured));
}
Expand Down
27 changes: 27 additions & 0 deletions oracle/chain.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -867,6 +867,33 @@ test('getAgentScore: capped by the matured total, so linked standing is not inst
assert.equal(await chain.getAgentScore('0xPayer'), 4);
});

test('getAgentScore: every read is made at the block it is given, and at the latest without one', async () => {
// The epoch reads standings at the day's snapshot block, where they cannot change, and keeps them for
// the day. A read that went to the latest block instead would be cached as the snapshot's.
const asked = [];
const note = (name, value) => async (...args) => {
const last = args[args.length - 1];
asked.push([name, last && typeof last === 'object' ? last.blockTag : 'latest']);
return value;
};
chain.init(CFG, {
provider: makeFakeProvider(1),
identityContract: {
computeDidHash: async () => '0xdeadbeef',
getIdentity: note('getIdentity', { registeredAt: 1n, status: 0 }),
},
reputationContract: {
getReputation: note('getReputation', { externalScore: 20n }),
getTotalScore: note('getTotalScore', 60n),
},
});
assert.equal(await chain.getAgentScore('0xPayer', 4242), 20);
assert.deepEqual(asked.sort(), [['getIdentity', 4242], ['getReputation', 4242], ['getTotalScore', 4242]]);
asked.length = 0;
await chain.getAgentScore('0xPayer');
assert.deepEqual(asked.sort(), [['getIdentity', 'latest'], ['getReputation', 'latest'], ['getTotalScore', 'latest']]);
});

test('getAgentScore: an unregistered counterparty has no standing', async () => {
chain.init(CFG, { provider: makeFakeProvider(1), ...makeStandingContracts({ registeredAt: 0, externalScore: 25, total: 90 }) });
assert.equal(await chain.getAgentScore('0xStranger'), 0);
Expand Down
39 changes: 35 additions & 4 deletions oracle/http-helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@ const net = require('net');

const MAX_BODY_SIZE = 1024 * 1024; // 1 MB

// POST /attest is public, so its bodies are held to what a real one needs. The largest is a payer
// outcome: its signature (payer-outcome.js MAX_SIGNATURE_BYTES) in hex plus a few hundred bytes of
// fields. A megabyte let each request a client left unfinished hold a megabyte of this process.
const ATTEST_MAX_BODY_SIZE = 32 * 1024;

// How long a request has to deliver its body. Node's requestTimeout is five minutes, and a client that
// sent all but the last byte and stopped kept everything it had sent in memory for that long: at the
// write limit of 60 requests a minute, about 300 MB from one address.
const BODY_DEADLINE_MS = 10_000;

// Past this many bytes the connection is cut. Up to it, the rest of an oversize body is read and
// thrown away, so a client that is still writing can finish and read the 413. Destroying the
// request at the limit left it with a reset and no answer.
Expand All @@ -24,21 +34,37 @@ function bodyTooLarge() {
return Object.assign(new Error('Request body too large'), { code: 'body_too_large' });
}

// What a route answers when readBody rejects: 413 for an oversize body, 400 for anything else.
function bodyTooSlow() {
return Object.assign(new Error('Request body too slow'), { code: 'body_timeout' });
}

// What a route answers when readBody rejects: 413 for an oversize body, 408 for one that did not
// arrive in time, 400 for anything else.
function bodyErrorStatus(err) {
return err && err.code === 'body_too_large' ? 413 : 400;
if (err && err.code === 'body_too_large') return 413;
if (err && err.code === 'body_timeout') return 408;
return 400;
}

// req only needs to be an EventEmitter emitting 'data' | 'end' | 'error' and
// exposing destroy() — a real http.IncomingMessage satisfies this, and so
// does a plain fake in tests. A declared content-length is read from
// req.headers when it has them.
async function readBody(req, maxBodySize = MAX_BODY_SIZE) {
async function readBody(req, maxBodySize = MAX_BODY_SIZE, deadlineMs = BODY_DEADLINE_MS) {
return new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
let refused = false;
const refuse = () => { refused = true; chunks.length = 0; reject(bodyTooLarge()); };
// A body still arriving at the deadline is dropped, and the connection with it, so what was sent
// is let go. The timer does not hold the process open on its own.
const deadline = setTimeout(() => {
refused = true;
chunks.length = 0;
reject(bodyTooSlow());
req.destroy();
}, deadlineMs);
deadline.unref?.();
// A declared length over the limit is refused before any of the body is read.
if (Number(req.headers && req.headers['content-length']) > maxBodySize) refuse();
req.on('data', c => {
Expand All @@ -51,10 +77,14 @@ async function readBody(req, maxBodySize = MAX_BODY_SIZE) {
chunks.push(c);
});
req.on('end', () => {
clearTimeout(deadline);
try { resolve(JSON.parse(Buffer.concat(chunks).toString() || '{}')); }
catch { reject(new Error('Invalid JSON')); }
});
req.on('error', reject);
req.on('error', (err) => {
clearTimeout(deadline);
reject(err);
});
});
}

Expand Down Expand Up @@ -425,6 +455,7 @@ module.exports = {
SCOPES,
MIN_TOKEN_LENGTH,
MAX_BODY_SIZE,
ATTEST_MAX_BODY_SIZE,
RATE_WINDOW_MS,
RATE_MAX,
json,
Expand Down
31 changes: 31 additions & 0 deletions oracle/http-helpers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,37 @@ test('bodyErrorStatus: 413 for an oversized body, 400 for anything else', async
assert.equal(bodyErrorStatus(undefined), 400);
});

test('readBody: a body still arriving at the deadline is dropped with its connection, and answered 408', async () => {
// Before the deadline a client could send all but the last byte and stop, and everything it had sent
// stayed in memory until Node's five-minute requestTimeout.
const req = makeFakeRequest();
let destroyed = false;
req.on('destroyed', () => { destroyed = true; });
req.headers = { 'content-length': '1000' };
const promise = readBody(req, 1000, 50);
req.emit('data', Buffer.from('x'.repeat(999)));

const outcome = await Promise.race([
promise.then(() => 'resolved', (err) => err),
new Promise((r) => setTimeout(() => r('still waiting'), 1_000)),
]);
assert.equal(outcome.code, 'body_timeout', `readBody ended as: ${outcome}`);
assert.equal(bodyErrorStatus(outcome), 408);
assert.equal(destroyed, true, 'the connection is cut, which lets go of what it sent');
});

test('readBody: a body that arrives in time is not cut by the deadline', async () => {
const req = makeFakeRequest();
let destroyed = false;
req.on('destroyed', () => { destroyed = true; });
const promise = readBody(req, 1000, 50);
req.emit('data', Buffer.from('{"a":1}'));
req.emit('end');
assert.deepEqual(await promise, { a: 1 });
await new Promise((r) => setTimeout(r, 100));
assert.equal(destroyed, false);
});

test('readBody: chunks are reassembled in order', async () => {
const req = makeFakeRequest();
const promise = readBody(req);
Expand Down
9 changes: 9 additions & 0 deletions oracle/http.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,15 @@ test('a body over the 1 MB limit is answered 413 on every route that reads one',
}
});

test('POST /attest takes at most 32 KB (the loopback routes keep 1 MB, tested below)', async () => {
// /attest is public. At a megabyte, every request a client left unfinished held a megabyte of the
// oracle until Node's five-minute request timeout.
const room = 32 * 1024 - JSON.stringify({ didHash: DID, success: true, attester: 'counteraudit', pad: '' }).length;
const over = await oracle.call('POST', '/attest', { didHash: DID, success: true, attester: 'counteraudit', pad: 'x'.repeat(room + 1) }, AUDITOR);
assert.equal(over.status, 413, over.text.slice(0, 120));
assert.equal(over.body.error, 'Request body too large');
});

test('the limit is 1 MB to the byte', async () => {
const unflagged = `0x${'12'.repeat(32)}`;
const room = MAX_BODY - JSON.stringify({ didHash: unflagged, pad: '' }).length;
Expand Down
Loading
Loading