brainchain-verify 0.6.0 → 0.7.0
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 +70 -1
- package/dist/cli.js +167 -9
- package/dist/verify.d.ts +87 -1
- package/dist/verify.js +292 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,11 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
Check any BrainChain decision against the chain. The tool reads the decision from the `DecisionLog`, fetches the record Jev's answer was published in, 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
4
|
|
|
5
|
+
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
|
+
|
|
5
7
|
```sh
|
|
6
8
|
npx brainchain-verify mainnet 1
|
|
7
9
|
npx brainchain-verify mainnet --task 11 --set v3-1
|
|
8
10
|
npx brainchain-verify testnet 100 --json
|
|
9
11
|
npx brainchain-verify mainnet --receipt receipt.json
|
|
12
|
+
npx brainchain-verify mainnet --entry 20424:7
|
|
13
|
+
npx brainchain-verify mainnet --agent 20424
|
|
10
14
|
```
|
|
11
15
|
|
|
12
16
|
Requires Node.js 22 or later.
|
|
@@ -17,6 +21,8 @@ Requires Node.js 22 or later.
|
|
|
17
21
|
brainchain-verify <mainnet|testnet|chainId> <decisionId> [--set <TaskBoard>] [--rpc <url>] [--offline] [--json]
|
|
18
22
|
brainchain-verify <mainnet|testnet|chainId> --task <taskId> [--set <TaskBoard>] [--rpc <url>] [--offline] [--json]
|
|
19
23
|
brainchain-verify <mainnet|testnet|chainId> [<decisionId>] --receipt <file|url> [--set <TaskBoard>] [--rpc <url>] [--json]
|
|
24
|
+
brainchain-verify mainnet --entry <agentId>:[<writer>:]<feedbackIndex> [--rpc <url>] [--registry-rpc <url>] [--json]
|
|
25
|
+
brainchain-verify mainnet --agent <agentId> [--rpc <url>] [--registry-rpc <url>] [--json]
|
|
20
26
|
```
|
|
21
27
|
|
|
22
28
|
| Argument | Meaning |
|
|
@@ -27,6 +33,9 @@ brainchain-verify <mainnet|testnet|chainId> [<decisionId>] --receipt <file|url>
|
|
|
27
33
|
| `--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. |
|
|
28
34
|
| `--rpc <url>` | Another RPC for the same chain. Records and briefs on private addresses are read only when this RPC is on one too. |
|
|
29
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). |
|
|
36
|
+
| `--entry <agentId>:[<writer>:]<index>` | Check one reputation entry BrainChain wrote. See [reputation entries](#reputation-entries). |
|
|
37
|
+
| `--agent <agentId>` | Check every reputation entry BrainChain wrote for one agent, oldest first. |
|
|
38
|
+
| `--registry-rpc <url>` | Another RPC for Robinhood Chain, where the ERC-8004 registries are. |
|
|
30
39
|
| `--offline` | Fetch no receipt from the brain host. A receipt given with `--receipt` is still checked. |
|
|
31
40
|
| `--json` | One JSON object on stdout. |
|
|
32
41
|
| `--version` | Print the version. |
|
|
@@ -167,6 +176,64 @@ Its answer and confidence are checked, and the confidence is recomputed from the
|
|
|
167
176
|
|
|
168
177
|
A paid grade runs the checks sent with its request. BrainChain appends them to the brief as its last block, and `checks` holds their run to the same rule as a task's. A caller can also write such a block into the brief's own text, where nothing runs it, and the record reads the same either way. So a brief that ends in a checks block with no run is a `skip`. An ACP evaluation runs no checks.
|
|
169
178
|
|
|
179
|
+
## Reputation entries
|
|
180
|
+
|
|
181
|
+
Each task that settles for a registered worker becomes one entry in the ERC-8004 reputation registry on Robinhood Chain (`0x8004BAa17C55a88189AE136b182e5fdA19dE9b63`). The value is 100 when the board paid the bounty and 0 when it refunded it, under the tags `brainchain` and `task`, and the endpoint is the task's page. An entry for a task an agent paid BrainChain for points at the task's signed [receipt](#receipts): `feedbackURI` is where the receipt is served, and `feedbackHash` is the `keccak256` of the receipt as served there. Every other entry names the task page again and carries a zero hash. That covers house tasks, tasks posted straight on the board, ACP orders and entries written before receipts.
|
|
182
|
+
|
|
183
|
+
```sh
|
|
184
|
+
npx brainchain-verify mainnet --entry 20424:7
|
|
185
|
+
npx brainchain-verify mainnet --entry 20424:0xafB0C4Ef895D4895040cdC6435B96D3EE8350c6E:12
|
|
186
|
+
npx brainchain-verify mainnet --agent 20424 --json
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
The registry names an entry by its agent id, the address that wrote it and its index, which counts from 1 for each agent and writer. `--entry` takes the three in that order, separated by colons. BrainChain writes from `0x97D558417c3D61f1074422AD843e1Db1E565b952`, and wrote from `0xafB0C4Ef895D4895040cdC6435B96D3EE8350c6E` before 10 November 2026. Leave the writer out for an entry from the first. Anyone can write under the same tags, so the tool reads entries from these two addresses only.
|
|
190
|
+
|
|
191
|
+
On an entry, the tool checks, in order:
|
|
192
|
+
|
|
193
|
+
| Check | What passes |
|
|
194
|
+
| --- | --- |
|
|
195
|
+
| `entry` | The entry's `NewFeedback` event and the registry's `readFeedback` agree. The tags are `brainchain` and `task`, and the value is 100 or 0 with no decimals. |
|
|
196
|
+
| `endpoint` | The endpoint is a task page naming the task and its board, and the board is in one of the contract sets the tool carries. Entries written before 5 November name the task alone. Task ids restart with each board, so `endpoint` skips on them and the task's checks do not run. |
|
|
197
|
+
| `feedback-hash` | The `keccak256` of the bytes served at `feedbackURI` equals `feedbackHash`. A zero hash is a `skip` that reads `no receipt`. |
|
|
198
|
+
| `entry-receipt` | The receipt is one BrainChain signs. It names a decision its DecisionLog holds, in one of the contract sets the tool carries, and `feedbackURI` is that decision's receipt address. |
|
|
199
|
+
| the decision's checks | The decision the receipt names, checked as any decision is, with this receipt. That covers its record, its evidence hash, and the receipt's signature, outcome and payment. The lines keep their names. |
|
|
200
|
+
| `entry-task` | The decision's subject is `subjectOf(task)` on the board the endpoint names. |
|
|
201
|
+
| `entry-value` | The board paid the task for 100 and refunded it for 0. With a receipt, its outcome is `accepted` for 100 and `rejected` for 0. |
|
|
202
|
+
| `entry-worker` | The board's `WorkerHired` event for the task names the agent. A house worker is hired by the `keccak256` of its model name, so agent 20424 is `keccak256("claude")`. The tool carries the five house agents, 20424 to 20428, as [Worker models](https://docs.usebrainchain.com/workers#erc-8004-identity) lists them. An outside worker is hired by its address, left-padded to 32 bytes. That address must have owned the agent, or been its registered wallet, on the identity registry (`0x8004A169FB4a3325136EB29fA0ceB6D2e539a432`) when the board hired it. |
|
|
203
|
+
|
|
204
|
+
The public RPC for Robinhood Chain keeps no past state, so the tool replays the agent's transfers and wallet changes on the identity registry up to the hire's block time. A transfer clears the wallet, as the registry does.
|
|
205
|
+
|
|
206
|
+
```text
|
|
207
|
+
$ npx brainchain-verify mainnet --entry 20424:7
|
|
208
|
+
Entry 20424:7 in the ERC-8004 reputation registry on Robinhood Chain (0x8004BAa17C55a88189AE136b182e5fdA19dE9b63)
|
|
209
|
+
|
|
210
|
+
ok entry: value 100 for agent 20424 under brainchain and task, written by 0x97D5…b952 in block 114772689, as the registry holds it
|
|
211
|
+
ok endpoint: task 49 on board 0x44b8…A211, contract set v3-5
|
|
212
|
+
skip 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
|
|
213
|
+
ok value: 100, as the board paid task 49
|
|
214
|
+
ok worker: the board hired claude for task 49 as keccak256("claude"), and agent 20424 is the house worker claude
|
|
215
|
+
|
|
216
|
+
Verdict: no receipt. No signed receipt backs this entry, and the checks the chain allows without one passed.
|
|
217
|
+
Not checked: that Jev produced the answer. See https://docs.usebrainchain.com/trust-model
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
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
|
+
|
|
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 checked out, and those that failed. `--entry` with a name from the list shows every check.
|
|
223
|
+
|
|
224
|
+
```text
|
|
225
|
+
$ npx brainchain-verify mainnet --agent 20425
|
|
226
|
+
Agent 20425 in the ERC-8004 reputation registry on Robinhood Chain (0x8004BAa17C55a88189AE136b182e5fdA19dE9b63): 8 entries BrainChain wrote
|
|
227
|
+
|
|
228
|
+
no receipt 20425:0xafB0C4Ef895D4895040cdC6435B96D3EE8350c6E:1 value 100, task 1
|
|
229
|
+
no receipt 20425:0xafB0C4Ef895D4895040cdC6435B96D3EE8350c6E:4 value 100, task 22 in set v3-5
|
|
230
|
+
no receipt 20425:2 value 100, task 41 in set v3-5
|
|
231
|
+
|
|
232
|
+
8 entries, 0 with a receipt, 0 verified, 0 failed.
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
Trimmed to three entries.
|
|
236
|
+
|
|
170
237
|
## What it cannot check
|
|
171
238
|
|
|
172
239
|
That Jev produced the answer. BrainChain records Jev's answers, and the contracts bound what a recorded answer can do. A decision that passes every check has the question, answer and probabilities the chain acted on. The [trust model](https://docs.usebrainchain.com/trust-model) explains what the chain relies on and what bounds it.
|
|
@@ -176,7 +243,7 @@ That Jev produced the answer. BrainChain records Jev's answers, and the contract
|
|
|
176
243
|
| Code | Meaning |
|
|
177
244
|
| --- | --- |
|
|
178
245
|
| 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. |
|
|
179
|
-
| 1 | A check failed, a record could not be fetched, or the decision could not be read: an unknown id, a task with no decisions, an RPC error, a `--receipt` that cannot be read. |
|
|
246
|
+
| 1 | A check failed, a record or receipt could not be fetched, 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. |
|
|
180
247
|
| 2 | Bad arguments, or an RPC that serves another chain. |
|
|
181
248
|
|
|
182
249
|
## JSON
|
|
@@ -219,6 +286,8 @@ That Jev produced the answer. BrainChain records Jev's answers, and the contract
|
|
|
219
286
|
}
|
|
220
287
|
```
|
|
221
288
|
|
|
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`.
|
|
290
|
+
|
|
222
291
|
## Building
|
|
223
292
|
|
|
224
293
|
```sh
|
package/dist/cli.js
CHANGED
|
@@ -3,11 +3,13 @@ import { createRequire } from "node:module";
|
|
|
3
3
|
import { createPublicClient, http, isAddress } from "viem";
|
|
4
4
|
import { decisionLogAbi, taskBoardAbi } from "./abi.js";
|
|
5
5
|
import { NETWORKS } from "./deployments.js";
|
|
6
|
-
import { clean, decisionsOf, errorMessage, outcomeOf, readReceipt, receiptDecision, verifyDecision, withheldNotChecked, } from "./verify.js";
|
|
6
|
+
import { clean, decisionsOf, entriesOf, entryName, entryOutcome, errorMessage, outcomeOf, readReceipt, receiptDecision, REPUTATION, 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]
|
|
10
10
|
brainchain-verify <mainnet|testnet|chainId> [<decisionId>] --receipt <file|url> [--set <TaskBoard>] [--rpc <url>] [--json]
|
|
11
|
+
brainchain-verify mainnet --entry <agentId>:[<writer>:]<feedbackIndex> [--rpc <url>] [--registry-rpc <url>] [--json]
|
|
12
|
+
brainchain-verify mainnet --agent <agentId> [--rpc <url>] [--registry-rpc <url>] [--json]
|
|
11
13
|
|
|
12
14
|
Checks a BrainChain decision against the chain: reads it from the DecisionLog,
|
|
13
15
|
fetches the published record, recomputes its hashes and confidence, and applies
|
|
@@ -16,18 +18,26 @@ the task's thresholds as the contracts do. Needs no keys.
|
|
|
16
18
|
--task <id> check every decision about one task
|
|
17
19
|
--receipt <r> check the receipt for a paid job, from a file or a URL, against
|
|
18
20
|
the decision it names, or the one given
|
|
21
|
+
--entry <e> check one ERC-8004 reputation entry BrainChain wrote: the entry,
|
|
22
|
+
its receipt, the decision and payment the receipt names, and the
|
|
23
|
+
task, value and worker on the board. The writer is needed only
|
|
24
|
+
for an entry from an address BrainChain no longer writes from
|
|
25
|
+
--agent <id> check every entry BrainChain wrote for one agent
|
|
19
26
|
--offline fetch no receipt from the brain host
|
|
20
27
|
--set <board> a retired contract set from 3.0.0 on, by TaskBoard address, by
|
|
21
28
|
its key on the site (v3-1) or by release (3.1.0); without it, the
|
|
22
29
|
active set
|
|
23
30
|
--rpc <url> another RPC for the same chain; records and briefs on private
|
|
24
31
|
addresses are read only when this is on one too
|
|
32
|
+
--registry-rpc <url>
|
|
33
|
+
another RPC for Robinhood Chain, where the registries are
|
|
25
34
|
--json one JSON object on stdout
|
|
26
35
|
--version print the version
|
|
27
36
|
|
|
28
37
|
Exit status: 0 when every check that could run matches, 1 on a mismatch or when
|
|
29
38
|
a decision or its record cannot be read, 2 on bad arguments.`;
|
|
30
39
|
const TRUST_MODEL = "https://docs.usebrainchain.com/trust-model";
|
|
40
|
+
const NOT_CHECKED = "That Jev produced the answer. BrainChain records Jev's answers, and the contracts bound what a recorded answer can do.";
|
|
31
41
|
// Sets before 3.0.0 named tasks by id alone, which the subject check does not model, so the package carries none.
|
|
32
42
|
const BEFORE_3 = /^(v2(-|$)|2\.|0x83b31d99fa31a9e5257955a737ef34c40f1c57bf$)/i;
|
|
33
43
|
function usage(message) {
|
|
@@ -67,12 +77,18 @@ const taskArg = flag("--task");
|
|
|
67
77
|
const setArg = flag("--set");
|
|
68
78
|
const rpcArg = flag("--rpc");
|
|
69
79
|
const receiptArg = flag("--receipt");
|
|
80
|
+
const entryArg = flag("--entry");
|
|
81
|
+
const agentArg = flag("--agent");
|
|
82
|
+
const registryRpcArg = flag("--registry-rpc");
|
|
70
83
|
// -1 is a bad id, not an option; the id check below says so.
|
|
71
84
|
const unknown = args.find((arg) => arg.startsWith("-") && !/^-\d/.test(arg));
|
|
72
85
|
if (unknown)
|
|
73
86
|
usage(`Unknown option ${unknown}`);
|
|
74
|
-
|
|
87
|
+
const web = (url) => URL.canParse(url) && ["http:", "https:"].includes(new URL(url).protocol);
|
|
88
|
+
if (rpcArg !== undefined && !web(rpcArg))
|
|
75
89
|
usage("--rpc needs an http or https URL");
|
|
90
|
+
if (registryRpcArg !== undefined && !web(registryRpcArg))
|
|
91
|
+
usage("--registry-rpc needs an http or https URL");
|
|
76
92
|
const [networkArg, idArg, ...extra] = args;
|
|
77
93
|
if (networkArg === undefined)
|
|
78
94
|
usage("Name a network: mainnet, testnet or a chain id");
|
|
@@ -80,8 +96,16 @@ if (extra.length > 0 || (taskArg !== undefined && idArg !== undefined))
|
|
|
80
96
|
usage("Too many arguments");
|
|
81
97
|
if (taskArg !== undefined && receiptArg !== undefined)
|
|
82
98
|
usage("A receipt is for one decision: name it, not a task");
|
|
83
|
-
|
|
84
|
-
|
|
99
|
+
const reputation = entryArg !== undefined || agentArg !== undefined;
|
|
100
|
+
if (reputation && (idArg !== undefined || taskArg !== undefined || receiptArg !== undefined || setArg !== undefined || offline)) {
|
|
101
|
+
usage("An entry names its own task, decision and receipt, so --entry and --agent take only --rpc, --registry-rpc and --json");
|
|
102
|
+
}
|
|
103
|
+
if (!reputation && registryRpcArg !== undefined)
|
|
104
|
+
usage("--registry-rpc is for --entry and --agent");
|
|
105
|
+
if (entryArg !== undefined && agentArg !== undefined)
|
|
106
|
+
usage("Name one entry with --entry, or an agent with --agent");
|
|
107
|
+
if (!reputation && taskArg === undefined && idArg === undefined && receiptArg === undefined)
|
|
108
|
+
usage("Name a decision id, a task with --task, or an entry with --entry");
|
|
85
109
|
const given = taskArg ?? idArg;
|
|
86
110
|
if (given !== undefined && !/^[1-9]\d*$/.test(given))
|
|
87
111
|
usage(`${taskArg === undefined ? "A decision" : "A task"} id is a whole number from 1`);
|
|
@@ -92,6 +116,11 @@ if (!foundNetwork)
|
|
|
92
116
|
usage(`Unknown network "${networkArg}": use mainnet, testnet, 274663 or 274630`);
|
|
93
117
|
const network = foundNetwork;
|
|
94
118
|
const client = createPublicClient({ transport: http(rpcArg ?? network.rpc) });
|
|
119
|
+
const TAGS = { ok: "ok", fail: "FAIL", skip: "skip", error: "ERROR" };
|
|
120
|
+
const tally = (checks, status) => checks.filter((c) => c.status === status).length;
|
|
121
|
+
const ENTRY_TAGS = { match: "match", "no-receipt": "no receipt", withheld: "withheld", mismatch: "MISMATCH", unverified: "UNVERIFIED" };
|
|
122
|
+
if (reputation)
|
|
123
|
+
await checkEntries();
|
|
95
124
|
const receipt = receiptArg === undefined ? undefined : await readReceipt(client, receiptArg).catch((error) => fail(errorMessage(error)));
|
|
96
125
|
const named = receipt && receiptDecision(receipt.value);
|
|
97
126
|
const target = given ?? named?.decision;
|
|
@@ -117,8 +146,6 @@ function fail(message, status = 1) {
|
|
|
117
146
|
console.error(clean(message));
|
|
118
147
|
process.exit(status);
|
|
119
148
|
}
|
|
120
|
-
const TAGS = { ok: "ok", fail: "FAIL", skip: "skip", error: "ERROR" };
|
|
121
|
-
const tally = (checks, status) => checks.filter((c) => c.status === status).length;
|
|
122
149
|
function verdict(reports) {
|
|
123
150
|
const all = reports.flatMap((r) => r.checks);
|
|
124
151
|
const failed = tally(all, "fail");
|
|
@@ -173,7 +200,7 @@ function report(reports, header, task) {
|
|
|
173
200
|
skipped,
|
|
174
201
|
decisions,
|
|
175
202
|
...(overall === "withheld" ? { withheldNotChecked: withheldNotChecked(reports) } : {}),
|
|
176
|
-
notChecked:
|
|
203
|
+
notChecked: NOT_CHECKED,
|
|
177
204
|
trustModel: TRUST_MODEL,
|
|
178
205
|
};
|
|
179
206
|
console.log(JSON.stringify(out, null, 2));
|
|
@@ -189,10 +216,141 @@ function report(reports, header, task) {
|
|
|
189
216
|
console.log(`Not checked: that Jev produced the answer. See ${TRUST_MODEL}`);
|
|
190
217
|
process.exit(failed + errors > 0 ? 1 : 0);
|
|
191
218
|
}
|
|
192
|
-
|
|
193
|
-
const chainId = await
|
|
219
|
+
async function sameChain(registry) {
|
|
220
|
+
const chainId = await client.getChainId();
|
|
194
221
|
if (chainId !== network.chainId)
|
|
195
222
|
usage(`The RPC serves chain ${chainId}, not ${network.name} (${network.chainId})`);
|
|
223
|
+
const registryChain = await registry?.client.getChainId();
|
|
224
|
+
if (registry && registryChain !== registry.chainId)
|
|
225
|
+
usage(`The registry RPC serves chain ${registryChain}, not Robinhood Chain (${registry.chainId})`);
|
|
226
|
+
}
|
|
227
|
+
function entryVerdict(r) {
|
|
228
|
+
const failed = tally(r.checks, "fail");
|
|
229
|
+
switch (entryOutcome([r])) {
|
|
230
|
+
case "mismatch":
|
|
231
|
+
return `Verdict: MISMATCH. ${failed} check${failed === 1 ? "" : "s"} failed; see the FAIL lines.`;
|
|
232
|
+
case "unverified":
|
|
233
|
+
return "Verdict: UNVERIFIED. The receipt or the record behind it could not be fetched, so the checks that need it did not run; see the ERROR lines.";
|
|
234
|
+
case "withheld":
|
|
235
|
+
return `Verdict: withheld, not a full match. ${withheldNotChecked([r.decision])}`;
|
|
236
|
+
case "no-receipt":
|
|
237
|
+
return "Verdict: no receipt. No signed receipt backs this entry, and the checks the chain allows without one passed.";
|
|
238
|
+
case "match":
|
|
239
|
+
if (tally(r.checks, "skip") > 0)
|
|
240
|
+
return "Verdict: match. Every check that could run passed; the skip lines say what could not be checked.";
|
|
241
|
+
return "Verdict: match. The entry, its receipt, the decision and payment the receipt names, and the task on the board agree with the chain.";
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
/** What an entry is about, on its line in an agent's list. */
|
|
245
|
+
function about(r) {
|
|
246
|
+
const task = r.task === undefined ? `endpoint ${r.endpoint}` : `task ${r.task}${r.set ? ` in set ${r.set}` : r.board ? ` on board ${r.board}` : ""}`;
|
|
247
|
+
return `value ${r.value}, ${task}${r.decision ? `, decision ${r.decision.id}` : ""}`;
|
|
248
|
+
}
|
|
249
|
+
function reportEntries(reports, header, agentId) {
|
|
250
|
+
const outcomes = reports.map((r) => entryOutcome([r]));
|
|
251
|
+
const receipted = reports.filter((r) => BigInt(r.feedbackHash) !== 0n);
|
|
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
|
+
};
|
|
259
|
+
const all = reports.flatMap((r) => r.checks);
|
|
260
|
+
const status = tally(all, "fail") + tally(all, "error") > 0 ? 1 : 0;
|
|
261
|
+
if (json) {
|
|
262
|
+
const entries = reports.map(({ checks, decision, ...r }, i) => ({
|
|
263
|
+
...r,
|
|
264
|
+
...(decision ? { decision: { id: decision.id, set: decision.set, kind: decision.kind, ...(decision.task === undefined ? {} : { task: decision.task }) } } : {}),
|
|
265
|
+
verdict: outcomes[i],
|
|
266
|
+
checks,
|
|
267
|
+
}));
|
|
268
|
+
const out = {
|
|
269
|
+
network: network.name,
|
|
270
|
+
chainId: network.chainId,
|
|
271
|
+
registry: { chainId: REPUTATION.chainId, address: REPUTATION.address, writers: REPUTATION.writers },
|
|
272
|
+
...(agentId === undefined ? {} : { agentId }),
|
|
273
|
+
verdict: entryOutcome(reports),
|
|
274
|
+
summary,
|
|
275
|
+
entries,
|
|
276
|
+
notChecked: NOT_CHECKED,
|
|
277
|
+
trustModel: TRUST_MODEL,
|
|
278
|
+
};
|
|
279
|
+
console.log(JSON.stringify(out, null, 2));
|
|
280
|
+
process.exit(status);
|
|
281
|
+
}
|
|
282
|
+
console.log(`${header}\n`);
|
|
283
|
+
const [one] = reports;
|
|
284
|
+
if (agentId === undefined && one) {
|
|
285
|
+
for (const c of one.checks)
|
|
286
|
+
console.log(` ${TAGS[c.status].padEnd(5)} ${c.message}`);
|
|
287
|
+
console.log(`\n${entryVerdict(one)}`);
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
for (const [i, r] of reports.entries()) {
|
|
291
|
+
console.log(` ${ENTRY_TAGS[outcomes[i]].padEnd(10)} ${r.entry} ${about(r)}`);
|
|
292
|
+
for (const c of r.checks)
|
|
293
|
+
if (c.status === "fail" || c.status === "error")
|
|
294
|
+
console.log(` ${TAGS[c.status].padEnd(5)} ${c.message}`);
|
|
295
|
+
}
|
|
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
|
+
}
|
|
299
|
+
console.log(`Not checked: that Jev produced the answer. See ${TRUST_MODEL}`);
|
|
300
|
+
process.exit(status);
|
|
301
|
+
}
|
|
302
|
+
/** --entry and --agent: BrainChain's entries in the ERC-8004 reputation registry, each checked through its receipt to the chain. */
|
|
303
|
+
async function checkEntries() {
|
|
304
|
+
if (network.chainId !== REPUTATION.network)
|
|
305
|
+
usage("BrainChain writes reputation entries for mainnet tasks only, so --entry and --agent read mainnet");
|
|
306
|
+
const registry = { ...REPUTATION, client: createPublicClient({ transport: http(registryRpcArg ?? REPUTATION.rpc) }) };
|
|
307
|
+
const [current, ...earlier] = registry.writers;
|
|
308
|
+
const where = `in the ERC-8004 reputation registry on Robinhood Chain (${registry.address})`;
|
|
309
|
+
const ctx = { client, network, set: network.sets[0], briefs: new Map() };
|
|
310
|
+
if (entryArg !== undefined) {
|
|
311
|
+
const parts = /^(0|[1-9]\d{0,77}):(?:(0x[0-9a-fA-F]{40}):)?([1-9]\d{0,19})$/.exec(entryArg);
|
|
312
|
+
if (!parts)
|
|
313
|
+
usage("An entry is <agentId>:<feedbackIndex>, or <agentId>:<writer>:<feedbackIndex> for one BrainChain wrote from an earlier address");
|
|
314
|
+
const named = parts[2];
|
|
315
|
+
const writer = named === undefined ? current : registry.writers.find((w) => w.toLowerCase() === named.toLowerCase());
|
|
316
|
+
if (!writer)
|
|
317
|
+
usage(`BrainChain writes its entries from ${registry.writers.join(" and ")}, not ${named}`);
|
|
318
|
+
const agentId = BigInt(parts[1]);
|
|
319
|
+
const index = BigInt(parts[3]);
|
|
320
|
+
try {
|
|
321
|
+
await sameChain(registry);
|
|
322
|
+
const found = await entriesOf(registry, agentId, [writer]);
|
|
323
|
+
const entry = found.find((f) => f.feedbackIndex === index);
|
|
324
|
+
if (!entry) {
|
|
325
|
+
const held = found.length === 0 ? `has written no entry for agent ${agentId}` : `wrote entries 1 to ${found.at(-1).feedbackIndex} for agent ${agentId}`;
|
|
326
|
+
const hint = named === undefined && earlier.length > 0 ? `. It wrote earlier ones from ${earlier.join(" and ")}: name one as ${agentId}:<writer>:<feedbackIndex>` : "";
|
|
327
|
+
fail(`BrainChain ${held} from ${writer}${hint}`);
|
|
328
|
+
}
|
|
329
|
+
reportEntries([await verifyEntry(ctx, registry, entry)], `Entry ${entryName(registry, entry)} ${where}`);
|
|
330
|
+
}
|
|
331
|
+
catch (error) {
|
|
332
|
+
fail(errorMessage(error));
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
if (!/^(0|[1-9]\d{0,77})$/.test(agentArg))
|
|
336
|
+
usage("An agent id is a whole number");
|
|
337
|
+
const agentId = BigInt(agentArg);
|
|
338
|
+
try {
|
|
339
|
+
await sameChain(registry);
|
|
340
|
+
const found = await entriesOf(registry, agentId);
|
|
341
|
+
if (found.length === 0)
|
|
342
|
+
fail(`BrainChain has written no entry for agent ${agentId} ${where}`);
|
|
343
|
+
const reports = [];
|
|
344
|
+
for (const f of found)
|
|
345
|
+
reports.push(await verifyEntry(ctx, registry, f));
|
|
346
|
+
reportEntries(reports, `Agent ${agentId} ${where}: ${found.length} entr${found.length === 1 ? "y" : "ies"} BrainChain wrote`, agentId.toString());
|
|
347
|
+
}
|
|
348
|
+
catch (error) {
|
|
349
|
+
fail(errorMessage(error));
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
try {
|
|
353
|
+
await sameChain();
|
|
196
354
|
const where = `on ${network.name}, contract set ${set.key}`;
|
|
197
355
|
if (taskArg !== undefined) {
|
|
198
356
|
const task = BigInt(taskArg);
|
package/dist/verify.d.ts
CHANGED
|
@@ -105,7 +105,93 @@ export declare function receiptDecision(value: unknown): {
|
|
|
105
105
|
} | undefined;
|
|
106
106
|
export type Outcome = "match" | "withheld" | "unverified" | "mismatch";
|
|
107
107
|
/** Disagreement first, then what could not be read. A withheld record never reads as a match: its hashes were not checked. */
|
|
108
|
-
export declare function outcomeOf(reports: DecisionReport[]): Outcome;
|
|
108
|
+
export declare function outcomeOf(reports: Pick<DecisionReport, "checks" | "withheld">[]): Outcome;
|
|
109
109
|
/** What a withheld copy leaves unchecked. A grade of outside work has no task here, so nothing on chain backs its brief or levels. */
|
|
110
110
|
export declare function withheldNotChecked(reports: DecisionReport[]): string;
|
|
111
|
+
/** Where BrainChain records each task that settles for an ERC-8004 agent, and whom its entries name. */
|
|
112
|
+
export interface Registry {
|
|
113
|
+
/** Reads the chain the registries are on. */
|
|
114
|
+
client: PublicClient;
|
|
115
|
+
chainId: number;
|
|
116
|
+
/** The ERC-8004 reputation registry. */
|
|
117
|
+
address: Address;
|
|
118
|
+
/** The ERC-8004 identity registry, which says who held an agent and when. */
|
|
119
|
+
identity: Address;
|
|
120
|
+
/** The addresses BrainChain writes entries from, the one it writes from now first. Anyone can write under its tag, so only these count. */
|
|
121
|
+
writers: readonly Address[];
|
|
122
|
+
/** The block of BrainChain's first entry. */
|
|
123
|
+
fromBlock: bigint;
|
|
124
|
+
/** BrainChain's house workers: the model name the board hires each agent id by. */
|
|
125
|
+
house: Readonly<Record<string, string>>;
|
|
126
|
+
}
|
|
127
|
+
/** BrainChain mainnet's: the registries on Robinhood Chain, and the addresses and agents its docs list (workers#erc-8004-identity). */
|
|
128
|
+
export declare const REPUTATION: {
|
|
129
|
+
readonly network: 274663;
|
|
130
|
+
readonly chainId: 4663;
|
|
131
|
+
readonly rpc: "https://rpc.mainnet.chain.robinhood.com";
|
|
132
|
+
readonly address: "0x8004BAa17C55a88189AE136b182e5fdA19dE9b63";
|
|
133
|
+
readonly identity: "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432";
|
|
134
|
+
readonly writers: readonly ["0x97D558417c3D61f1074422AD843e1Db1E565b952", "0xafB0C4Ef895D4895040cdC6435B96D3EE8350c6E"];
|
|
135
|
+
readonly fromBlock: 103375137n;
|
|
136
|
+
readonly house: {
|
|
137
|
+
readonly 20424: "claude";
|
|
138
|
+
readonly 20425: "gpt";
|
|
139
|
+
readonly 20426: "gemini";
|
|
140
|
+
readonly 20427: "grok";
|
|
141
|
+
readonly 20428: "deepseek";
|
|
142
|
+
};
|
|
143
|
+
};
|
|
144
|
+
/** An entry as its NewFeedback event states it. The registry names it by agent, writer and index. */
|
|
145
|
+
export interface Feedback {
|
|
146
|
+
agentId: bigint;
|
|
147
|
+
clientAddress: Address;
|
|
148
|
+
/** From 1 for each agent and writer. */
|
|
149
|
+
feedbackIndex: bigint;
|
|
150
|
+
value: bigint;
|
|
151
|
+
valueDecimals: number;
|
|
152
|
+
tag1: string;
|
|
153
|
+
tag2: string;
|
|
154
|
+
endpoint: string;
|
|
155
|
+
feedbackURI: string;
|
|
156
|
+
feedbackHash: Hex;
|
|
157
|
+
block: bigint;
|
|
158
|
+
transaction: Hex;
|
|
159
|
+
}
|
|
160
|
+
export interface EntryReport {
|
|
161
|
+
/** As --entry takes it: the agent and the index, with the writer between them unless it is the one BrainChain writes from now. */
|
|
162
|
+
entry: string;
|
|
163
|
+
agentId: string;
|
|
164
|
+
clientAddress: Address;
|
|
165
|
+
feedbackIndex: number;
|
|
166
|
+
value: number;
|
|
167
|
+
block: number;
|
|
168
|
+
transaction: Hex;
|
|
169
|
+
endpoint: string;
|
|
170
|
+
feedbackURI: string;
|
|
171
|
+
feedbackHash: Hex;
|
|
172
|
+
/** The task the endpoint names, and its board and contract set where it names one the tool carries. */
|
|
173
|
+
task?: number;
|
|
174
|
+
board?: Address;
|
|
175
|
+
set?: string;
|
|
176
|
+
/** The decision the entry's receipt names, checked with the receipt. Its checks are among the entry's. */
|
|
177
|
+
decision?: DecisionReport & {
|
|
178
|
+
set: string;
|
|
179
|
+
};
|
|
180
|
+
/** That decision's record was served without the work, so its hashes could not be checked. */
|
|
181
|
+
withheld?: boolean;
|
|
182
|
+
checks: Check[];
|
|
183
|
+
}
|
|
184
|
+
export declare const entryName: (registry: Registry, f: Pick<Feedback, "agentId" | "clientAddress" | "feedbackIndex">) => string;
|
|
185
|
+
/** Every entry BrainChain wrote for an agent, from the writers given or all of its own, oldest first. */
|
|
186
|
+
export declare function entriesOf(registry: Registry, agentId: bigint, writers?: readonly Address[]): Promise<Feedback[]>;
|
|
187
|
+
/**
|
|
188
|
+
* One entry, end to end: as the registry holds it, the task its endpoint
|
|
189
|
+
* names, the receipt its feedbackHash commits to, the decision and payment
|
|
190
|
+
* that receipt names, and the board's settlement and hire behind its value
|
|
191
|
+
* and its agent.
|
|
192
|
+
*/
|
|
193
|
+
export declare function verifyEntry(ctx: Context, registry: Registry, f: Feedback): Promise<EntryReport>;
|
|
194
|
+
export type EntryOutcome = Outcome | "no-receipt";
|
|
195
|
+
/** As for decisions, and `no-receipt` when everything passed and no entry had a receipt to check. */
|
|
196
|
+
export declare function entryOutcome(reports: EntryReport[]): EntryOutcome;
|
|
111
197
|
export {};
|
package/dist/verify.js
CHANGED
|
@@ -4,7 +4,7 @@ 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";
|
|
6
6
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
7
|
-
import { BaseError, createPublicClient, decodeFunctionData, encodeAbiParameters, encodeFunctionData, http, keccak256, pad, parseAbi, parseEventLogs, recoverMessageAddress, recoverTypedDataAddress, toBytes, TransactionReceiptNotFoundError, toHex, } from "viem";
|
|
7
|
+
import { BaseError, createPublicClient, decodeFunctionData, encodeAbiParameters, encodeFunctionData, getAddress, http, keccak256, pad, parseAbi, parseEventLogs, recoverMessageAddress, recoverTypedDataAddress, size, toBytes, TransactionReceiptNotFoundError, toHex, zeroAddress, } from "viem";
|
|
8
8
|
import { decisionExecutorAbi, decisionLogAbi, modelRegistryAbi, taskBoardAbi } from "./abi.js";
|
|
9
9
|
import { canonicalStringify } from "./canonical.js";
|
|
10
10
|
const Kind = { Hire: 1, Grade: 2, Ruling: 3, Change: 4 };
|
|
@@ -1260,11 +1260,12 @@ async function readDesk({ client, network, set }, origin) {
|
|
|
1260
1260
|
const former = Array.isArray(manifest.formerDesks) ? manifest.formerDesks.filter((d) => typeof d === "string") : [];
|
|
1261
1261
|
return { payees: payees, formerDesks: former };
|
|
1262
1262
|
}
|
|
1263
|
+
const ROBINHOOD_RPC = "https://rpc.mainnet.chain.robinhood.com";
|
|
1263
1264
|
// Public RPCs for the networks the desk takes payment on.
|
|
1264
1265
|
const PAYMENT_RPCS = {
|
|
1265
1266
|
"eip155:8453": "https://mainnet.base.org",
|
|
1266
1267
|
"eip155:84532": "https://sepolia.base.org",
|
|
1267
|
-
"eip155:4663":
|
|
1268
|
+
"eip155:4663": ROBINHOOD_RPC,
|
|
1268
1269
|
"eip155:46630": "https://rpc.testnet.chain.robinhood.com",
|
|
1269
1270
|
"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": "https://api.mainnet-beta.solana.com",
|
|
1270
1271
|
"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1": "https://api.devnet.solana.com",
|
|
@@ -1350,3 +1351,292 @@ export function withheldNotChecked(reports) {
|
|
|
1350
1351
|
? "Its answer and confidence agree with the chain. The rest of it, such as the question, its levels and the second grader, is the host's word."
|
|
1351
1352
|
: "Its answer and confidence agree with the chain, and so do the task's brief, levels and threshold. The rest of it, such as the question and the second grader, is the host's word."));
|
|
1352
1353
|
}
|
|
1354
|
+
/** BrainChain mainnet's: the registries on Robinhood Chain, and the addresses and agents its docs list (workers#erc-8004-identity). */
|
|
1355
|
+
export const REPUTATION = {
|
|
1356
|
+
network: 274663,
|
|
1357
|
+
chainId: 4663,
|
|
1358
|
+
rpc: ROBINHOOD_RPC,
|
|
1359
|
+
address: "0x8004BAa17C55a88189AE136b182e5fdA19dE9b63",
|
|
1360
|
+
identity: "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432",
|
|
1361
|
+
// The desk key since 10 November 2026, and the one before it.
|
|
1362
|
+
writers: ["0x97D558417c3D61f1074422AD843e1Db1E565b952", "0xafB0C4Ef895D4895040cdC6435B96D3EE8350c6E"],
|
|
1363
|
+
fromBlock: 103375137n,
|
|
1364
|
+
house: { 20424: "claude", 20425: "gpt", 20426: "gemini", 20427: "grok", 20428: "deepseek" },
|
|
1365
|
+
};
|
|
1366
|
+
// EIP-8004's registries, as deployed on Robinhood Chain.
|
|
1367
|
+
const reputationAbi = parseAbi([
|
|
1368
|
+
"event NewFeedback(uint256 indexed agentId, address indexed clientAddress, uint64 feedbackIndex, int128 value, uint8 valueDecimals, string indexed indexedTag1, string tag1, string tag2, string endpoint, string feedbackURI, bytes32 feedbackHash)",
|
|
1369
|
+
"function readFeedback(uint256 agentId, address clientAddress, uint64 feedbackIndex) view returns (int128 value, uint8 valueDecimals, string tag1, string tag2, bool isRevoked)",
|
|
1370
|
+
]);
|
|
1371
|
+
const identityAbi = parseAbi([
|
|
1372
|
+
"event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)",
|
|
1373
|
+
"event MetadataSet(uint256 indexed agentId, string indexed indexedMetadataKey, string metadataKey, bytes metadataValue)",
|
|
1374
|
+
]);
|
|
1375
|
+
const TAG = "brainchain";
|
|
1376
|
+
// Robinhood Chain's RPC reads logs over at most this many blocks, and only when each topic it filters on has one value.
|
|
1377
|
+
const LOG_SPAN = 10000000n;
|
|
1378
|
+
// An outside worker's model id is its address, left-padded to 32 bytes.
|
|
1379
|
+
const PADDED = /^0x0{24}([0-9a-f]{40})$/i;
|
|
1380
|
+
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
|
+
export const entryName = (registry, f) => `${f.agentId}:${eq(f.clientAddress, registry.writers[0] ?? "") ? "" : `${f.clientAddress}:`}${f.feedbackIndex}`;
|
|
1382
|
+
/** Every entry BrainChain wrote for an agent, from the writers given or all of its own, oldest first. */
|
|
1383
|
+
export async function entriesOf(registry, agentId, writers = registry.writers) {
|
|
1384
|
+
const { client, address } = registry;
|
|
1385
|
+
const head = await client.getBlockNumber();
|
|
1386
|
+
const found = [];
|
|
1387
|
+
for (const writer of writers) {
|
|
1388
|
+
for (let from = registry.fromBlock; from <= head; from += LOG_SPAN) {
|
|
1389
|
+
const toBlock = from + LOG_SPAN - 1n < head ? from + LOG_SPAN - 1n : head;
|
|
1390
|
+
const events = await client.getContractEvents({ address, abi: reputationAbi, eventName: "NewFeedback", args: { agentId, clientAddress: writer }, fromBlock: from, toBlock, strict: true });
|
|
1391
|
+
for (const { args, blockNumber, transactionHash } of events) {
|
|
1392
|
+
const { indexedTag1: _, ...entry } = args;
|
|
1393
|
+
found.push({ ...entry, block: blockNumber, transaction: transactionHash });
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
return found.sort((a, b) => (a.block === b.block ? Number(a.feedbackIndex - b.feedbackIndex) : a.block < b.block ? -1 : 1));
|
|
1398
|
+
}
|
|
1399
|
+
/**
|
|
1400
|
+
* One entry, end to end: as the registry holds it, the task its endpoint
|
|
1401
|
+
* names, the receipt its feedbackHash commits to, the decision and payment
|
|
1402
|
+
* that receipt names, and the board's settlement and hire behind its value
|
|
1403
|
+
* and its agent.
|
|
1404
|
+
*/
|
|
1405
|
+
export async function verifyEntry(ctx, registry, f) {
|
|
1406
|
+
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
|
+
};
|
|
1420
|
+
await checkStored(registry, c, f);
|
|
1421
|
+
const page = taskPage(ctx.network.sets, f.endpoint);
|
|
1422
|
+
if (page)
|
|
1423
|
+
report.task = Number(page.task);
|
|
1424
|
+
if (page?.board)
|
|
1425
|
+
report.board = page.board;
|
|
1426
|
+
if (page?.set)
|
|
1427
|
+
report.set = page.set.key;
|
|
1428
|
+
checkEndpoint(c, f.endpoint, page);
|
|
1429
|
+
let receipt;
|
|
1430
|
+
if (eq(f.feedbackHash, NO))
|
|
1431
|
+
c.add("feedback-hash", "skip", NO_RECEIPT);
|
|
1432
|
+
else
|
|
1433
|
+
receipt = await entryReceipt(ctx, c, f);
|
|
1434
|
+
if (receipt) {
|
|
1435
|
+
const on = contextFor(ctx, receipt.set);
|
|
1436
|
+
const decided = await verifyDecision(on, receipt.decision, receipt.given);
|
|
1437
|
+
c.list.push(...decided.checks);
|
|
1438
|
+
report.decision = { ...decided, set: receipt.set.key };
|
|
1439
|
+
if (decided.withheld)
|
|
1440
|
+
report.withheld = true;
|
|
1441
|
+
await checkEntryTask(on, c, receipt.decision, page);
|
|
1442
|
+
}
|
|
1443
|
+
if (page?.set) {
|
|
1444
|
+
const placed = { task: page.task, set: page.set };
|
|
1445
|
+
await checkValue(ctx, c, f, placed, receipt?.outcome);
|
|
1446
|
+
await checkWorker(ctx, registry, c, f, placed);
|
|
1447
|
+
}
|
|
1448
|
+
return report;
|
|
1449
|
+
}
|
|
1450
|
+
/** The entry as the registry holds it beside its event, under BrainChain's tags and on its scale. */
|
|
1451
|
+
async function checkStored({ client, address }, c, f) {
|
|
1452
|
+
const [value, decimals, tag1, tag2, revoked] = await client.readContract({ address, abi: reputationAbi, functionName: "readFeedback", args: [f.agentId, f.clientAddress, f.feedbackIndex] });
|
|
1453
|
+
const wrong = [];
|
|
1454
|
+
if (value !== f.value || decimals !== f.valueDecimals || tag1 !== f.tag1 || tag2 !== f.tag2) {
|
|
1455
|
+
wrong.push(`the registry holds ${value} with ${decimals} decimals under ${tag1} and ${tag2}, where its NewFeedback event says ${f.value} with ${f.valueDecimals} under ${f.tag1} and ${f.tag2}`);
|
|
1456
|
+
}
|
|
1457
|
+
if (f.tag1 !== TAG || f.tag2 !== "task")
|
|
1458
|
+
wrong.push(`its tags are ${f.tag1} and ${f.tag2}, where BrainChain writes ${TAG} and task`);
|
|
1459
|
+
if (f.valueDecimals !== 0 || (f.value !== 0n && f.value !== 100n))
|
|
1460
|
+
wrong.push(`its value is ${f.value} with ${f.valueDecimals} decimals, where BrainChain writes 100 or 0 with none`);
|
|
1461
|
+
c.check("entry", wrong.length === 0, `entry: value ${f.value} for agent ${f.agentId} under ${TAG} and task, written by ${short(f.clientAddress)} in block ${f.block}, as the registry holds it${revoked ? ". Revoked since, so the registry's summaries leave it out" : ""}`, `entry: ${wrong.join("; ")}`);
|
|
1462
|
+
}
|
|
1463
|
+
/** The task page BrainChain names as an entry's endpoint: `task?id=<task>&board=<TaskBoard>`, or the id alone before 5 November. */
|
|
1464
|
+
function taskPage(sets, endpoint) {
|
|
1465
|
+
if (!URL.canParse(endpoint))
|
|
1466
|
+
return undefined;
|
|
1467
|
+
const url = new URL(endpoint);
|
|
1468
|
+
const id = url.searchParams.get("id");
|
|
1469
|
+
const board = url.searchParams.get("board");
|
|
1470
|
+
if (!url.pathname.endsWith("/task") || id === null || !/^[1-9]\d{0,77}$/.test(id) || (board !== null && !ADDRESS.test(board)))
|
|
1471
|
+
return undefined;
|
|
1472
|
+
if (board === null)
|
|
1473
|
+
return { task: BigInt(id) };
|
|
1474
|
+
return { task: BigInt(id), board: getAddress(board), set: sets.find((s) => eq(s.board, board)) };
|
|
1475
|
+
}
|
|
1476
|
+
function checkEndpoint(c, endpoint, page) {
|
|
1477
|
+
if (!page)
|
|
1478
|
+
return c.add("endpoint", "fail", `endpoint: ${display(endpoint)} is not a task page, which BrainChain names in every entry`);
|
|
1479
|
+
if (!page.board) {
|
|
1480
|
+
return c.add("endpoint", "skip", `endpoint: task ${page.task}, on no board. Entries from before 5 November name the task alone, and task ids restart with each board, so the task's checks did not run`);
|
|
1481
|
+
}
|
|
1482
|
+
if (!page.set)
|
|
1483
|
+
return c.add("endpoint", "skip", `endpoint: task ${page.task} on board ${short(page.board)}, none of the contract sets this tool carries, so the task's checks did not run`);
|
|
1484
|
+
c.add("endpoint", "ok", `endpoint: task ${page.task} on board ${short(page.board)}, contract set ${page.set.key}`);
|
|
1485
|
+
}
|
|
1486
|
+
/** The receipt at feedbackURI, once its bytes hash to feedbackHash and it names a decision the DecisionLog it names holds, at the address the brain serves that receipt from. */
|
|
1487
|
+
async function entryReceipt(ctx, c, f) {
|
|
1488
|
+
let bytes;
|
|
1489
|
+
try {
|
|
1490
|
+
({ bytes } = await fetchBytes(f.feedbackURI, { what: "receipt", limit: MAX_RECEIPT_BYTES, allowPrivate: await allowsPrivate(ctx.client) }));
|
|
1491
|
+
}
|
|
1492
|
+
catch (error) {
|
|
1493
|
+
c.add("feedback-hash", "error", `could not fetch the receipt: ${errorMessage(error)}`);
|
|
1494
|
+
return undefined;
|
|
1495
|
+
}
|
|
1496
|
+
const hash = keccak256(bytes);
|
|
1497
|
+
const where = display(f.feedbackURI);
|
|
1498
|
+
if (!eq(hash, f.feedbackHash)) {
|
|
1499
|
+
c.add("feedback-hash", "fail", `feedback hash: the receipt at ${where} hashes to ${short(hash)}, not to feedbackHash ${short(f.feedbackHash)}`);
|
|
1500
|
+
return undefined;
|
|
1501
|
+
}
|
|
1502
|
+
c.add("feedback-hash", "ok", `feedback hash: the receipt at ${where} hashes to feedbackHash ${short(hash)}`);
|
|
1503
|
+
const text = decodeText(bytes);
|
|
1504
|
+
const value = text === undefined ? undefined : parseJson(text);
|
|
1505
|
+
const receipt = parseReceipt(value);
|
|
1506
|
+
if (!receipt || receipt.x402) {
|
|
1507
|
+
c.add("entry-receipt", "fail", `receipt: ${where} is not a receipt as BrainChain signs one`);
|
|
1508
|
+
return undefined;
|
|
1509
|
+
}
|
|
1510
|
+
const { decision, decisionLog, outcome } = receipt.payload;
|
|
1511
|
+
const set = ctx.network.sets.find((s) => eq(s.log, decisionLog));
|
|
1512
|
+
if (!set) {
|
|
1513
|
+
c.add("entry-receipt", "fail", `receipt: names DecisionLog ${short(decisionLog)}, none of the contract sets on ${ctx.network.name}`);
|
|
1514
|
+
return undefined;
|
|
1515
|
+
}
|
|
1516
|
+
const recorded = await ctx.client.readContract({ address: set.log, abi: decisionLogAbi, functionName: "count" });
|
|
1517
|
+
const path = `/receipts/${decisionLog.toLowerCase()}/${decision}.json`;
|
|
1518
|
+
const wrong = [];
|
|
1519
|
+
if (BigInt(decision) < 1n || BigInt(decision) > recorded)
|
|
1520
|
+
wrong.push(`decision ${decision}, and DecisionLog ${short(set.log)} holds decisions 1 to ${recorded}`);
|
|
1521
|
+
if (!URL.canParse(f.feedbackURI) || new URL(f.feedbackURI).pathname !== path)
|
|
1522
|
+
wrong.push(`decision ${decision} on DecisionLog ${short(set.log)}, whose receipt the brain serves at ${path}, not at ${where}`);
|
|
1523
|
+
c.check("entry-receipt", wrong.length === 0, `receipt: names decision ${decision} on DecisionLog ${short(set.log)}, contract set ${set.key}, and is served at that decision's address`, `receipt: names ${list(wrong)}`);
|
|
1524
|
+
return wrong.length === 0 ? { decision: BigInt(decision), set, given: { from: clean(f.feedbackURI), value }, outcome } : undefined;
|
|
1525
|
+
}
|
|
1526
|
+
const setContexts = new WeakMap();
|
|
1527
|
+
/** The context for another contract set on the same network, kept so each set's briefs and desk are read once. */
|
|
1528
|
+
function contextFor(ctx, set) {
|
|
1529
|
+
if (set === ctx.set)
|
|
1530
|
+
return ctx;
|
|
1531
|
+
let known = setContexts.get(ctx);
|
|
1532
|
+
if (!known)
|
|
1533
|
+
setContexts.set(ctx, (known = new Map()));
|
|
1534
|
+
let found = known.get(set.key);
|
|
1535
|
+
if (!found)
|
|
1536
|
+
known.set(set.key, (found = { ...ctx, set, briefs: new Map() }));
|
|
1537
|
+
return found;
|
|
1538
|
+
}
|
|
1539
|
+
async function checkEntryTask(ctx, c, id, page) {
|
|
1540
|
+
if (!page?.set)
|
|
1541
|
+
return c.add("entry-task", "skip", `task: the endpoint names no task on a board this tool carries, so decision ${id} is not tied to one`);
|
|
1542
|
+
const { subject } = await readDecision(ctx, id);
|
|
1543
|
+
const board = short(page.set.board);
|
|
1544
|
+
c.check("entry-task", subject === taskSubject(ctx.network.chainId, page.set.board, page.task), `task: decision ${id} is about task ${page.task} on board ${board}, the task the endpoint names`, `task: decision ${id} on DecisionLog ${short(ctx.set.log)} is not about task ${page.task} on board ${board}, the task the endpoint names`);
|
|
1545
|
+
}
|
|
1546
|
+
/** BrainChain writes 100 for a task the board paid and 0 for one it refunded, and a task's receipt says accepted or rejected for the same. */
|
|
1547
|
+
async function checkValue({ client }, c, f, { task, set }, outcome) {
|
|
1548
|
+
const on = await client.readContract({ address: set.board, abi: taskBoardAbi, functionName: "get", args: [task] });
|
|
1549
|
+
const settled = on.status === Status.Paid ? "paid" : on.status === Status.Refunded ? "refunded" : undefined;
|
|
1550
|
+
if (!settled) {
|
|
1551
|
+
return c.add("entry-value", "fail", `value: task ${task} is ${STATUS[on.status] ?? `status ${on.status}`}. The board has neither paid nor refunded it, and BrainChain writes an entry only once it has`);
|
|
1552
|
+
}
|
|
1553
|
+
const owed = settled === "paid" ? 100n : 0n;
|
|
1554
|
+
const wrong = [];
|
|
1555
|
+
if (f.value !== owed)
|
|
1556
|
+
wrong.push(`the board ${settled} task ${task}, which BrainChain writes as ${owed}`);
|
|
1557
|
+
if (outcome !== undefined && outcome !== (f.value === 100n ? "accepted" : "rejected"))
|
|
1558
|
+
wrong.push(`the receipt says ${outcome}`);
|
|
1559
|
+
c.check("entry-value", wrong.length === 0, `value: ${f.value}, as the board ${settled} task ${task}${outcome === undefined ? "" : ` and the receipt says ${outcome}`}`, `value: ${f.value}, but ${list(wrong)}`);
|
|
1560
|
+
}
|
|
1561
|
+
/** The worker the board hired for the task is the agent: a house worker by its model name, an outside worker by an address that held the agent when it was hired. */
|
|
1562
|
+
async function checkWorker(ctx, registry, c, f, { task, set }) {
|
|
1563
|
+
const hires = await ctx.client.getContractEvents({ address: set.board, abi: taskBoardAbi, eventName: "WorkerHired", args: { id: task }, fromBlock: BigInt(set.fromBlock), strict: true });
|
|
1564
|
+
const hired = hires.at(-1);
|
|
1565
|
+
if (!hired)
|
|
1566
|
+
return c.add("entry-worker", "fail", `worker: the board hired no worker for task ${task}`);
|
|
1567
|
+
const model = hired.args.model.toLowerCase();
|
|
1568
|
+
const agent = f.agentId.toString();
|
|
1569
|
+
const named = (id) => {
|
|
1570
|
+
const house = Object.entries(registry.house).find(([, name]) => keccak256(toBytes(name)) === id);
|
|
1571
|
+
return house ? `${house[1]}, house agent ${house[0]}` : `model ${short(id)}`;
|
|
1572
|
+
};
|
|
1573
|
+
const house = registry.house[agent];
|
|
1574
|
+
if (house !== undefined) {
|
|
1575
|
+
c.check("entry-worker", keccak256(toBytes(house)) === model, `worker: the board hired ${house} for task ${task} as keccak256("${house}"), and agent ${agent} is the house worker ${house}`, `worker: agent ${agent} is the house worker ${house}, and the board hired ${named(model)} for task ${task}`);
|
|
1576
|
+
return;
|
|
1577
|
+
}
|
|
1578
|
+
const account = PADDED.exec(model)?.[1];
|
|
1579
|
+
if (!account)
|
|
1580
|
+
return c.add("entry-worker", "fail", `worker: the board hired ${named(model)} for task ${task}, which no outside agent can be`);
|
|
1581
|
+
const worker = getAddress(`0x${account}`);
|
|
1582
|
+
const { timestamp } = await ctx.client.getBlock({ blockNumber: hired.blockNumber });
|
|
1583
|
+
const held = await holderAt(registry, f.agentId, timestamp);
|
|
1584
|
+
const as = held.owner && eq(held.owner, worker) ? "owned" : held.wallet && eq(held.wallet, worker) ? "was the registered wallet of" : undefined;
|
|
1585
|
+
const holder = held.owner ? `${short(held.owner)} owned it${held.wallet ? ` and ${short(held.wallet)} was its wallet` : ""}` : "nobody held it";
|
|
1586
|
+
c.check("entry-worker", as !== undefined, `worker: the board hired ${short(worker)} for task ${task}, which ${as} agent ${agent} on the identity registry when it was hired`, `worker: the board hired ${short(worker)} for task ${task}, but when it was hired ${holder} on the identity registry`);
|
|
1587
|
+
}
|
|
1588
|
+
const identities = new WeakMap();
|
|
1589
|
+
/** Who owned the agent and which wallet it had registered at `time`, replayed from its events: the registry clears the wallet when the agent changes hands. */
|
|
1590
|
+
async function holderAt(registry, agentId, time) {
|
|
1591
|
+
let known = identities.get(registry);
|
|
1592
|
+
if (!known)
|
|
1593
|
+
identities.set(registry, (known = new Map()));
|
|
1594
|
+
let pending = known.get(agentId);
|
|
1595
|
+
if (!pending)
|
|
1596
|
+
known.set(agentId, (pending = identityEvents(registry, agentId)));
|
|
1597
|
+
let owner;
|
|
1598
|
+
let wallet;
|
|
1599
|
+
for (const event of await pending) {
|
|
1600
|
+
if (event.time > time)
|
|
1601
|
+
break;
|
|
1602
|
+
if (event.transfer) {
|
|
1603
|
+
owner = event.transfer.to === zeroAddress ? undefined : event.transfer.to;
|
|
1604
|
+
if (event.transfer.from !== zeroAddress)
|
|
1605
|
+
wallet = undefined;
|
|
1606
|
+
}
|
|
1607
|
+
else {
|
|
1608
|
+
wallet = event.wallet && size(event.wallet) === 20 ? getAddress(event.wallet) : undefined;
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
return { ...(owner ? { owner } : {}), ...(wallet ? { wallet } : {}) };
|
|
1612
|
+
}
|
|
1613
|
+
/** The agent's transfers and agentWallet changes, oldest first, read back from the head to its mint. */
|
|
1614
|
+
async function identityEvents({ client, identity }, agentId) {
|
|
1615
|
+
const found = [];
|
|
1616
|
+
for (let to = await client.getBlockNumber();;) {
|
|
1617
|
+
const fromBlock = to >= LOG_SPAN ? to - LOG_SPAN + 1n : 0n;
|
|
1618
|
+
const span = { address: identity, abi: identityAbi, fromBlock, toBlock: to, strict: true };
|
|
1619
|
+
const [transfers, wallets] = await Promise.all([
|
|
1620
|
+
client.getContractEvents({ ...span, eventName: "Transfer", args: { tokenId: agentId } }),
|
|
1621
|
+
client.getContractEvents({ ...span, eventName: "MetadataSet", args: { agentId, indexedMetadataKey: "agentWallet" } }),
|
|
1622
|
+
]);
|
|
1623
|
+
for (const { args, blockNumber, logIndex } of transfers)
|
|
1624
|
+
found.push({ block: blockNumber, index: logIndex, event: { transfer: { from: args.from, to: args.to } } });
|
|
1625
|
+
for (const { args, blockNumber, logIndex } of wallets)
|
|
1626
|
+
found.push({ block: blockNumber, index: logIndex, event: { wallet: args.metadataValue } });
|
|
1627
|
+
if (fromBlock === 0n || transfers.some((t) => t.args.from === zeroAddress))
|
|
1628
|
+
break;
|
|
1629
|
+
to = fromBlock - 1n;
|
|
1630
|
+
}
|
|
1631
|
+
found.sort((a, b) => (a.block === b.block ? a.index - b.index : a.block < b.block ? -1 : 1));
|
|
1632
|
+
const times = new Map();
|
|
1633
|
+
for (const { block } of found)
|
|
1634
|
+
if (!times.has(block))
|
|
1635
|
+
times.set(block, client.getBlock({ blockNumber: block }).then((b) => b.timestamp));
|
|
1636
|
+
return Promise.all(found.map(async ({ block, event }) => ({ ...event, time: await times.get(block) })));
|
|
1637
|
+
}
|
|
1638
|
+
/** As for decisions, and `no-receipt` when everything passed and no entry had a receipt to check. */
|
|
1639
|
+
export function entryOutcome(reports) {
|
|
1640
|
+
const outcome = outcomeOf(reports);
|
|
1641
|
+
return outcome === "match" && reports.every((r) => eq(r.feedbackHash, NO)) ? "no-receipt" : outcome;
|
|
1642
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "brainchain-verify",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
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",
|