brainchain-verify 0.7.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -14
- package/dist/abi.js +1 -1
- package/dist/cli.js +54 -38
- package/dist/verify.d.ts +25 -4
- package/dist/verify.js +220 -92
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
# brainchain-verify
|
|
2
2
|
|
|
3
|
-
Check any BrainChain decision against the chain. The tool reads the decision from the `DecisionLog`, fetches
|
|
3
|
+
Check any BrainChain decision against the chain. The tool reads the decision from the `DecisionLog`, fetches its published record, recomputes its hashes and confidence, and applies the task's thresholds the way the contracts do. It needs a public RPC and nothing else: no keys, no account.
|
|
4
|
+
|
|
5
|
+
Each record holds the question BrainChain asked Jev, a decision model served by TypeSafe, and Jev's answer with its probabilities.
|
|
4
6
|
|
|
5
7
|
It also checks the reputation BrainChain writes for its workers. Each entry in the ERC-8004 registry on Robinhood Chain is followed through its signed receipt to the decision, the payment and the task on the board.
|
|
6
8
|
|
|
@@ -32,7 +34,7 @@ brainchain-verify mainnet --agent <agentId> [--rpc <url>] [--registry-rpc <url>]
|
|
|
32
34
|
| `--task <id>` | Check every decision about one task, oldest first. |
|
|
33
35
|
| `--set <TaskBoard>` | A retired contract set from 3.0.0 on, by its TaskBoard address, by the key a decision page uses (`?set=v3-1`, or an older one the site still opens, such as `v4` for `v3-4`) or by release (`3.1.0`). Without it, the active set. Each set numbers its tasks and decisions from 1. The `v2` set is not supported: its board named tasks by id alone, which the subject check does not read. |
|
|
34
36
|
| `--rpc <url>` | Another RPC for the same chain. Records and briefs on private addresses are read only when this RPC is on one too. |
|
|
35
|
-
| `--receipt <file\|url>` | Check the receipt for a paid job, from a JSON file or an http(s) URL. Without a decision id, the tool checks the decision the receipt names, in the contract set its DecisionLog belongs to. See [receipts](#receipts). |
|
|
37
|
+
| `--receipt <file\|url>` | Check the receipt for a paid job, from a JSON file or an http(s) URL, of at most 64 KB. Without a decision id, the tool checks the decision the receipt names, in the contract set its DecisionLog belongs to. See [receipts](#receipts). |
|
|
36
38
|
| `--entry <agentId>:[<writer>:]<index>` | Check one reputation entry BrainChain wrote. See [reputation entries](#reputation-entries). |
|
|
37
39
|
| `--agent <agentId>` | Check every reputation entry BrainChain wrote for one agent, oldest first. |
|
|
38
40
|
| `--registry-rpc <url>` | Another RPC for Robinhood Chain, where the ERC-8004 registries are. |
|
|
@@ -40,13 +42,14 @@ brainchain-verify mainnet --agent <agentId> [--rpc <url>] [--registry-rpc <url>]
|
|
|
40
42
|
| `--json` | One JSON object on stdout. |
|
|
41
43
|
| `--version` | Print the version. |
|
|
42
44
|
|
|
43
|
-
The package carries the active and retired contract sets from [`deployments/`](
|
|
45
|
+
The package carries the active and retired contract sets from [`deployments/`](https://github.com/usebrainchain/brainchain/tree/main/deployments) as they stood when it was built. An unknown `--set` lists them.
|
|
44
46
|
|
|
45
47
|
## Output
|
|
46
48
|
|
|
47
49
|
```text
|
|
48
50
|
$ npx brainchain-verify mainnet 22 --set v3-1
|
|
49
51
|
Decision 22 on BrainChain mainnet, contract set v3-1 (DecisionLog 0xbe8E68EbDEaf2C65bc13D8AD070d17098Be6d335)
|
|
52
|
+
Task 11: Compare the rule of 72 with the exact doubling time
|
|
50
53
|
|
|
51
54
|
ok read from DecisionLog 0xbe8E…d335: grade, recorded 2026-11-01 00:40:23 UTC in block 419, confidence 8000 bps
|
|
52
55
|
ok fetched the record from https://brain.usebrainchain.com/records/0xc6570be10e86227b06d9ce78b739c83dac8d62e9f9cf33b67f25b7d148e8182a.json
|
|
@@ -66,7 +69,9 @@ Verdict: match. The published record is exactly what the chain recorded, and the
|
|
|
66
69
|
Not checked: that Jev produced the answer. See https://docs.usebrainchain.com/trust-model
|
|
67
70
|
```
|
|
68
71
|
|
|
69
|
-
|
|
72
|
+
Under the header, a decision about a task names the task by its brief's title, or the brief's first line, cut to 100 characters, once the brief committed on chain has been read. With `--task` that line reads `Brief:`. If the title is not the task you meant, check `--set`: each set numbers its own tasks and decisions.
|
|
73
|
+
|
|
74
|
+
Each line is one check. `ok` passed and `FAIL` means the record and the chain disagree. `skip` is a check with nothing to run on, such as a brief the host does not have, with the reason on the line. `ERROR` is a check that could not run because something it reads could not be read: the host did not answer in up to three tries and 30 seconds in all, answered with an error, or sent more than the tool reads. A record the host does not have, or one the tool refuses to read (see `fetch`), is an `ERROR` too, since no other check can run without it. With `--task` or `--agent`, a decision or entry the RPC cannot read gets one `ERROR` line, named `rpc`, and the others are still checked. Each RPC call gets two tries of 8 seconds, and an RPC error names the RPC by chain and origin, such as `BrainChain RPC https://rpc.usebrainchain.com` or `Robinhood Chain RPC https://rpc.mainnet.chain.robinhood.com`.
|
|
70
75
|
|
|
71
76
|
The verdict is `match`, `withheld`, `UNVERIFIED` or `MISMATCH`. `withheld` means a record served without the work passed the checks that could run, and says what they leave out.
|
|
72
77
|
|
|
@@ -75,12 +80,12 @@ The verdict is `match`, `withheld`, `UNVERIFIED` or `MISMATCH`. `withheld` means
|
|
|
75
80
|
| Check | What passes |
|
|
76
81
|
| --- | --- |
|
|
77
82
|
| `read` | `DecisionLog.get(id)` and the decision's `Recorded` event agree. |
|
|
78
|
-
| `fetch` | The record at the event's `payloadURI` (https, http or a base64 `data:` URI, with redirects refused) is a decision record of at most 4 MB. Briefs are read the same way, up to 256 KB. Anything on a private or loopback address is refused, however its name resolves, unless `--rpc` is on one too. |
|
|
83
|
+
| `fetch` | The record at the event's `payloadURI` (https, http or a base64 `data:` URI, with redirects refused) is a decision record of at most 4 MB. A body that is not JSON, such as a proxy's error page, is an `ERROR`; JSON that is not a decision record is a `FAIL`. Briefs are read the same way, up to 256 KB. Anything on a private or loopback address is refused, however its name resolves, unless `--rpc` is on one too. |
|
|
79
84
|
| `withheld` | On a record served without the work: the kind is a grade or ruling, the request carries the service's marker where the work was, and the chain shows the work is not public. If any of these fails, the record is held to its hashes like any other. |
|
|
80
85
|
| `record-hash` | `keccak256` of the fetched bytes equals `payloadHash`. |
|
|
81
86
|
| `input-hash` | `keccak256` of the record's `request`, serialized canonically (keys sorted, no whitespace), equals `inputHash`. |
|
|
82
87
|
| `kind` | The record's kind is the one on chain. |
|
|
83
|
-
| `subject` | A task decision names `TaskBoard.subjectOf(task)` for this chain and board. A change
|
|
88
|
+
| `subject` | A task decision names `TaskBoard.subjectOf(task)` for this chain and board. A change's subject is the one on chain; it is tied to the call Jev was shown only once the change is queued, by `change-subject` and `change-call`. A grade of outside work is matched by the rules below. |
|
|
84
89
|
| `options` | The probabilities cover exactly the options in the question. A panel that decided without Jev records none of Jev's, and `panel` checks that it names Jev as missing. |
|
|
85
90
|
| `answer` | The record's answer encodes to the one on chain: the hired model's id or worker address, or 1 for accept, pay, adopt and allow and 0 for their opposites. |
|
|
86
91
|
| `confidence` | The record's confidence times 10,000, rounded, equals `confidenceBps`. |
|
|
@@ -89,7 +94,7 @@ The verdict is `match`, `withheld`, `UNVERIFIED` or `MISMATCH`. `withheld` means
|
|
|
89
94
|
| `second-grader` | On a decision graded twice: the second grader's probability of paying recomputes from its probabilities, and the receipt id it carries is shown. |
|
|
90
95
|
| `judge` | On a decision by a panel, one line for each judge after the second grader: its probability of paying recomputes from its probabilities, which cover the question's options, and the receipt id it carries is shown. |
|
|
91
96
|
| `panel` | On a decision by a panel: the candidate rules recompute from the judges' probabilities of paying, the record's rule is one of them, and a panel short of a member says which and pays only from 90%. |
|
|
92
|
-
| `brief` | The question quotes the task's brief, fetched from its `Posted` event and checked against `briefHash`. Bytes that miss the hash are a `FAIL
|
|
97
|
+
| `brief` | The question quotes the task's brief, fetched from its `Posted` event and checked against `briefHash`. Bytes that miss the hash are a `FAIL`. A host that answers 404, or a location the tool refuses, is a `skip`. A host that does not answer, answers with an error or sends more than 256 KB is an `ERROR`. Either way, a grade's confidence is still recomputed, from the record's own pass level. |
|
|
93
98
|
| `checks` | A brief can carry checks: a fenced block marked `python checks` or `javascript checks`. The record of a grade or ruling on that brief holds BrainChain's run of them after the delivered code, and the line names the run's language and outcome. A run that failed, timed out, found no code in that language or was too long to run makes the answer reject, or refund on a ruling, at 10,000 bps. A run that passed is in the question the graders read, in BrainChain's own wording. A task record with checks in its brief and no run is a `FAIL`. |
|
|
94
99
|
| `levels` | A grade or ruling used the brief's own quality levels and pass level. On a grade of outside work, the pass level is a whole number naming one of the question's levels above the lowest. |
|
|
95
100
|
| `threshold` | The task's threshold, applied as `TaskBoard.hire`, `grade`, `rule` and `ruleAppeal` do, gives the outcome the board emitted. A poster can raise the grade and ruling thresholds while the task is open, so they can be higher than when it was posted; they cannot change after the hire. A ruling on appeal (set 3.5.0 and later) is checked against the board's `AppealRuled` event. A change is queued only on a yes. |
|
|
@@ -104,6 +109,7 @@ The verdict is `match`, `withheld`, `UNVERIFIED` or `MISMATCH`. `withheld` means
|
|
|
104
109
|
Some checks skip by design:
|
|
105
110
|
|
|
106
111
|
- A decision the board never applied, because a later decision or a closed window settled the task, skips `threshold`.
|
|
112
|
+
- A brief the host does not have, or one at a location the tool refuses, skips `brief`. A grade's confidence is then recomputed from the record's own pass level, and `levels` skips.
|
|
107
113
|
- A grade recorded before the chain gated on the paid levels skips `confidence-recomputed`: its confidence is Jev's score confidence, which the probabilities alone do not give.
|
|
108
114
|
- A grade or ruling recorded before BrainChain ran a brief's checks skips `checks` when its brief carries some. Such a record has no `jevPaid`, which every later grade and ruling states unless its panel decided without Jev.
|
|
109
115
|
- A grade of outside work skips `checks` when its brief ends in a checks block and its record holds no run. The section on grades of outside work says why.
|
|
@@ -134,9 +140,9 @@ The chain holds the hash too. A decision's `payloadURI` in its `Recorded` event
|
|
|
134
140
|
|
|
135
141
|
### Receipts
|
|
136
142
|
|
|
137
|
-
Every job an agent pays BrainChain for gets a receipt, signed by the key that records decisions. A paid grade gets one once
|
|
143
|
+
Every job an agent pays BrainChain for gets a receipt, signed by the key that records decisions. A paid grade gets one once BrainChain decides it. A paid task gets one once the board pays or refunds it, for the grade or ruling it settled on. Receipts come with a brain release that is not yet live on mainnet, so no record there carries one yet, and records from before that release never will. The receipt is EIP-712 under the domain `BrainChain receipt`, version 1, on the DecisionLog, in the envelope of the x402 offer-and-receipt extension (version 0.6): `{ format, payload, signature }`.
|
|
138
144
|
|
|
139
|
-
For
|
|
145
|
+
For a grade or ruling whose record has a `payments` field, the tool asks the host that serves the record for its receipt at `/receipts/<DecisionLog in lowercase>/<decision id>.json`. A record without one, as every record from before receipts is, gets no receipt line. A host that has none yet is a `skip`. A host that does not answer, or answers with an error, is an `ERROR`. `--offline` turns this off, and `--receipt` checks a receipt you kept instead.
|
|
140
146
|
|
|
141
147
|
On a receipt, the tool checks that:
|
|
142
148
|
|
|
@@ -145,7 +151,7 @@ On a receipt, the tool checks that:
|
|
|
145
151
|
- for a task, the board paid it for `accepted` and refunded it for `rejected`, and the last grade or ruling it applied is this decision. For a paid grade, `accepted` means accept at or above the board's grade bar when the decision was recorded.
|
|
146
152
|
- `network`, `asset`, `amount`, `payer` and `transaction` are those of a payment in the record, and on that network the transaction moved `amount` of `asset` from `payer` to the desk. The desk is the `payTo` for that network in the brain host's `/network.json`, which the tool believes only when `brain()` on the active DecisionLog signed it. A desk's former addresses count on EVM networks.
|
|
147
153
|
|
|
148
|
-
The tool reads payments on Base, Robinhood Chain and Solana, and on their testnets, from their public RPCs.
|
|
154
|
+
The tool reads payments on Base, Robinhood Chain and Solana, and on their testnets, from their public RPCs. A `/network.json` signed by another key, or naming another chain, fails `receipt-payment`. A host with no `/network.json`, or a payment on a network the tool has no RPC for, skips it. A host or RPC that does not answer is an `ERROR`, and so is a payment transaction the RPC does not find yet, since a node that lags or a Solana transaction not yet finalized can miss one. Only a transaction that reverted, or failed on Solana, fails.
|
|
149
155
|
|
|
150
156
|
### Keeping a receipt
|
|
151
157
|
|
|
@@ -219,7 +225,7 @@ Not checked: that Jev produced the answer. See https://docs.usebrainchain.com/tr
|
|
|
219
225
|
|
|
220
226
|
An entry's verdict is `match`, `no receipt`, `withheld`, `MISMATCH` or `UNVERIFIED`. `no receipt` means the hash is zero and every check that could run passed. `withheld` is a decision record served without the work, as for any decision.
|
|
221
227
|
|
|
222
|
-
`--agent` gives one line per entry: its verdict, its name and what it is about. Below an entry go the lines of any check that failed or could not run. The last line counts the entries, those with a receipt, those whose receipt and decision
|
|
228
|
+
`--agent` gives one line per entry: its verdict, its name and what it is about. Below an entry go the lines of any check that failed or could not run. The last line counts the entries, those with a receipt, those whose receipt and decision fully matched, those withheld, and those that failed. A withheld entry is never counted as verified. `--entry` with a name from the list shows every check.
|
|
223
229
|
|
|
224
230
|
```text
|
|
225
231
|
$ npx brainchain-verify mainnet --agent 20425
|
|
@@ -243,12 +249,12 @@ That Jev produced the answer. BrainChain records Jev's answers, and the contract
|
|
|
243
249
|
| Code | Meaning |
|
|
244
250
|
| --- | --- |
|
|
245
251
|
| 0 | Every check that could run passed. Skips do not fail a decision. A `withheld` verdict also exits 0, so read the verdict if you need to tell it from a full match. |
|
|
246
|
-
| 1 | A check failed, a record or receipt
|
|
252
|
+
| 1 | A check failed, a check could not run (an `ERROR` line, such as a record, brief or receipt the host did not serve), or the decision or entry could not be read: an unknown id, a task with no decisions, an entry the registry does not hold, an RPC error, a `--receipt` that cannot be read or is not a receipt. |
|
|
247
253
|
| 2 | Bad arguments, or an RPC that serves another chain. |
|
|
248
254
|
|
|
249
255
|
## JSON
|
|
250
256
|
|
|
251
|
-
`--json` prints one object. `decisions` holds one entry, or one per decision with `--task`. `verdict` is `match`, `withheld`, `mismatch` or `unverified` (a
|
|
257
|
+
`--json` prints one object. `decisions` holds one entry, or one per decision with `--task`. `verdict` is `match`, `withheld`, `mismatch` or `unverified` (a check could not run). With `withheld`, `withheldNotChecked` says what was left out, and the decision carries `withheld: true`. A decision about a task whose brief was read carries `title`, as the header shows it. A grade of outside work carries `outside: true`. A grade or ruling that holds a run of its brief's checks carries `run`, with the run's `language` and `outcome`. A grade or ruling decided by a panel carries `panel`: its `rule`, `judges` with each judge that answered by `model` and `paid`, Jev first, and `degraded`. A degraded panel also carries `missing` and `bar`. These are the record's own values, and the `judge` and `panel` checks say whether they recompute. A decision whose record matched the evidence hash on chain carries it as `evidence`. A decision whose receipt was checked carries `receipt`: where it was read as `from`, and the `job` and `outcome` it states. Each check keeps its `name` across releases, and its `status` is `ok`, `fail`, `skip` or `error`. When the tool cannot run, it prints `{ "error": "..." }` and exits 1, or 2 for bad arguments or an RPC that serves another chain. Trimmed to one check:
|
|
252
258
|
|
|
253
259
|
```json
|
|
254
260
|
{
|
|
@@ -271,6 +277,7 @@ That Jev produced the answer. BrainChain records Jev's answers, and the contract
|
|
|
271
277
|
"id": 22,
|
|
272
278
|
"kind": "grade",
|
|
273
279
|
"task": 11,
|
|
280
|
+
"title": "Compare the rule of 72 with the exact doubling time",
|
|
274
281
|
"block": 419,
|
|
275
282
|
"recordedAt": "2026-11-01 00:40:23 UTC",
|
|
276
283
|
"confidenceBps": 8000,
|
|
@@ -286,7 +293,7 @@ That Jev produced the answer. BrainChain records Jev's answers, and the contract
|
|
|
286
293
|
}
|
|
287
294
|
```
|
|
288
295
|
|
|
289
|
-
With `--entry` or `--agent`, the object holds `registry`, `verdict`, `summary` and `entries` instead of `set` and `decisions`, and `agentId` with `--agent`. `verdict` is `match`, `no-receipt`, `withheld`, `mismatch` or `unverified`. It is `no-receipt` only when every check passed and no entry had a receipt. `summary` counts `entries`, `withReceipt`, `verified`, `failed` and `unverified`. Each entry carries its name as `entry`, the fields of its `NewFeedback` event, the `task`, `board` and `set` its endpoint names, the `decision` its receipt names with its `id`, `set` and `kind`, its own `verdict` and its `checks`.
|
|
296
|
+
With `--entry` or `--agent`, the object holds `registry`, `verdict`, `summary` and `entries` instead of `set` and `decisions`, and `agentId` with `--agent`. `verdict` is `match`, `no-receipt`, `withheld`, `mismatch` or `unverified`. It is `no-receipt` only when every check passed and no entry had a receipt. `summary` counts `entries`, `withReceipt`, `verified`, `withheld`, `failed` and `unverified`. `verified` counts only entries whose verdict is `match`. Each entry carries its name as `entry`, the fields of its `NewFeedback` event, the `task`, `board` and `set` its endpoint names, the `decision` its receipt names with its `id`, `set` and `kind`, its own `verdict` and its `checks`.
|
|
290
297
|
|
|
291
298
|
## Building
|
|
292
299
|
|
package/dist/abi.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Generated by scripts/abi.mjs from
|
|
1
|
+
// Generated by scripts/abi.mjs from usebrainchain/brainchain 348cc37. Do not edit.
|
|
2
2
|
export const decisionLogAbi = [
|
|
3
3
|
{ "type": "function", "name": "acceptOwnership", "inputs": [], "outputs": [], "stateMutability": "nonpayable" },
|
|
4
4
|
{ "type": "function", "name": "allowApp", "inputs": [{ "name": "app", "type": "bytes32", "internalType": "bytes32" }, { "name": "allowed", "type": "bool", "internalType": "bool" }], "outputs": [], "stateMutability": "nonpayable" },
|
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
|
-
import { createPublicClient,
|
|
3
|
+
import { createPublicClient, isAddress } from "viem";
|
|
4
4
|
import { decisionLogAbi, taskBoardAbi } from "./abi.js";
|
|
5
5
|
import { NETWORKS } from "./deployments.js";
|
|
6
|
-
import { clean, decisionsOf, entriesOf, entryName, entryOutcome, errorMessage, outcomeOf, readReceipt, receiptDecision, REPUTATION, verifyDecision, verifyEntry, withheldNotChecked, } from "./verify.js";
|
|
6
|
+
import { clean, decisionsOf, entriesOf, entryName, entryOutcome, entryReport, entrySummary, errorMessage, isReceipt, outcomeOf, readReceipt, receiptDecision, REPUTATION, rpcTransport, verifyDecision, verifyEntry, withheldNotChecked, } from "./verify.js";
|
|
7
7
|
const USAGE = `Usage:
|
|
8
8
|
brainchain-verify <mainnet|testnet|chainId> <decisionId> [--set <TaskBoard>] [--rpc <url>] [--offline] [--json]
|
|
9
9
|
brainchain-verify <mainnet|testnet|chainId> --task <taskId> [--set <TaskBoard>] [--rpc <url>] [--offline] [--json]
|
|
@@ -40,6 +40,7 @@ const TRUST_MODEL = "https://docs.usebrainchain.com/trust-model";
|
|
|
40
40
|
const NOT_CHECKED = "That Jev produced the answer. BrainChain records Jev's answers, and the contracts bound what a recorded answer can do.";
|
|
41
41
|
// Sets before 3.0.0 named tasks by id alone, which the subject check does not model, so the package carries none.
|
|
42
42
|
const BEFORE_3 = /^(v2(-|$)|2\.|0x83b31d99fa31a9e5257955a737ef34c40f1c57bf$)/i;
|
|
43
|
+
// Only a command line of the wrong shape gets the usage. A value that names nothing the tool can read gets a message that says what would.
|
|
43
44
|
function usage(message) {
|
|
44
45
|
if (json)
|
|
45
46
|
fail(message, 2);
|
|
@@ -63,13 +64,16 @@ const flag = (name) => {
|
|
|
63
64
|
if (value === undefined || value.startsWith("--"))
|
|
64
65
|
usage(`${name} needs a value`);
|
|
65
66
|
args.splice(at, 2);
|
|
67
|
+
if (args.includes(name))
|
|
68
|
+
usage(`${name} given twice`);
|
|
66
69
|
return value;
|
|
67
70
|
};
|
|
71
|
+
// A switch given twice means the same as once.
|
|
68
72
|
const toggle = (name) => {
|
|
69
|
-
const
|
|
70
|
-
|
|
73
|
+
const given = args.length;
|
|
74
|
+
for (let at = args.indexOf(name); at >= 0; at = args.indexOf(name))
|
|
71
75
|
args.splice(at, 1);
|
|
72
|
-
return
|
|
76
|
+
return args.length < given;
|
|
73
77
|
};
|
|
74
78
|
const json = toggle("--json");
|
|
75
79
|
const offline = toggle("--offline");
|
|
@@ -86,9 +90,9 @@ if (unknown)
|
|
|
86
90
|
usage(`Unknown option ${unknown}`);
|
|
87
91
|
const web = (url) => URL.canParse(url) && ["http:", "https:"].includes(new URL(url).protocol);
|
|
88
92
|
if (rpcArg !== undefined && !web(rpcArg))
|
|
89
|
-
|
|
93
|
+
fail("--rpc needs an http or https URL", 2);
|
|
90
94
|
if (registryRpcArg !== undefined && !web(registryRpcArg))
|
|
91
|
-
|
|
95
|
+
fail("--registry-rpc needs an http or https URL", 2);
|
|
92
96
|
const [networkArg, idArg, ...extra] = args;
|
|
93
97
|
if (networkArg === undefined)
|
|
94
98
|
usage("Name a network: mainnet, testnet or a chain id");
|
|
@@ -108,24 +112,28 @@ if (!reputation && taskArg === undefined && idArg === undefined && receiptArg ==
|
|
|
108
112
|
usage("Name a decision id, a task with --task, or an entry with --entry");
|
|
109
113
|
const given = taskArg ?? idArg;
|
|
110
114
|
if (given !== undefined && !/^[1-9]\d*$/.test(given))
|
|
111
|
-
|
|
115
|
+
fail(`${taskArg === undefined ? "A decision" : "A task"} id is a whole number from 1`, 2);
|
|
112
116
|
const foundNetwork = Object.hasOwn(NETWORKS, networkArg)
|
|
113
117
|
? NETWORKS[networkArg]
|
|
114
118
|
: Object.values(NETWORKS).find((n) => String(n.chainId) === networkArg);
|
|
115
119
|
if (!foundNetwork)
|
|
116
|
-
|
|
120
|
+
fail(`Unknown network "${networkArg}": use mainnet, testnet, 274663 or 274630`, 2);
|
|
117
121
|
const network = foundNetwork;
|
|
118
|
-
const client = createPublicClient({ transport:
|
|
122
|
+
const client = createPublicClient({ transport: rpcTransport("BrainChain", rpcArg ?? network.rpc) });
|
|
119
123
|
const TAGS = { ok: "ok", fail: "FAIL", skip: "skip", error: "ERROR" };
|
|
120
124
|
const tally = (checks, status) => checks.filter((c) => c.status === status).length;
|
|
125
|
+
// With --task or --agent, one decision or entry the RPC cannot read is an error line of its own, and the rest still run.
|
|
126
|
+
const unread = (what, error) => ({ name: "rpc", status: "error", message: `could not check ${what}: ${errorMessage(error)}` });
|
|
121
127
|
const ENTRY_TAGS = { match: "match", "no-receipt": "no receipt", withheld: "withheld", mismatch: "MISMATCH", unverified: "UNVERIFIED" };
|
|
122
128
|
if (reputation)
|
|
123
129
|
await checkEntries();
|
|
124
130
|
const receipt = receiptArg === undefined ? undefined : await readReceipt(client, receiptArg).catch((error) => fail(errorMessage(error)));
|
|
131
|
+
if (receipt && !isReceipt(receipt.value))
|
|
132
|
+
fail(`${receipt.from} is not a receipt as BrainChain or the x402 extension signs one`);
|
|
125
133
|
const named = receipt && receiptDecision(receipt.value);
|
|
126
134
|
const target = given ?? named?.decision;
|
|
127
135
|
if (target === undefined || !/^[1-9]\d*$/.test(target))
|
|
128
|
-
|
|
136
|
+
fail("The receipt names no decision; give the decision's id", 2);
|
|
129
137
|
// A receipt names its log, so it opens a retired set on its own.
|
|
130
138
|
const receiptSet = named && network.sets.find((s) => s.log.toLowerCase() === named.decisionLog.toLowerCase());
|
|
131
139
|
const foundSet = setArg === undefined
|
|
@@ -133,9 +141,9 @@ const foundSet = setArg === undefined
|
|
|
133
141
|
: network.sets.find((s) => (isAddress(setArg) ? s.board.toLowerCase() === setArg.toLowerCase() : s.key === setArg || s.release === setArg || s.aliases?.includes(setArg)));
|
|
134
142
|
if (!foundSet) {
|
|
135
143
|
if (setArg !== undefined && BEFORE_3.test(setArg))
|
|
136
|
-
|
|
144
|
+
fail(`Contract set ${setArg} predates release 3.0.0, which this tool does not read: those boards named tasks by id alone.`, 2);
|
|
137
145
|
const sets = network.sets.map((s, i) => `${s.key} (TaskBoard ${s.board}${i === 0 ? ", active" : ""})`);
|
|
138
|
-
|
|
146
|
+
fail(`No contract set ${setArg} on ${network.name}. Sets: ${sets.join(", ")}`, 2);
|
|
139
147
|
}
|
|
140
148
|
const set = foundSet;
|
|
141
149
|
const ctx = { client, network, set, briefs: new Map(), offline };
|
|
@@ -154,7 +162,7 @@ function verdict(reports) {
|
|
|
154
162
|
case "mismatch":
|
|
155
163
|
return `Verdict: MISMATCH. ${failed} check${failed === 1 ? "" : "s"} failed; see the FAIL lines.`;
|
|
156
164
|
case "unverified":
|
|
157
|
-
return "Verdict: UNVERIFIED.
|
|
165
|
+
return "Verdict: UNVERIFIED. Some checks could not run; the ERROR lines say what could not be read.";
|
|
158
166
|
case "withheld":
|
|
159
167
|
return `Verdict: withheld, not a full match${many ? ` (decision${reports.filter((r) => r.withheld).length === 1 ? "" : "s"} ${reports.filter((r) => r.withheld).map((r) => r.id).join(", ")})` : ""}. ${withheldNotChecked(reports)}`;
|
|
160
168
|
case "match":
|
|
@@ -176,6 +184,7 @@ function report(reports, header, task) {
|
|
|
176
184
|
id: r.id,
|
|
177
185
|
kind: r.kind,
|
|
178
186
|
task: r.task,
|
|
187
|
+
...(r.title ? { title: r.title } : {}),
|
|
179
188
|
...(r.outside ? { outside: true } : {}),
|
|
180
189
|
...(r.withheld ? { withheld: true } : {}),
|
|
181
190
|
...(r.run ? { run: r.run } : {}),
|
|
@@ -219,10 +228,10 @@ function report(reports, header, task) {
|
|
|
219
228
|
async function sameChain(registry) {
|
|
220
229
|
const chainId = await client.getChainId();
|
|
221
230
|
if (chainId !== network.chainId)
|
|
222
|
-
|
|
231
|
+
fail(`The RPC serves chain ${chainId}, not ${network.name} (${network.chainId})`, 2);
|
|
223
232
|
const registryChain = await registry?.client.getChainId();
|
|
224
233
|
if (registry && registryChain !== registry.chainId)
|
|
225
|
-
|
|
234
|
+
fail(`The registry RPC serves chain ${registryChain}, not Robinhood Chain (${registry.chainId})`, 2);
|
|
226
235
|
}
|
|
227
236
|
function entryVerdict(r) {
|
|
228
237
|
const failed = tally(r.checks, "fail");
|
|
@@ -230,7 +239,7 @@ function entryVerdict(r) {
|
|
|
230
239
|
case "mismatch":
|
|
231
240
|
return `Verdict: MISMATCH. ${failed} check${failed === 1 ? "" : "s"} failed; see the FAIL lines.`;
|
|
232
241
|
case "unverified":
|
|
233
|
-
return "Verdict: UNVERIFIED.
|
|
242
|
+
return "Verdict: UNVERIFIED. Some checks could not run; the ERROR lines say what could not be read.";
|
|
234
243
|
case "withheld":
|
|
235
244
|
return `Verdict: withheld, not a full match. ${withheldNotChecked([r.decision])}`;
|
|
236
245
|
case "no-receipt":
|
|
@@ -248,14 +257,7 @@ function about(r) {
|
|
|
248
257
|
}
|
|
249
258
|
function reportEntries(reports, header, agentId) {
|
|
250
259
|
const outcomes = reports.map((r) => entryOutcome([r]));
|
|
251
|
-
const
|
|
252
|
-
const summary = {
|
|
253
|
-
entries: reports.length,
|
|
254
|
-
withReceipt: receipted.length,
|
|
255
|
-
verified: receipted.filter((r) => ["match", "withheld"].includes(entryOutcome([r]))).length,
|
|
256
|
-
failed: outcomes.filter((o) => o === "mismatch").length,
|
|
257
|
-
unverified: outcomes.filter((o) => o === "unverified").length,
|
|
258
|
-
};
|
|
260
|
+
const summary = entrySummary(reports);
|
|
259
261
|
const all = reports.flatMap((r) => r.checks);
|
|
260
262
|
const status = tally(all, "fail") + tally(all, "error") > 0 ? 1 : 0;
|
|
261
263
|
if (json) {
|
|
@@ -293,8 +295,8 @@ function reportEntries(reports, header, agentId) {
|
|
|
293
295
|
if (c.status === "fail" || c.status === "error")
|
|
294
296
|
console.log(` ${TAGS[c.status].padEnd(5)} ${c.message}`);
|
|
295
297
|
}
|
|
296
|
-
const { entries, withReceipt, verified, failed, unverified } = summary;
|
|
297
|
-
console.log(`\n${entries} entr${entries === 1 ? "y" : "ies"}, ${withReceipt} with a receipt, ${verified} verified, ${failed} failed${unverified > 0 ? `, ${unverified} could not be checked` : ""}.`);
|
|
298
|
+
const { entries, withReceipt, verified, withheld, failed, unverified } = summary;
|
|
299
|
+
console.log(`\n${entries} entr${entries === 1 ? "y" : "ies"}, ${withReceipt} with a receipt, ${verified} verified${withheld > 0 ? `, ${withheld} withheld` : ""}, ${failed} failed${unverified > 0 ? `, ${unverified} could not be checked` : ""}.`);
|
|
298
300
|
}
|
|
299
301
|
console.log(`Not checked: that Jev produced the answer. See ${TRUST_MODEL}`);
|
|
300
302
|
process.exit(status);
|
|
@@ -302,19 +304,19 @@ function reportEntries(reports, header, agentId) {
|
|
|
302
304
|
/** --entry and --agent: BrainChain's entries in the ERC-8004 reputation registry, each checked through its receipt to the chain. */
|
|
303
305
|
async function checkEntries() {
|
|
304
306
|
if (network.chainId !== REPUTATION.network)
|
|
305
|
-
|
|
306
|
-
const registry = { ...REPUTATION, client: createPublicClient({ transport:
|
|
307
|
+
fail("BrainChain writes reputation entries for mainnet tasks only, so --entry and --agent read mainnet", 2);
|
|
308
|
+
const registry = { ...REPUTATION, client: createPublicClient({ transport: rpcTransport("Robinhood Chain", registryRpcArg ?? REPUTATION.rpc) }) };
|
|
307
309
|
const [current, ...earlier] = registry.writers;
|
|
308
310
|
const where = `in the ERC-8004 reputation registry on Robinhood Chain (${registry.address})`;
|
|
309
311
|
const ctx = { client, network, set: network.sets[0], briefs: new Map() };
|
|
310
312
|
if (entryArg !== undefined) {
|
|
311
313
|
const parts = /^(0|[1-9]\d{0,77}):(?:(0x[0-9a-fA-F]{40}):)?([1-9]\d{0,19})$/.exec(entryArg);
|
|
312
314
|
if (!parts)
|
|
313
|
-
|
|
315
|
+
fail("An entry is <agentId>:<feedbackIndex>, or <agentId>:<writer>:<feedbackIndex> for one BrainChain wrote from an earlier address", 2);
|
|
314
316
|
const named = parts[2];
|
|
315
317
|
const writer = named === undefined ? current : registry.writers.find((w) => w.toLowerCase() === named.toLowerCase());
|
|
316
318
|
if (!writer)
|
|
317
|
-
|
|
319
|
+
fail(`BrainChain writes its entries from ${registry.writers.join(" and ")}, not ${named}`, 2);
|
|
318
320
|
const agentId = BigInt(parts[1]);
|
|
319
321
|
const index = BigInt(parts[3]);
|
|
320
322
|
try {
|
|
@@ -333,7 +335,7 @@ async function checkEntries() {
|
|
|
333
335
|
}
|
|
334
336
|
}
|
|
335
337
|
if (!/^(0|[1-9]\d{0,77})$/.test(agentArg))
|
|
336
|
-
|
|
338
|
+
fail("An agent id is a whole number", 2);
|
|
337
339
|
const agentId = BigInt(agentArg);
|
|
338
340
|
try {
|
|
339
341
|
await sameChain(registry);
|
|
@@ -342,13 +344,24 @@ async function checkEntries() {
|
|
|
342
344
|
fail(`BrainChain has written no entry for agent ${agentId} ${where}`);
|
|
343
345
|
const reports = [];
|
|
344
346
|
for (const f of found)
|
|
345
|
-
reports.push(await verifyEntry(ctx, registry, f));
|
|
347
|
+
reports.push(await verifyEntry(ctx, registry, f).catch((error) => entryReport(registry, f, [unread(`entry ${entryName(registry, f)}`, error)])));
|
|
346
348
|
reportEntries(reports, `Agent ${agentId} ${where}: ${found.length} entr${found.length === 1 ? "y" : "ies"} BrainChain wrote`, agentId.toString());
|
|
347
349
|
}
|
|
348
350
|
catch (error) {
|
|
349
351
|
fail(errorMessage(error));
|
|
350
352
|
}
|
|
351
353
|
}
|
|
354
|
+
/** The other sets whose boards hold a task with this id, for a task this set's board does not hold or decided nothing on. */
|
|
355
|
+
async function otherBoards(task) {
|
|
356
|
+
const others = network.sets.filter((s) => s !== set);
|
|
357
|
+
// Only a hint, so a board the RPC cannot read is left out of it.
|
|
358
|
+
const counts = await Promise.allSettled(others.map((s) => client.readContract({ address: s.board, abi: taskBoardAbi, functionName: "count" })));
|
|
359
|
+
const holding = others.filter((_, i) => {
|
|
360
|
+
const count = counts[i];
|
|
361
|
+
return count.status === "fulfilled" && count.value >= task;
|
|
362
|
+
});
|
|
363
|
+
return holding.length > 0 ? ` Each set numbers its own tasks; try --set ${holding.map((s) => s.key).join(" or ")}.` : "";
|
|
364
|
+
}
|
|
352
365
|
try {
|
|
353
366
|
await sameChain();
|
|
354
367
|
const where = `on ${network.name}, contract set ${set.key}`;
|
|
@@ -356,14 +369,15 @@ try {
|
|
|
356
369
|
const task = BigInt(taskArg);
|
|
357
370
|
const tasks = await ctx.client.readContract({ address: set.board, abi: taskBoardAbi, functionName: "count" });
|
|
358
371
|
if (task > tasks)
|
|
359
|
-
fail(`TaskBoard ${set.board} (set ${set.key}) holds tasks 1 to ${tasks}`);
|
|
372
|
+
fail(`TaskBoard ${set.board} (set ${set.key}) holds tasks 1 to ${tasks}.${await otherBoards(task)}`);
|
|
360
373
|
const ids = await decisionsOf(ctx, task);
|
|
361
374
|
if (ids.length === 0)
|
|
362
|
-
fail(`Task ${task} has no decisions ${where}`);
|
|
375
|
+
fail(`Task ${task} has no decisions ${where}.${await otherBoards(task)}`);
|
|
363
376
|
const reports = [];
|
|
364
377
|
for (const id of ids)
|
|
365
|
-
reports.push(await verifyDecision(ctx, id));
|
|
366
|
-
|
|
378
|
+
reports.push(await verifyDecision(ctx, id).catch((error) => ({ id: Number(id), checks: [unread(`decision ${id}`, error)] })));
|
|
379
|
+
const title = reports.find((r) => r.title)?.title;
|
|
380
|
+
report(reports, `Task ${task} ${where} (TaskBoard ${set.board}): decision${ids.length === 1 ? "" : "s"} ${ids.join(", ")}${title ? `\nBrief: ${title}` : ""}`, Number(task));
|
|
367
381
|
}
|
|
368
382
|
const id = BigInt(target);
|
|
369
383
|
const decisions = await ctx.client.readContract({ address: set.log, abi: decisionLogAbi, functionName: "count" });
|
|
@@ -372,7 +386,9 @@ try {
|
|
|
372
386
|
const hint = others.length > 0 ? ` Each set numbers its own decisions; try --set ${others.join(" or ")}.` : "";
|
|
373
387
|
fail(`DecisionLog ${set.log} (set ${set.key}) holds decisions 1 to ${decisions}.${hint}`);
|
|
374
388
|
}
|
|
375
|
-
|
|
389
|
+
const checked = await verifyDecision(ctx, id, receipt);
|
|
390
|
+
// What the task is about, so a decision read from the wrong set does not pass for the one meant.
|
|
391
|
+
report([checked], `Decision ${id} ${where} (DecisionLog ${set.log})${checked.title ? `\nTask ${checked.task}: ${checked.title}` : ""}`);
|
|
376
392
|
}
|
|
377
393
|
catch (error) {
|
|
378
394
|
fail(errorMessage(error));
|
package/dist/verify.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type Address, type Hex, type PublicClient } from "viem";
|
|
1
|
+
import { type Address, type Hex, type HttpTransport, type PublicClient } from "viem";
|
|
2
2
|
import type { ContractSet, Network } from "./deployments.js";
|
|
3
3
|
/** `error` is a check that could not complete, such as a record host that did not answer. */
|
|
4
4
|
export type Status = "ok" | "fail" | "skip" | "error";
|
|
@@ -30,6 +30,8 @@ export interface DecisionReport {
|
|
|
30
30
|
id: number;
|
|
31
31
|
kind?: string;
|
|
32
32
|
task?: number;
|
|
33
|
+
/** The task's brief by its title, or its first line, cut to 100 characters. Set once the brief committed on chain was read. */
|
|
34
|
+
title?: string;
|
|
33
35
|
/** A grade of work delivered outside BrainChain, so no task here. */
|
|
34
36
|
outside?: boolean;
|
|
35
37
|
/** Served without the work, as the chain shows it may be, so its hashes could not be checked. */
|
|
@@ -63,8 +65,9 @@ export interface Payment {
|
|
|
63
65
|
}
|
|
64
66
|
/**
|
|
65
67
|
* How a transaction changed each owner's balance of `asset`, by owner, in
|
|
66
|
-
* lowercase on EVM networks. Undefined when it
|
|
67
|
-
*
|
|
68
|
+
* lowercase on EVM networks. Undefined when it did not succeed, or cannot be on
|
|
69
|
+
* `network`. Throws when the network's RPC does not find it, which a lagging
|
|
70
|
+
* node can explain.
|
|
68
71
|
*/
|
|
69
72
|
export type Balances = (network: string, transaction: string, asset: string) => Promise<Map<string, bigint> | undefined>;
|
|
70
73
|
export interface Context {
|
|
@@ -72,7 +75,7 @@ export interface Context {
|
|
|
72
75
|
network: Network;
|
|
73
76
|
set: ContractSet;
|
|
74
77
|
briefs: Map<bigint, Promise<Brief>>;
|
|
75
|
-
/** Reads payment transactions; public RPCs for Base, Robinhood Chain and Solana when absent. */
|
|
78
|
+
/** Reads payment transactions; public RPCs for Base, Robinhood Chain and Solana when absent. balancesFrom builds one from other RPCs. */
|
|
76
79
|
balances?: Balances;
|
|
77
80
|
/** Fetches no receipt from the brain host, so only one given to verifyDecision is checked. */
|
|
78
81
|
offline?: boolean;
|
|
@@ -92,17 +95,23 @@ interface Brief {
|
|
|
92
95
|
}
|
|
93
96
|
export declare const clean: (text: string) => string;
|
|
94
97
|
export declare function errorMessage(error: unknown): string;
|
|
98
|
+
/** An http transport for one RPC, with two tries of 8 seconds, whose errors say which RPC failed: `name` is its chain, as in "BrainChain RPC <origin>". */
|
|
99
|
+
export declare function rpcTransport(name: string, url: string): HttpTransport;
|
|
95
100
|
/** Decision ids about one task on the set's board, oldest first. */
|
|
96
101
|
export declare function decisionsOf({ client, network, set }: Context, task: bigint): Promise<bigint[]>;
|
|
97
102
|
/** `receipt` is one the caller kept. Without it, the receipt of a paid grade or ruling is fetched from the host that serves its record, unless the context is offline. */
|
|
98
103
|
export declare function verifyDecision(ctx: Context, id: bigint, receipt?: GivenReceipt): Promise<DecisionReport>;
|
|
99
104
|
/** Reads a receipt from a file or an http(s) URL: the receipt itself, or a reply that carries it as `receipt`. */
|
|
100
105
|
export declare function readReceipt(client: PublicClient, source: string): Promise<GivenReceipt>;
|
|
106
|
+
/** Whether a value is a receipt as BrainChain or the x402 extension signs one. */
|
|
107
|
+
export declare const isReceipt: (value: unknown) => boolean;
|
|
101
108
|
/** The decision and log a BrainChain receipt names. The x402 extension's receipt names neither. */
|
|
102
109
|
export declare function receiptDecision(value: unknown): {
|
|
103
110
|
decision: string;
|
|
104
111
|
decisionLog: Address;
|
|
105
112
|
} | undefined;
|
|
113
|
+
/** Reads payment transactions from the RPC given for each CAIP-2 network, such as eip155:8453. */
|
|
114
|
+
export declare function balancesFrom(rpcs: Readonly<Record<string, string>>): Balances;
|
|
106
115
|
export type Outcome = "match" | "withheld" | "unverified" | "mismatch";
|
|
107
116
|
/** Disagreement first, then what could not be read. A withheld record never reads as a match: its hashes were not checked. */
|
|
108
117
|
export declare function outcomeOf(reports: Pick<DecisionReport, "checks" | "withheld">[]): Outcome;
|
|
@@ -182,6 +191,8 @@ export interface EntryReport {
|
|
|
182
191
|
checks: Check[];
|
|
183
192
|
}
|
|
184
193
|
export declare const entryName: (registry: Registry, f: Pick<Feedback, "agentId" | "clientAddress" | "feedbackIndex">) => string;
|
|
194
|
+
/** An entry as its NewFeedback event states it, with `checks` as its own. */
|
|
195
|
+
export declare function entryReport(registry: Registry, f: Feedback, checks: Check[]): EntryReport;
|
|
185
196
|
/** Every entry BrainChain wrote for an agent, from the writers given or all of its own, oldest first. */
|
|
186
197
|
export declare function entriesOf(registry: Registry, agentId: bigint, writers?: readonly Address[]): Promise<Feedback[]>;
|
|
187
198
|
/**
|
|
@@ -194,4 +205,14 @@ export declare function verifyEntry(ctx: Context, registry: Registry, f: Feedbac
|
|
|
194
205
|
export type EntryOutcome = Outcome | "no-receipt";
|
|
195
206
|
/** As for decisions, and `no-receipt` when everything passed and no entry had a receipt to check. */
|
|
196
207
|
export declare function entryOutcome(reports: EntryReport[]): EntryOutcome;
|
|
208
|
+
export interface EntrySummary {
|
|
209
|
+
entries: number;
|
|
210
|
+
withReceipt: number;
|
|
211
|
+
/** Entries whose receipt and decision fully matched. A copy served without the work never does. */
|
|
212
|
+
verified: number;
|
|
213
|
+
withheld: number;
|
|
214
|
+
failed: number;
|
|
215
|
+
unverified: number;
|
|
216
|
+
}
|
|
217
|
+
export declare function entrySummary(reports: EntryReport[]): EntrySummary;
|
|
197
218
|
export {};
|
package/dist/verify.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { lookup as dnsLookup, promises as dns } from "node:dns";
|
|
2
|
-
import {
|
|
2
|
+
import { open, stat } from "node:fs/promises";
|
|
3
3
|
import { Agent as HttpAgent, request as httpRequest } from "node:http";
|
|
4
4
|
import { Agent as HttpsAgent, request as httpsRequest } from "node:https";
|
|
5
5
|
import { BlockList, isIP } from "node:net";
|
|
@@ -65,15 +65,49 @@ function rootCause(error) {
|
|
|
65
65
|
}
|
|
66
66
|
return reason;
|
|
67
67
|
}
|
|
68
|
+
function describe(error) {
|
|
69
|
+
const reason = rootCause(error);
|
|
70
|
+
if (!(error instanceof BaseError))
|
|
71
|
+
return reason ? `${error.message}: ${reason}` : error.message;
|
|
72
|
+
const detail = reason ?? error.details;
|
|
73
|
+
return detail ? `${error.shortMessage} (${detail})` : error.shortMessage;
|
|
74
|
+
}
|
|
68
75
|
export function errorMessage(error) {
|
|
69
76
|
if (!(error instanceof Error))
|
|
70
77
|
return clean(String(error));
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
78
|
+
const rpc = rpcOf(error);
|
|
79
|
+
return clean(rpc ? `${rpc}: ${describe(error)}` : describe(error));
|
|
80
|
+
}
|
|
81
|
+
// Which RPC an error came from, so a failure on --rpc reads apart from one on --registry-rpc.
|
|
82
|
+
const rpcNames = new WeakMap();
|
|
83
|
+
// Only the origin: providers put API keys in the path.
|
|
84
|
+
const rpcLabel = (name, url) => (URL.canParse(url) ? `${name} RPC ${new URL(url).origin}` : `${name} RPC`);
|
|
85
|
+
function fromRpc(error, rpc) {
|
|
86
|
+
if (error instanceof Error)
|
|
87
|
+
rpcNames.set(error, rpc);
|
|
88
|
+
return error;
|
|
89
|
+
}
|
|
90
|
+
function rpcOf(error) {
|
|
91
|
+
for (let next = error; next instanceof Error; next = next.cause) {
|
|
92
|
+
const rpc = rpcNames.get(next);
|
|
93
|
+
if (rpc)
|
|
94
|
+
return rpc;
|
|
95
|
+
}
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
// viem's own default, four tries of 10 seconds, held the tool 40 seconds on an RPC that never answers.
|
|
99
|
+
const RPC_TIMEOUT_MS = 8_000;
|
|
100
|
+
/** An http transport for one RPC, with two tries of 8 seconds, whose errors say which RPC failed: `name` is its chain, as in "BrainChain RPC <origin>". */
|
|
101
|
+
export function rpcTransport(name, url) {
|
|
102
|
+
const transport = http(url, { timeout: RPC_TIMEOUT_MS, retryCount: 1 });
|
|
103
|
+
const rpc = rpcLabel(name, url);
|
|
104
|
+
return (config) => {
|
|
105
|
+
const built = transport(config);
|
|
106
|
+
const request = ((args, options) => built.request(args, options).catch((error) => {
|
|
107
|
+
throw fromRpc(error, rpc);
|
|
108
|
+
}));
|
|
109
|
+
return { ...built, request };
|
|
110
|
+
};
|
|
77
111
|
}
|
|
78
112
|
function parseJson(text) {
|
|
79
113
|
try {
|
|
@@ -218,12 +252,17 @@ const MAX_RECORD_BYTES = 4 * 1024 * 1024;
|
|
|
218
252
|
const MAX_BRIEF_BYTES = 256 * 1024;
|
|
219
253
|
const MAX_RECEIPT_BYTES = 64 * 1024;
|
|
220
254
|
const MAX_MANIFEST_BYTES = 256 * 1024;
|
|
221
|
-
/** A location the tool will not read. Trying again would not help. */
|
|
255
|
+
/** A location or payment network the tool will not read. Trying again would not help. */
|
|
222
256
|
class Refused extends Error {
|
|
223
257
|
}
|
|
258
|
+
/** More than the thing fetched may be. Not tried again either, but unlike a refused location, a check that could not run. */
|
|
259
|
+
class TooLarge extends Refused {
|
|
260
|
+
}
|
|
224
261
|
/** A host that answered 404, which for a receipt means it has not been signed yet. */
|
|
225
262
|
class NotFound extends Error {
|
|
226
263
|
}
|
|
264
|
+
/** Not there to check: a host's 404, or a location the tool will not read. A host that fails to answer, or sends too much, is a check that could not run. */
|
|
265
|
+
const absent = (error) => error instanceof NotFound || (error instanceof Refused && !(error instanceof TooLarge));
|
|
227
266
|
const PRIVATE = new BlockList();
|
|
228
267
|
for (const [net, bits] of [["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], ["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.168.0.0", 16], ["224.0.0.0", 4], ["240.0.0.0", 4]]) {
|
|
229
268
|
PRIVATE.addSubnet(net, bits, "ipv4");
|
|
@@ -288,7 +327,7 @@ function readOnce(uri, url, wanted, signal) {
|
|
|
288
327
|
response.on("data", (chunk) => {
|
|
289
328
|
size += chunk.length;
|
|
290
329
|
if (size > wanted.limit)
|
|
291
|
-
request.destroy(new
|
|
330
|
+
request.destroy(new TooLarge(`${display(uri)} is larger than the ${Math.round(wanted.limit / 1024)} KB a ${wanted.what} may be, so it was not read`));
|
|
292
331
|
else
|
|
293
332
|
chunks.push(chunk);
|
|
294
333
|
});
|
|
@@ -323,7 +362,7 @@ async function get(uri, url, wanted, deadline) {
|
|
|
323
362
|
async function readBytes(uri, url, wanted, deadline) {
|
|
324
363
|
const response = await get(uri, url, wanted, deadline);
|
|
325
364
|
if (response.status === 404) {
|
|
326
|
-
const gone = wanted.what === "network manifest" ? "the host has none" : `the host
|
|
365
|
+
const gone = wanted.what === "network manifest" ? "the host has none" : `the host has no ${wanted.what} at this address`;
|
|
327
366
|
throw new NotFound(`${display(uri)} answered with status 404: ${gone}`);
|
|
328
367
|
}
|
|
329
368
|
if (response.status < 200 || response.status >= 300)
|
|
@@ -334,10 +373,10 @@ async function fetchBytes(uri, wanted) {
|
|
|
334
373
|
if (uri.startsWith("data:")) {
|
|
335
374
|
const comma = uri.indexOf(",");
|
|
336
375
|
if (comma < 0 || !uri.slice(0, comma).endsWith(";base64"))
|
|
337
|
-
throw new
|
|
376
|
+
throw new Refused("only base64 data URIs are supported");
|
|
338
377
|
const bytes = Uint8Array.from(Buffer.from(uri.slice(comma + 1), "base64"));
|
|
339
378
|
if (bytes.length > wanted.limit)
|
|
340
|
-
throw new
|
|
379
|
+
throw new TooLarge(`the ${wanted.what} is larger than the ${Math.round(wanted.limit / 1024)} KB it may be, so it was not read`);
|
|
341
380
|
return { bytes, withheld: false };
|
|
342
381
|
}
|
|
343
382
|
if (!URL.canParse(uri))
|
|
@@ -374,8 +413,8 @@ class Checks {
|
|
|
374
413
|
function readDecision({ client, set }, id) {
|
|
375
414
|
return client.readContract({ address: set.log, abi: decisionLogAbi, functionName: "get", args: [id] });
|
|
376
415
|
}
|
|
377
|
-
/**
|
|
378
|
-
class
|
|
416
|
+
/** What the chain contradicts, such as bytes that miss their hash: a disagreement, where an unreachable host is only a check that could not run. */
|
|
417
|
+
class Mismatch extends Error {
|
|
379
418
|
}
|
|
380
419
|
async function briefOf({ client, set }, task) {
|
|
381
420
|
const [posted] = await client.getContractEvents({
|
|
@@ -390,9 +429,17 @@ async function briefOf({ client, set }, task) {
|
|
|
390
429
|
throw new Error(`task ${task} has no Posted event on board ${set.board}`);
|
|
391
430
|
const { bytes } = await fetchBytes(posted.args.briefURI, { what: "brief", limit: MAX_BRIEF_BYTES, allowPrivate: await allowsPrivate(client) });
|
|
392
431
|
if (keccak256(bytes) !== posted.args.briefHash.toLowerCase())
|
|
393
|
-
throw new
|
|
432
|
+
throw new Mismatch(`task ${task}'s brief does not match its briefHash on chain`);
|
|
394
433
|
return parseBrief(decodeText(bytes));
|
|
395
434
|
}
|
|
435
|
+
/** What a task is about: its brief's title, or the brief's first line, cut to 100 characters. */
|
|
436
|
+
function headline({ title, brief }) {
|
|
437
|
+
const line = [title, brief].flatMap((text) => text.split("\n")).map((l) => l.trim()).find((l) => l.length > 0);
|
|
438
|
+
if (line === undefined)
|
|
439
|
+
return undefined;
|
|
440
|
+
const chars = [...line];
|
|
441
|
+
return clean(chars.length > 100 ? `${chars.slice(0, 99).join("").trimEnd()}…` : line);
|
|
442
|
+
}
|
|
396
443
|
/** Decision ids about one task on the set's board, oldest first. */
|
|
397
444
|
export async function decisionsOf({ client, network, set }, task) {
|
|
398
445
|
const events = await client.getContractEvents({
|
|
@@ -450,6 +497,11 @@ export async function verifyDecision(ctx, id, receipt) {
|
|
|
450
497
|
}
|
|
451
498
|
const text = decodeText(fetched.bytes);
|
|
452
499
|
const record = text === undefined ? undefined : parseJson(text);
|
|
500
|
+
// A proxy's error page says nothing about the record. JSON that is not one is the host's answer.
|
|
501
|
+
if (record === undefined) {
|
|
502
|
+
c.add("fetch", "error", `could not read the record: ${display(location)} sent something other than JSON, such as an error page`);
|
|
503
|
+
return report;
|
|
504
|
+
}
|
|
453
505
|
if (!isPublished(record)) {
|
|
454
506
|
c.add("fetch", "fail", `${display(location)} is not a decision record`);
|
|
455
507
|
return report;
|
|
@@ -479,7 +531,7 @@ export async function verifyDecision(ctx, id, receipt) {
|
|
|
479
531
|
}
|
|
480
532
|
c.check("kind", record.kind === kind, `kind: ${record.kind}`, `the record is a ${record.kind}; the chain recorded a ${kind}`);
|
|
481
533
|
if (decision.kind === Kind.Change) {
|
|
482
|
-
c.check("subject", record.subject.toLowerCase() === decision.subject, `subject: ${short(decision.subject)}, the
|
|
534
|
+
c.check("subject", record.subject.toLowerCase() === decision.subject, `subject: ${short(decision.subject)}, as recorded on chain. It is tied to the call Jev was shown only once the change is queued`, "the record's subject differs from the one on chain");
|
|
483
535
|
}
|
|
484
536
|
else if (outside) {
|
|
485
537
|
c.add("subject", "ok", outsideSubject(outside));
|
|
@@ -533,6 +585,9 @@ export async function verifyDecision(ctx, id, receipt) {
|
|
|
533
585
|
if (task !== undefined) {
|
|
534
586
|
await checkBrief(ctx, c, task, decision, record, state);
|
|
535
587
|
await checkTaskThreshold(ctx, c, id, task, decision, record);
|
|
588
|
+
const title = await ctx.briefs.get(task)?.then(headline, () => undefined);
|
|
589
|
+
if (title)
|
|
590
|
+
report.title = title;
|
|
536
591
|
}
|
|
537
592
|
if (outside) {
|
|
538
593
|
checkRun(c, decision, record, state, {
|
|
@@ -586,7 +641,7 @@ async function withholding(ctx, decision, record, task, outside, block) {
|
|
|
586
641
|
const bar = await gradeBar(ctx, block);
|
|
587
642
|
if (decision.confidenceBps >= bar)
|
|
588
643
|
return refuse(`this paid grade cleared the ${percent(bar)} bar, so its record is public`);
|
|
589
|
-
return { allowed: true, why: `a paid grade is published only once accepted, and ${percent(decision.confidenceBps)}
|
|
644
|
+
return { allowed: true, why: `a paid grade is published only once accepted, and this one was not: Jev answered ${named(record.answer)}, but at ${percent(decision.confidenceBps)} confidence, below the ${percent(bar)} bar` };
|
|
590
645
|
}
|
|
591
646
|
if (task === undefined || taskSubject(network.chainId, set.board, task) !== decision.subject)
|
|
592
647
|
return refuse("the record does not name the task on chain");
|
|
@@ -616,10 +671,18 @@ async function checkBrief(ctx, c, task, decision, record, state) {
|
|
|
616
671
|
brief = await pending;
|
|
617
672
|
}
|
|
618
673
|
catch (error) {
|
|
619
|
-
c.add("brief", error instanceof
|
|
674
|
+
c.add("brief", error instanceof Mismatch ? "fail" : absent(error) ? "skip" : "error", `brief: ${errorMessage(error)}`);
|
|
620
675
|
checkRun(c, decision, record, state);
|
|
621
|
-
if (decision.kind
|
|
622
|
-
|
|
676
|
+
if (decision.kind !== Kind.Grade)
|
|
677
|
+
return;
|
|
678
|
+
if (predatesPaidLevels(record))
|
|
679
|
+
return c.add("confidence-recomputed", "skip", PREDATES_PAID_LEVELS);
|
|
680
|
+
// Without the brief, the record's own pass level still ties the answer to the probabilities.
|
|
681
|
+
const own = ownPassLevel(c, record);
|
|
682
|
+
if (!own)
|
|
683
|
+
return;
|
|
684
|
+
c.add("levels", "skip", `levels: the brief could not be read, so the confidence is recomputed from the record's own ${own.levels} levels, paid from level ${own.passFrom}`);
|
|
685
|
+
checkGradeConfidence(c, record, own.paidKeys);
|
|
623
686
|
return;
|
|
624
687
|
}
|
|
625
688
|
c.check("brief", state.task?.brief === `${brief.title}\n\n${brief.brief}`, `the question quotes task ${task}'s brief, as committed on chain`, `the brief in the question is not task ${task}'s brief`);
|
|
@@ -634,10 +697,8 @@ async function checkBrief(ctx, c, task, decision, record, state) {
|
|
|
634
697
|
return;
|
|
635
698
|
const ascending = [...brief.levels].reverse();
|
|
636
699
|
c.check("levels", same(question.criteria, ascending), "the levels Jev scored against are the brief's, lowest first", "the levels in the question are not the brief's");
|
|
637
|
-
if (record
|
|
638
|
-
c.add("confidence-recomputed", "skip",
|
|
639
|
-
return;
|
|
640
|
-
}
|
|
700
|
+
if (predatesPaidLevels(record))
|
|
701
|
+
return c.add("confidence-recomputed", "skip", PREDATES_PAID_LEVELS);
|
|
641
702
|
checkGradeConfidence(c, record, ascending.map((_, i) => String(i)).slice(ascending.length - 1 - brief.passIndex));
|
|
642
703
|
}
|
|
643
704
|
/**
|
|
@@ -683,22 +744,31 @@ function checkRun(c, decision, record, state, brief) {
|
|
|
683
744
|
const { instructions } = record.request.questions.decision;
|
|
684
745
|
c.check("checks", typeof instructions === "string" && instructions.endsWith(SHOWN), `${ran}, and the question shows the graders that run`, `${ran}, but the question does not show the graders that run as BrainChain words it`);
|
|
685
746
|
}
|
|
686
|
-
|
|
687
|
-
|
|
747
|
+
const predatesPaidLevels = (record) => record.scoreConfidence === undefined && record.panel === undefined;
|
|
748
|
+
const PREDATES_PAID_LEVELS = "grade confidence: this grade predates the rule that gates on the paid levels, so its confidence is Jev's score confidence, which the probabilities alone do not give";
|
|
749
|
+
/** The question's levels and the record's own pass level, where no brief says them. Undefined once a line says why there are none to use. */
|
|
750
|
+
function ownPassLevel(c, record) {
|
|
688
751
|
const levels = record.request.questions.decision.criteria;
|
|
689
752
|
const { passFrom } = record;
|
|
690
753
|
if (!Array.isArray(levels) || passFrom === undefined) {
|
|
691
754
|
c.add("confidence-recomputed", "skip", "grade confidence: the record does not name its pass level");
|
|
692
|
-
return;
|
|
755
|
+
return undefined;
|
|
693
756
|
}
|
|
694
757
|
// The lowest level never passes, or every result would.
|
|
695
758
|
if (typeof passFrom !== "number" || !Number.isInteger(passFrom) || passFrom < 1 || passFrom >= levels.length) {
|
|
696
759
|
c.add("levels", "fail", `levels: the record's pass level ${JSON.stringify(passFrom)} is not one of levels 1 to ${levels.length - 1} of the ${levels.length} the question lists`);
|
|
697
760
|
c.add("confidence-recomputed", "skip", "grade confidence: needs a valid pass level");
|
|
698
|
-
return;
|
|
761
|
+
return undefined;
|
|
699
762
|
}
|
|
700
|
-
|
|
701
|
-
|
|
763
|
+
return { levels: levels.length, passFrom, paidKeys: levels.map((_, i) => String(i)).slice(passFrom) };
|
|
764
|
+
}
|
|
765
|
+
// No brief on chain to compare with. payloadHash commits a whole record's levels and pass level, and nothing commits a withheld record's.
|
|
766
|
+
function checkOutsideGrade(c, record, withheld) {
|
|
767
|
+
const own = ownPassLevel(c, record);
|
|
768
|
+
if (!own)
|
|
769
|
+
return;
|
|
770
|
+
c.add("levels", "skip", `levels: the record's own ${own.levels} levels, paid from level ${own.passFrom}. No brief on chain says what they should be${withheld ? ", and no hash commits them on this copy" : ""}`);
|
|
771
|
+
checkGradeConfidence(c, record, own.paidKeys);
|
|
702
772
|
}
|
|
703
773
|
function checkGradeConfidence(c, record, paidKeys) {
|
|
704
774
|
const parts = paidKeys.map((key) => record.probabilities[key] ?? 0);
|
|
@@ -1060,13 +1130,30 @@ function signerOf(receipt) {
|
|
|
1060
1130
|
signature: receipt.signature,
|
|
1061
1131
|
});
|
|
1062
1132
|
}
|
|
1133
|
+
/** A file, read no further than one byte past `limit`. A device or a pipe can go on for ever, so only a regular file is read. */
|
|
1134
|
+
async function readCapped(path, limit) {
|
|
1135
|
+
const found = await stat(path).catch((error) => {
|
|
1136
|
+
throw ["ENOENT", "ENOTDIR"].includes(error.code ?? "") ? new Refused(`No file at ${display(path)}.`) : error;
|
|
1137
|
+
});
|
|
1138
|
+
if (!found.isFile())
|
|
1139
|
+
throw new Refused(`${display(path)} is not a regular file, so it was not read`);
|
|
1140
|
+
const file = await open(path);
|
|
1141
|
+
try {
|
|
1142
|
+
const bytes = new Uint8Array(limit + 1);
|
|
1143
|
+
const { bytesRead } = await file.read(bytes, 0, bytes.length, 0);
|
|
1144
|
+
return bytes.subarray(0, bytesRead);
|
|
1145
|
+
}
|
|
1146
|
+
finally {
|
|
1147
|
+
await file.close();
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1063
1150
|
/** Reads a receipt from a file or an http(s) URL: the receipt itself, or a reply that carries it as `receipt`. */
|
|
1064
1151
|
export async function readReceipt(client, source) {
|
|
1065
1152
|
const bytes = /^https?:\/\//i.test(source)
|
|
1066
1153
|
? (await fetchBytes(source, { what: "receipt", limit: MAX_RECEIPT_BYTES, allowPrivate: await allowsPrivate(client) })).bytes
|
|
1067
|
-
: await
|
|
1154
|
+
: await readCapped(source, MAX_RECEIPT_BYTES);
|
|
1068
1155
|
if (bytes.length > MAX_RECEIPT_BYTES)
|
|
1069
|
-
throw new
|
|
1156
|
+
throw new TooLarge(`${display(source)} is larger than the ${MAX_RECEIPT_BYTES / 1024} KB a receipt may be, so it was not read`);
|
|
1070
1157
|
const text = decodeText(bytes);
|
|
1071
1158
|
const value = text === undefined ? undefined : parseJson(text);
|
|
1072
1159
|
if (value === undefined)
|
|
@@ -1074,6 +1161,8 @@ export async function readReceipt(client, source) {
|
|
|
1074
1161
|
const carried = value?.receipt;
|
|
1075
1162
|
return { from: clean(source), value: typeof carried === "object" && carried !== null ? carried : value };
|
|
1076
1163
|
}
|
|
1164
|
+
/** Whether a value is a receipt as BrainChain or the x402 extension signs one. */
|
|
1165
|
+
export const isReceipt = (value) => parseReceipt(value) !== undefined;
|
|
1077
1166
|
/** The decision and log a BrainChain receipt names. The x402 extension's receipt names neither. */
|
|
1078
1167
|
export function receiptDecision(value) {
|
|
1079
1168
|
const receipt = parseReceipt(value);
|
|
@@ -1100,7 +1189,7 @@ async function servedReceipt(ctx, c, d) {
|
|
|
1100
1189
|
const why = error instanceof NotFound
|
|
1101
1190
|
? `${display(url)} has none. A task's receipt is signed once the board pays or refunds it, for the grade or ruling it settled on`
|
|
1102
1191
|
: `could not fetch one: ${errorMessage(error)}`;
|
|
1103
|
-
c.add("receipt", "skip", `receipt: ${why}`);
|
|
1192
|
+
c.add("receipt", absent(error) ? "skip" : "error", `receipt: ${why}`);
|
|
1104
1193
|
return undefined;
|
|
1105
1194
|
}
|
|
1106
1195
|
}
|
|
@@ -1204,14 +1293,17 @@ async function checkPayment(ctx, c, d, claimed, fields) {
|
|
|
1204
1293
|
const origin = hostOf(d.payloadURI);
|
|
1205
1294
|
if (!origin)
|
|
1206
1295
|
return c.add("receipt-payment", "skip", `payment: the receipt's payment is the record's. The record is not served by a host, so no network.json names the desk to check ${tx} against`);
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1296
|
+
const [deskRead, movedRead] = await Promise.allSettled([deskOf(ctx, origin), (ctx.balances ?? balancesOnChain)(network, transaction, asset)]);
|
|
1297
|
+
if (deskRead.status === "rejected" || movedRead.status === "rejected") {
|
|
1298
|
+
// A manifest the chain contradicts fails whatever else could not be read, and a host that did not answer outweighs one that has nothing.
|
|
1299
|
+
const reasons = [deskRead, movedRead].flatMap((read) => (read.status === "rejected" ? [read.reason] : []));
|
|
1300
|
+
const reason = reasons.find((r) => r instanceof Mismatch) ?? reasons.find((r) => !absent(r)) ?? reasons[0];
|
|
1301
|
+
if (reason instanceof Mismatch)
|
|
1302
|
+
return c.add("receipt-payment", "fail", `payment: the receipt's payment is the record's, but ${errorMessage(reason)}`);
|
|
1303
|
+
return c.add("receipt-payment", absent(reason) ? "skip" : "error", `payment: the receipt's payment is the record's, and ${tx} was not checked: ${errorMessage(reason)}`);
|
|
1304
|
+
}
|
|
1305
|
+
const desk = deskRead.value;
|
|
1306
|
+
const moved = movedRead.value;
|
|
1215
1307
|
if (!moved)
|
|
1216
1308
|
return c.add("receipt-payment", "fail", `payment: ${tx} did not succeed, or is not on that network`);
|
|
1217
1309
|
const evm = network.startsWith("eip155:");
|
|
@@ -1251,16 +1343,24 @@ async function readDesk({ client, network, set }, origin) {
|
|
|
1251
1343
|
client.readContract({ address: log, abi: decisionLogAbi, functionName: "brain" }),
|
|
1252
1344
|
]);
|
|
1253
1345
|
if (!eq(signer, brain))
|
|
1254
|
-
throw new
|
|
1346
|
+
throw new Mismatch(`${display(uri)} is signed by ${short(signer)}, not by ${short(brain)}, the brain on DecisionLog ${short(log)}`);
|
|
1255
1347
|
const manifest = parseJson(signed.slice(MANIFEST_PREFIX.length));
|
|
1256
1348
|
const payees = manifest?.payees;
|
|
1257
1349
|
const valid = Array.isArray(payees) && payees.every((p) => typeof p === "object" && p !== null && ["network", "asset", "payTo"].every((k) => typeof p[k] === "string"));
|
|
1258
1350
|
if (manifest?.chainId !== network.chainId || !valid)
|
|
1259
|
-
throw new
|
|
1351
|
+
throw new Mismatch(`${display(uri)} does not list the payees of chain ${network.chainId}`);
|
|
1260
1352
|
const former = Array.isArray(manifest.formerDesks) ? manifest.formerDesks.filter((d) => typeof d === "string") : [];
|
|
1261
1353
|
return { payees: payees, formerDesks: former };
|
|
1262
1354
|
}
|
|
1263
1355
|
const ROBINHOOD_RPC = "https://rpc.mainnet.chain.robinhood.com";
|
|
1356
|
+
const CHAINS = {
|
|
1357
|
+
"eip155:8453": "Base",
|
|
1358
|
+
"eip155:84532": "Base Sepolia",
|
|
1359
|
+
"eip155:4663": "Robinhood Chain",
|
|
1360
|
+
"eip155:46630": "Robinhood Chain testnet",
|
|
1361
|
+
"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": "Solana",
|
|
1362
|
+
"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1": "Solana devnet",
|
|
1363
|
+
};
|
|
1264
1364
|
// Public RPCs for the networks the desk takes payment on.
|
|
1265
1365
|
const PAYMENT_RPCS = {
|
|
1266
1366
|
"eip155:8453": "https://mainnet.base.org",
|
|
@@ -1271,50 +1371,62 @@ const PAYMENT_RPCS = {
|
|
|
1271
1371
|
"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1": "https://api.devnet.solana.com",
|
|
1272
1372
|
};
|
|
1273
1373
|
const TRANSFER = parseAbi(["event Transfer(address indexed from, address indexed to, uint256 value)"]);
|
|
1274
|
-
const
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
const receipt = await client.getTransactionReceipt({ hash: transaction }).catch((error) => {
|
|
1287
|
-
if (error instanceof TransactionReceiptNotFoundError)
|
|
1374
|
+
const UNSEEN = "the RPC does not find it yet: a node that lags, or a Solana transaction not yet finalized, can miss one";
|
|
1375
|
+
/** Reads payment transactions from the RPC given for each CAIP-2 network, such as eip155:8453. */
|
|
1376
|
+
export function balancesFrom(rpcs) {
|
|
1377
|
+
const clients = new Map();
|
|
1378
|
+
return async (network, transaction, asset) => {
|
|
1379
|
+
const rpc = Object.hasOwn(rpcs, network) ? rpcs[network] : undefined;
|
|
1380
|
+
if (!rpc)
|
|
1381
|
+
throw new Refused(`the tool has no RPC for ${clean(network)}`);
|
|
1382
|
+
const name = Object.hasOwn(CHAINS, network) ? CHAINS[network] : clean(network);
|
|
1383
|
+
if (network.startsWith("solana:"))
|
|
1384
|
+
return solanaBalances(name, rpc, transaction, asset);
|
|
1385
|
+
if (!BYTES32.test(transaction))
|
|
1288
1386
|
return undefined;
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
add(
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1387
|
+
let client = clients.get(network);
|
|
1388
|
+
if (!client)
|
|
1389
|
+
clients.set(network, (client = createPublicClient({ transport: rpcTransport(name, rpc) })));
|
|
1390
|
+
const receipt = await client.getTransactionReceipt({ hash: transaction }).catch((error) => {
|
|
1391
|
+
throw error instanceof TransactionReceiptNotFoundError ? new Error(UNSEEN) : error;
|
|
1392
|
+
});
|
|
1393
|
+
if (receipt.status !== "success")
|
|
1394
|
+
return undefined;
|
|
1395
|
+
const changes = new Map();
|
|
1396
|
+
const add = (owner, value) => changes.set(owner.toLowerCase(), (changes.get(owner.toLowerCase()) ?? 0n) + value);
|
|
1397
|
+
for (const { address, args } of parseEventLogs({ abi: TRANSFER, logs: receipt.logs, eventName: "Transfer", strict: true })) {
|
|
1398
|
+
if (!eq(address, asset))
|
|
1399
|
+
continue;
|
|
1400
|
+
add(args.from, -args.value);
|
|
1401
|
+
add(args.to, args.value);
|
|
1402
|
+
}
|
|
1403
|
+
return changes;
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
const balancesOnChain = balancesFrom(PAYMENT_RPCS);
|
|
1303
1407
|
/** A Solana transaction's change to each owner's balance of the mint, from its token balances before and after. */
|
|
1304
|
-
async function solanaBalances(rpc, signature, mint) {
|
|
1305
|
-
const
|
|
1408
|
+
async function solanaBalances(name, rpc, signature, mint) {
|
|
1409
|
+
const label = rpcLabel(name, rpc);
|
|
1410
|
+
const { result, error } = await fetch(rpc, {
|
|
1306
1411
|
method: "POST",
|
|
1307
1412
|
headers: { "content-type": "application/json", "user-agent": "brainchain-verify" },
|
|
1308
1413
|
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "getTransaction", params: [signature, { encoding: "jsonParsed", commitment: "finalized", maxSupportedTransactionVersion: 0 }] }),
|
|
1309
|
-
signal: AbortSignal.timeout(
|
|
1414
|
+
signal: AbortSignal.timeout(RPC_TIMEOUT_MS),
|
|
1415
|
+
})
|
|
1416
|
+
.then(async (response) => {
|
|
1417
|
+
if (!response.ok)
|
|
1418
|
+
throw new Error(`answered with status ${response.status}`);
|
|
1419
|
+
return (await response.json());
|
|
1420
|
+
})
|
|
1421
|
+
.catch((reason) => {
|
|
1422
|
+
throw fromRpc(reason, label);
|
|
1310
1423
|
});
|
|
1311
|
-
if (!response.ok)
|
|
1312
|
-
throw new Error(`${rpc} answered with status ${response.status}`);
|
|
1313
|
-
const { result, error } = (await response.json());
|
|
1314
1424
|
if (error)
|
|
1315
|
-
throw new Error(
|
|
1425
|
+
throw fromRpc(new Error(clean(String(error.message))), label);
|
|
1316
1426
|
const meta = result?.meta;
|
|
1317
|
-
if (!meta
|
|
1427
|
+
if (!meta)
|
|
1428
|
+
throw new Error(UNSEEN);
|
|
1429
|
+
if (meta.err !== null)
|
|
1318
1430
|
return undefined;
|
|
1319
1431
|
const changes = new Map();
|
|
1320
1432
|
for (const [sign, balances] of [[-1n, meta.preTokenBalances], [1n, meta.postTokenBalances]]) {
|
|
@@ -1379,6 +1491,22 @@ const LOG_SPAN = 10000000n;
|
|
|
1379
1491
|
const PADDED = /^0x0{24}([0-9a-f]{40})$/i;
|
|
1380
1492
|
const NO_RECEIPT = "no receipt: the entry's feedbackHash is zero. Only a task an agent paid BrainChain for has a signed receipt; house tasks, tasks posted straight on the board, ACP orders and older entries have none";
|
|
1381
1493
|
export const entryName = (registry, f) => `${f.agentId}:${eq(f.clientAddress, registry.writers[0] ?? "") ? "" : `${f.clientAddress}:`}${f.feedbackIndex}`;
|
|
1494
|
+
/** An entry as its NewFeedback event states it, with `checks` as its own. */
|
|
1495
|
+
export function entryReport(registry, f, checks) {
|
|
1496
|
+
return {
|
|
1497
|
+
entry: entryName(registry, f),
|
|
1498
|
+
agentId: f.agentId.toString(),
|
|
1499
|
+
clientAddress: f.clientAddress,
|
|
1500
|
+
feedbackIndex: Number(f.feedbackIndex),
|
|
1501
|
+
value: Number(f.value),
|
|
1502
|
+
block: Number(f.block),
|
|
1503
|
+
transaction: f.transaction,
|
|
1504
|
+
endpoint: clean(f.endpoint),
|
|
1505
|
+
feedbackURI: clean(f.feedbackURI),
|
|
1506
|
+
feedbackHash: f.feedbackHash,
|
|
1507
|
+
checks,
|
|
1508
|
+
};
|
|
1509
|
+
}
|
|
1382
1510
|
/** Every entry BrainChain wrote for an agent, from the writers given or all of its own, oldest first. */
|
|
1383
1511
|
export async function entriesOf(registry, agentId, writers = registry.writers) {
|
|
1384
1512
|
const { client, address } = registry;
|
|
@@ -1404,19 +1532,7 @@ export async function entriesOf(registry, agentId, writers = registry.writers) {
|
|
|
1404
1532
|
*/
|
|
1405
1533
|
export async function verifyEntry(ctx, registry, f) {
|
|
1406
1534
|
const c = new Checks();
|
|
1407
|
-
const report =
|
|
1408
|
-
entry: entryName(registry, f),
|
|
1409
|
-
agentId: f.agentId.toString(),
|
|
1410
|
-
clientAddress: f.clientAddress,
|
|
1411
|
-
feedbackIndex: Number(f.feedbackIndex),
|
|
1412
|
-
value: Number(f.value),
|
|
1413
|
-
block: Number(f.block),
|
|
1414
|
-
transaction: f.transaction,
|
|
1415
|
-
endpoint: clean(f.endpoint),
|
|
1416
|
-
feedbackURI: clean(f.feedbackURI),
|
|
1417
|
-
feedbackHash: f.feedbackHash,
|
|
1418
|
-
checks: c.list,
|
|
1419
|
-
};
|
|
1535
|
+
const report = entryReport(registry, f, c.list);
|
|
1420
1536
|
await checkStored(registry, c, f);
|
|
1421
1537
|
const page = taskPage(ctx.network.sets, f.endpoint);
|
|
1422
1538
|
if (page)
|
|
@@ -1640,3 +1756,15 @@ export function entryOutcome(reports) {
|
|
|
1640
1756
|
const outcome = outcomeOf(reports);
|
|
1641
1757
|
return outcome === "match" && reports.every((r) => eq(r.feedbackHash, NO)) ? "no-receipt" : outcome;
|
|
1642
1758
|
}
|
|
1759
|
+
export function entrySummary(reports) {
|
|
1760
|
+
const outcomes = reports.map((r) => entryOutcome([r]));
|
|
1761
|
+
const count = (outcome) => outcomes.filter((o) => o === outcome).length;
|
|
1762
|
+
return {
|
|
1763
|
+
entries: reports.length,
|
|
1764
|
+
withReceipt: reports.filter((r) => !eq(r.feedbackHash, NO)).length,
|
|
1765
|
+
verified: count("match"),
|
|
1766
|
+
withheld: count("withheld"),
|
|
1767
|
+
failed: count("mismatch"),
|
|
1768
|
+
unverified: count("unverified"),
|
|
1769
|
+
};
|
|
1770
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "brainchain-verify",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"description": "Check a BrainChain decision against the chain: the published record, its hashes, its confidence and the thresholds the contracts applied.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "BrainChain",
|