@t3foundry/tasra-sdk 0.3.1 → 0.4.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/CHANGELOG.md +1067 -28
- package/README.md +15 -0
- package/dist/app/approvals.d.ts +66 -4
- package/dist/app/approvals.js +153 -16
- package/dist/app/authorization.d.ts +1 -1
- package/dist/app/authorization.js +1 -1
- package/dist/app/browser.d.ts +63 -0
- package/dist/app/browser.js +242 -0
- package/dist/app/client.d.ts +114 -13
- package/dist/app/client.js +302 -76
- package/dist/app/identity.js +21 -9
- package/dist/app/index.d.ts +28 -3
- package/dist/app/index.js +16 -1
- package/dist/app/memory-store.d.ts +7 -0
- package/dist/app/memory-store.js +55 -0
- package/dist/app/node.d.ts +34 -6
- package/dist/app/node.js +387 -64
- package/dist/app/paid-allowance.d.ts +325 -0
- package/dist/app/paid-allowance.js +1290 -0
- package/dist/app/paid-approval.d.ts +122 -0
- package/dist/app/paid-approval.js +379 -0
- package/dist/app/paid-journal.d.ts +51 -0
- package/dist/app/paid-journal.js +117 -0
- package/dist/app/paid-keys.d.ts +12 -0
- package/dist/app/paid-keys.js +20 -0
- package/dist/app/paid-operation.d.ts +821 -0
- package/dist/app/paid-operation.js +1720 -0
- package/dist/app/paid-reservation.d.ts +157 -0
- package/dist/app/paid-reservation.js +323 -0
- package/dist/app/paid-session.d.ts +147 -0
- package/dist/app/paid-session.js +578 -0
- package/dist/app/payer-queue.d.ts +11 -0
- package/dist/app/payer-queue.js +27 -0
- package/dist/app/policy-bootstrap.d.ts +342 -0
- package/dist/app/policy-bootstrap.js +365 -0
- package/dist/app/policy-operation.d.ts +47 -0
- package/dist/app/policy-operation.js +101 -0
- package/dist/app/ready-slot.d.ts +12 -0
- package/dist/app/ready-slot.js +5 -2
- package/dist/app/rotation-lock.d.ts +38 -0
- package/dist/app/rotation-lock.js +42 -0
- package/dist/app/session-decrypt.d.ts +135 -0
- package/dist/app/session-decrypt.js +335 -0
- package/dist/app/session-grants.d.ts +349 -0
- package/dist/app/session-grants.js +811 -0
- package/dist/app/signing-intents.d.ts +78 -0
- package/dist/app/signing-intents.js +95 -0
- package/dist/app/store-commit.d.ts +63 -0
- package/dist/app/store-commit.js +126 -0
- package/dist/app/store-errors.d.ts +8 -0
- package/dist/app/store-errors.js +11 -0
- package/dist/app/tasra-client.d.ts +2 -0
- package/dist/app/tasra-client.js +1 -1
- package/dist/app/wallet.js +4 -1
- package/dist/auth/holderProof.d.ts +3 -0
- package/dist/auth/holderProof.js +8 -7
- package/dist/auth/verifier.d.ts +4 -2
- package/dist/auth/verifier.js +5 -2
- package/dist/chain/abis/index.d.ts +6178 -4101
- package/dist/chain/abis/index.js +3 -0
- package/dist/chain/abis/keyRegistry.d.ts +256 -0
- package/dist/chain/abis/keyRegistry.js +333 -0
- package/dist/chain/abis/prepaidFaultOracle.d.ts +321 -0
- package/dist/chain/abis/prepaidFaultOracle.js +413 -0
- package/dist/chain/abis/settlement.d.ts +2203 -703
- package/dist/chain/abis/settlement.js +2685 -764
- package/dist/chain/allowance.d.ts +358 -0
- package/dist/chain/allowance.js +800 -0
- package/dist/chain/billing.d.ts +85 -0
- package/dist/chain/billing.js +197 -0
- package/dist/chain/chainId.d.ts +13 -0
- package/dist/chain/chainId.js +26 -0
- package/dist/chain/client.d.ts +15 -1
- package/dist/chain/client.js +57 -1
- package/dist/chain/commitmentRecovery.d.ts +51 -0
- package/dist/chain/commitmentRecovery.js +38 -0
- package/dist/chain/committeeClient.d.ts +17 -10
- package/dist/chain/committeeClient.js +64 -16
- package/dist/chain/committeeDraw.d.ts +12 -0
- package/dist/chain/committeeDraw.js +56 -0
- package/dist/chain/custodyHealth.d.ts +212 -0
- package/dist/chain/custodyHealth.js +365 -0
- package/dist/chain/deployments.js +2 -0
- package/dist/chain/events.js +2 -0
- package/dist/chain/headFollower.d.ts +77 -0
- package/dist/chain/headFollower.js +219 -0
- package/dist/chain/headPrefetch.d.ts +23 -0
- package/dist/chain/headPrefetch.js +67 -0
- package/dist/chain/index.d.ts +50 -8
- package/dist/chain/index.js +28 -3
- package/dist/chain/keeperExecution.d.ts +44 -0
- package/dist/chain/keeperExecution.js +127 -0
- package/dist/chain/keeperRecovery.d.ts +78 -0
- package/dist/chain/keeperRecovery.js +91 -0
- package/dist/chain/node.d.ts +24 -1
- package/dist/chain/node.js +88 -43
- package/dist/chain/offchain.d.ts +2 -0
- package/dist/chain/paidAgentTransport.d.ts +38 -0
- package/dist/chain/paidAgentTransport.js +1 -0
- package/dist/chain/paidEpoch.d.ts +66 -0
- package/dist/chain/paidEpoch.js +139 -0
- package/dist/chain/paidPacing.d.ts +81 -0
- package/dist/chain/paidPacing.js +136 -0
- package/dist/chain/pinnedReads.d.ts +49 -0
- package/dist/chain/pinnedReads.js +218 -0
- package/dist/chain/prepaid.d.ts +383 -0
- package/dist/chain/prepaid.js +1046 -0
- package/dist/chain/prepaidEscape.d.ts +274 -0
- package/dist/chain/prepaidEscape.js +432 -0
- package/dist/chain/prepaidFault.d.ts +94 -0
- package/dist/chain/prepaidFault.js +148 -0
- package/dist/chain/receipt.d.ts +24 -0
- package/dist/chain/receipt.js +82 -0
- package/dist/chain/registeredAgent.d.ts +68 -3
- package/dist/chain/registeredAgent.js +143 -42
- package/dist/chain/registeredOperation.d.ts +10 -1
- package/dist/chain/registeredOperation.js +18 -3
- package/dist/chain/registeredPaidAgent.d.ts +254 -0
- package/dist/chain/registeredPaidAgent.js +889 -0
- package/dist/chain/registeredRelay.d.ts +31 -1
- package/dist/chain/registeredRelay.js +164 -43
- package/dist/chain/relayVoucher.d.ts +64 -0
- package/dist/chain/relayVoucher.js +69 -0
- package/dist/chain/reservation.d.ts +239 -0
- package/dist/chain/reservation.js +746 -0
- package/dist/chain/reshareRoster.d.ts +64 -0
- package/dist/chain/reshareRoster.js +85 -0
- package/dist/chain/revertReason.d.ts +8 -0
- package/dist/chain/revertReason.js +2 -1
- package/dist/chain/rotationLock.d.ts +130 -0
- package/dist/chain/rotationLock.js +168 -0
- package/dist/chain/serviceRequestPolicy.d.ts +47 -0
- package/dist/chain/serviceRequestPolicy.js +86 -0
- package/dist/chain/services.d.ts +7 -0
- package/dist/chain/services.js +44 -4
- package/dist/chain/slotClient.js +11 -2
- package/dist/chain/slotHandoff.d.ts +81 -0
- package/dist/chain/slotHandoff.js +166 -0
- package/dist/chain/slotSeed.d.ts +47 -5
- package/dist/chain/slotSeed.js +173 -42
- package/dist/chain/verifierSnapshot.d.ts +36 -0
- package/dist/chain/verifierSnapshot.js +197 -0
- package/dist/chain/write.d.ts +111 -21
- package/dist/chain/write.js +378 -146
- package/dist/committee/blsSharing.d.ts +53 -0
- package/dist/committee/blsSharing.js +90 -0
- package/dist/committee/client.d.ts +62 -23
- package/dist/committee/client.js +288 -72
- package/dist/committee/dual-operation.d.ts +165 -0
- package/dist/committee/dual-operation.js +229 -0
- package/dist/committee/dual-sign.d.ts +26 -1
- package/dist/committee/dual-sign.js +85 -7
- package/dist/committee/ecdsa.d.ts +38 -0
- package/dist/committee/ecdsa.js +87 -15
- package/dist/committee/evidence.d.ts +30 -0
- package/dist/committee/evidence.js +65 -0
- package/dist/committee/execution.d.ts +414 -0
- package/dist/committee/execution.js +446 -0
- package/dist/committee/extraction.js +33 -26
- package/dist/committee/index.d.ts +30 -7
- package/dist/committee/index.js +18 -6
- package/dist/committee/keeperExecution.d.ts +37 -0
- package/dist/committee/keeperExecution.js +141 -0
- package/dist/committee/oauth.d.ts +14 -4
- package/dist/committee/oauth.js +17 -5
- package/dist/committee/payment.d.ts +369 -0
- package/dist/committee/payment.js +339 -0
- package/dist/committee/recovery.d.ts +136 -0
- package/dist/committee/recovery.js +204 -0
- package/dist/committee/recoveryJson.d.ts +2 -0
- package/dist/committee/recoveryJson.js +87 -0
- package/dist/committee/request.d.ts +63 -27
- package/dist/committee/request.js +77 -66
- package/dist/committee/session-grant.d.ts +320 -0
- package/dist/committee/session-grant.js +397 -0
- package/dist/committee/status-refresh.d.ts +257 -0
- package/dist/committee/status-refresh.js +619 -0
- package/dist/committee/token.d.ts +163 -15
- package/dist/committee/token.js +247 -10
- package/dist/crypto/bn254.d.ts +70 -0
- package/dist/crypto/bn254.js +222 -0
- package/dist/crypto/ibe.d.ts +32 -0
- package/dist/crypto/ibe.js +56 -8
- package/dist/crypto/index.d.ts +1 -1
- package/dist/crypto/index.js +1 -1
- package/dist/crypto/kem.d.ts +31 -0
- package/dist/crypto/kem.js +113 -7
- package/dist/crypto/recipient.d.ts +75 -0
- package/dist/crypto/recipient.js +107 -0
- package/dist/decryption/client.d.ts +10 -16
- package/dist/decryption/client.js +8 -76
- package/dist/decryption/index.d.ts +2 -0
- package/dist/decryption/index.js +2 -0
- package/dist/decryption/sealed.d.ts +72 -0
- package/dist/decryption/sealed.js +147 -0
- package/dist/decryption/session.d.ts +115 -0
- package/dist/decryption/session.js +358 -0
- package/dist/errors.d.ts +406 -1
- package/dist/errors.js +400 -5
- package/dist/index.d.ts +9 -2
- package/dist/index.js +6 -1
- package/dist/internal/bounded.d.ts +66 -0
- package/dist/internal/bounded.js +126 -0
- package/dist/internal/network.d.ts +4 -0
- package/dist/internal/network.js +40 -0
- package/dist/internal/retryAfter.d.ts +8 -0
- package/dist/internal/retryAfter.js +28 -0
- package/dist/internal/sleep.d.ts +6 -0
- package/dist/internal/sleep.js +15 -0
- package/dist/internal/typedData.d.ts +13 -0
- package/dist/internal/typedData.js +77 -0
- package/dist/internal/viemErrors.d.ts +26 -0
- package/dist/internal/viemErrors.js +49 -0
- package/dist/oid4vp/binding.d.ts +27 -1
- package/dist/oid4vp/binding.js +36 -1
- package/dist/oid4vp/jose.d.ts +4 -2
- package/dist/oid4vp/jose.js +39 -7
- package/dist/oid4vp/request-object.d.ts +61 -4
- package/dist/oid4vp/request-object.js +140 -5
- package/dist/oid4vp/verifier-agent.d.ts +18 -8
- package/dist/oid4vp/verifier-agent.js +48 -6
- package/dist/oid4vp/wallet.d.ts +2 -4
- package/dist/oid4vp/wallet.js +1 -0
- package/dist/retry.d.ts +78 -0
- package/dist/retry.js +137 -0
- package/dist/signing/frost.d.ts +1 -1
- package/dist/verifier-agent/index.d.ts +41 -5
- package/dist/verifier-agent/index.js +124 -9
- package/dist/verifier-agent/payment.d.ts +7 -0
- package/dist/verifier-agent/payment.js +17 -0
- package/docs/api.md +8 -2
- package/docs/application-api.md +25 -2
- package/docs/chain.md +155 -9
- package/docs/consumer-migrations.md +61 -0
- package/docs/encrypted-notes.md +3 -2
- package/docs/encryption.md +4 -2
- package/docs/errors.md +14 -1
- package/docs/flows.md +2 -2
- package/docs/funding.md +902 -0
- package/docs/native-approvals.md +63 -0
- package/docs/reference/README.md +9 -8
- package/docs/reference/app-browser.md +232 -0
- package/docs/reference/app-node.md +38 -8
- package/docs/reference/app.md +4621 -805
- package/docs/reference/chain-node.md +74 -16
- package/docs/reference/chain.md +6740 -1592
- package/docs/reference/committee.md +5630 -987
- package/docs/reference/main.md +1439 -140
- package/docs/reference/oid4vp.md +297 -144
- package/docs/reference/verifier-agent.md +77 -35
- package/docs/signing.md +6 -0
- package/examples/encrypted-notes.ts +21 -6
- package/examples/getting-started.ts +2 -7
- package/examples/live-config.ts +24 -17
- package/package.json +17 -5
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
// Custody health of a slot (network ADR-0099 D5): what each keeper of the committee says about its
|
|
2
|
+
// own share, verified against the operator's REGISTERED identity key, plus the committee's state
|
|
3
|
+
// read from the chain.
|
|
4
|
+
//
|
|
5
|
+
// A keeper answers `GET /v1/keys/:id/custody-health` with a JSON body and an `attestation`: a
|
|
6
|
+
// statement signed by its operator identity key (ed25519) over `custodyStatementHash`. Only the
|
|
7
|
+
// statement is signed. The SDK therefore:
|
|
8
|
+
// - verifies the signature under the key NodeRegistry holds for the polled operator, never the
|
|
9
|
+
// `pubkey` the reply names;
|
|
10
|
+
// - refuses an unsigned, malformed, stale or mismatched reply with a typed `CustodyHealthError`;
|
|
11
|
+
// - returns only signed fields, and derives the committee's liveness, margin and rotation lock
|
|
12
|
+
// from its own chain reads, never from the reply's unsigned body.
|
|
13
|
+
// The hash mirrors `keykeeper_committee::custody_health::custody_statement_hash` byte for byte.
|
|
14
|
+
import { ed25519 } from '@noble/curves/ed25519';
|
|
15
|
+
import { keccak_256 } from '@noble/hashes/sha3';
|
|
16
|
+
import { concatBytes, utf8ToBytes } from '@noble/hashes/utils';
|
|
17
|
+
import { bytesToHex, getAddress, hexToBytes, isAddress, keccak256, toHex } from 'viem';
|
|
18
|
+
import { TasraError } from '../errors.js';
|
|
19
|
+
import { resolveKeeperMembers, withNetworkDeadline } from '../internal/network.js';
|
|
20
|
+
import { viemErrorChainHas } from '../internal/viemErrors.js';
|
|
21
|
+
import { keyRegistryAbi } from './abis/keyRegistry.js';
|
|
22
|
+
import { nodeRegistryAbi } from './abis/nodeRegistry.js';
|
|
23
|
+
import { chainIdOf } from './chainId.js';
|
|
24
|
+
import { requireAddress } from './deployments.js';
|
|
25
|
+
import { ROTATION_LOCK_SENTINEL } from './rotationLock.js';
|
|
26
|
+
/** Domain tag of {@link custodyStatementHash}; a changed preimage gets a new name on the network. */
|
|
27
|
+
export const CUSTODY_HEALTH_DOMAIN = 'keykeeper-committee/custody-health/v1';
|
|
28
|
+
/** Default maximum age of a statement, in seconds; the keepers count a peer's statement for 900 s. */
|
|
29
|
+
export const CUSTODY_STATEMENT_MAX_AGE_SECS = 900;
|
|
30
|
+
/** Largest custody-health reply read from a keeper, in bytes. */
|
|
31
|
+
const MAX_REPLY_BYTES = 64 * 1024;
|
|
32
|
+
/** NodeRegistry keeper tag, `keccak256("keykeeper")`: a live committee member is an active keeper. */
|
|
33
|
+
const KEEPER_TAG = keccak256(toHex('keykeeper'));
|
|
34
|
+
const RESHARE_STATES = ['current', 'pending', 'not_member', 'no_key', 'unknown'];
|
|
35
|
+
/** A custody-health reply that was not counted, or a slot that could not be read. */
|
|
36
|
+
export class CustodyHealthError extends TasraError {
|
|
37
|
+
/** Refusal category; never infer it from the message. */
|
|
38
|
+
code;
|
|
39
|
+
/** Operator whose reply was refused, when the refusal is about one keeper. */
|
|
40
|
+
operator;
|
|
41
|
+
constructor(code, message, opts = {}) {
|
|
42
|
+
super(message, { cause: opts.cause, retryable: code === 'unreachable' || code === 'stale' });
|
|
43
|
+
this.code = code;
|
|
44
|
+
if (opts.operator !== undefined)
|
|
45
|
+
this.operator = opts.operator;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function u64(v) {
|
|
49
|
+
const out = new Uint8Array(8);
|
|
50
|
+
new DataView(out.buffer).setBigUint64(0, BigInt(v));
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
function lengthPrefixed(b) {
|
|
54
|
+
return concatBytes(u64(b.length), b);
|
|
55
|
+
}
|
|
56
|
+
function optU64(v) {
|
|
57
|
+
return v === null ? new Uint8Array([0]) : concatBytes(new Uint8Array([1]), u64(v));
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* `keccak256(domain || fields)`, every field fixed-width or length-prefixed and every optional
|
|
61
|
+
* field tagged: the 32 bytes a keeper signs. Identical to the network's `custody_statement_hash`.
|
|
62
|
+
* @param s Statement to hash; integers must be non-negative safe integers.
|
|
63
|
+
*/
|
|
64
|
+
export function custodyStatementHash(s) {
|
|
65
|
+
const failure = s.lastFailure === null
|
|
66
|
+
? new Uint8Array([0])
|
|
67
|
+
: concatBytes(new Uint8Array([1]), u64(s.lastFailure.committeeVersion), optU64(s.lastFailure.blamedOperatorId), lengthPrefixed(utf8ToBytes(s.lastFailure.reason)));
|
|
68
|
+
return keccak_256(concatBytes(utf8ToBytes(CUSTODY_HEALTH_DOMAIN), u64(s.chainId), hexToBytes(s.slot), hexToBytes(s.operator), u64(s.epoch), u64(s.committeeVersion), lengthPrefixed(hexToBytes(s.publicKey)), lengthPrefixed(utf8ToBytes(s.reshare)), optU64(s.shareCommitteeVersion), optU64(s.shareMatchesChainKey === null ? null : Number(s.shareMatchesChainKey)), optU64(s.retainedGenerations), failure, u64(s.observedAt)));
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Whether `signature` is the operator's ed25519 signature over the statement. Take `publicKey`
|
|
72
|
+
* from NodeRegistry for `statement.operator`, never from the reply.
|
|
73
|
+
* @param statement Statement as parsed from the reply.
|
|
74
|
+
* @param publicKey The operator's registered 32-byte identity key.
|
|
75
|
+
* @param signature 64-byte signature from the reply.
|
|
76
|
+
*/
|
|
77
|
+
export function verifyCustodyStatement(statement, publicKey, signature) {
|
|
78
|
+
if (publicKey.length !== 32 || signature.length !== 64)
|
|
79
|
+
return false;
|
|
80
|
+
try {
|
|
81
|
+
return ed25519.verify(signature, custodyStatementHash(statement), publicKey, { zip215: false });
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const malformed = (message, operator) => new CustodyHealthError('malformed', message, operator ? { operator } : {});
|
|
88
|
+
function record(v, what, keys, required, operator) {
|
|
89
|
+
if (typeof v !== 'object' || v === null || Array.isArray(v))
|
|
90
|
+
throw malformed(`custody-health ${what} is not an object`, operator);
|
|
91
|
+
const r = v;
|
|
92
|
+
const unknown = Object.keys(r).find(k => !keys.includes(k));
|
|
93
|
+
if (unknown !== undefined)
|
|
94
|
+
throw malformed(`custody-health ${what} carries an unsigned field ${JSON.stringify(unknown)}`, operator);
|
|
95
|
+
const missing = required.find(k => !(k in r));
|
|
96
|
+
if (missing !== undefined)
|
|
97
|
+
throw malformed(`custody-health ${what} lacks ${missing}`, operator);
|
|
98
|
+
return r;
|
|
99
|
+
}
|
|
100
|
+
function int(v, field, max = Number.MAX_SAFE_INTEGER) {
|
|
101
|
+
if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < 0 || v > max)
|
|
102
|
+
throw malformed(`custody statement ${field} is not an integer in range`);
|
|
103
|
+
return v;
|
|
104
|
+
}
|
|
105
|
+
function optInt(v, field, max) {
|
|
106
|
+
return v === undefined || v === null ? null : int(v, field, max);
|
|
107
|
+
}
|
|
108
|
+
function hex(v, field, bytes) {
|
|
109
|
+
if (typeof v !== 'string' || !/^0x(?:[0-9a-fA-F]{2})*$/.test(v) || (bytes !== undefined && v.length !== 2 + bytes * 2)) {
|
|
110
|
+
throw malformed(`custody statement ${field} is not ${bytes === undefined ? 'hex' : `${bytes} bytes of hex`}`);
|
|
111
|
+
}
|
|
112
|
+
return v.toLowerCase();
|
|
113
|
+
}
|
|
114
|
+
const STATEMENT_KEYS = ['chain_id', 'slot', 'operator', 'epoch', 'committee_version', 'public_key', 'reshare', 'share_committee_version',
|
|
115
|
+
'share_matches_chain_key', 'retained_generations', 'last_failure', 'observed_at'];
|
|
116
|
+
const STATEMENT_REQUIRED = ['chain_id', 'slot', 'operator', 'epoch', 'committee_version', 'public_key', 'reshare', 'observed_at'];
|
|
117
|
+
/**
|
|
118
|
+
* Parse a statement as the network serializes it (snake case). Refuses unknown fields: they would
|
|
119
|
+
* not be covered by the signature. Throws `CustodyHealthError` with code `malformed`.
|
|
120
|
+
* @param raw The `attestation.statement` value of a reply.
|
|
121
|
+
*/
|
|
122
|
+
export function parseCustodyStatement(raw) {
|
|
123
|
+
const r = record(raw, 'statement', STATEMENT_KEYS, STATEMENT_REQUIRED);
|
|
124
|
+
if (typeof r.reshare !== 'string' || !RESHARE_STATES.includes(r.reshare))
|
|
125
|
+
throw malformed('custody statement reshare is not a known state');
|
|
126
|
+
const matches = r.share_matches_chain_key;
|
|
127
|
+
if (matches !== undefined && matches !== null && typeof matches !== 'boolean')
|
|
128
|
+
throw malformed('custody statement share_matches_chain_key is not a boolean');
|
|
129
|
+
let lastFailure = null;
|
|
130
|
+
if (r.last_failure !== undefined && r.last_failure !== null) {
|
|
131
|
+
const f = record(r.last_failure, 'last_failure', ['committee_version', 'blamed_operator_id', 'reason'], ['committee_version', 'reason']);
|
|
132
|
+
if (typeof f.reason !== 'string')
|
|
133
|
+
throw malformed('custody statement last_failure.reason is not a string');
|
|
134
|
+
lastFailure = { committeeVersion: int(f.committee_version, 'last_failure.committee_version'),
|
|
135
|
+
blamedOperatorId: optInt(f.blamed_operator_id, 'last_failure.blamed_operator_id', 0xffff), reason: f.reason };
|
|
136
|
+
}
|
|
137
|
+
return {
|
|
138
|
+
chainId: int(r.chain_id, 'chain_id'), slot: hex(r.slot, 'slot', 32), operator: hex(r.operator, 'operator', 20),
|
|
139
|
+
epoch: int(r.epoch, 'epoch'), committeeVersion: int(r.committee_version, 'committee_version'), publicKey: hex(r.public_key, 'public_key'),
|
|
140
|
+
reshare: r.reshare, shareCommitteeVersion: optInt(r.share_committee_version, 'share_committee_version'),
|
|
141
|
+
shareMatchesChainKey: (matches ?? null), retainedGenerations: optInt(r.retained_generations, 'retained_generations'),
|
|
142
|
+
lastFailure, observedAt: int(r.observed_at, 'observed_at'),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
const same = (a, b) => a.toLowerCase() === b.toLowerCase();
|
|
146
|
+
/** Compare an unsigned reply field with its signed counterpart; absent is fine, different is not. */
|
|
147
|
+
function agrees(body, s) {
|
|
148
|
+
const chain = typeof body.chain === 'object' && body.chain !== null ? body.chain : {};
|
|
149
|
+
const failure = body.last_failure;
|
|
150
|
+
const checks = [
|
|
151
|
+
['slot', typeof body.slot === 'string' ? body.slot.toLowerCase() : body.slot, s.slot],
|
|
152
|
+
['reshare', body.reshare, s.reshare],
|
|
153
|
+
['observed_at', body.observed_at, s.observedAt],
|
|
154
|
+
['chain.epoch', chain.epoch, s.epoch],
|
|
155
|
+
['chain.committee_version', chain.committee_version, s.committeeVersion],
|
|
156
|
+
['chain.public_key', typeof chain.public_key === 'string' ? chain.public_key.toLowerCase() : chain.public_key, s.publicKey],
|
|
157
|
+
];
|
|
158
|
+
for (const [field, unsigned, signed] of checks)
|
|
159
|
+
if (unsigned !== undefined && unsigned !== signed)
|
|
160
|
+
return field;
|
|
161
|
+
if (failure !== undefined) {
|
|
162
|
+
const f = s.lastFailure;
|
|
163
|
+
const differs = failure === null ? f !== null
|
|
164
|
+
: !f || failure.committee_version !== f.committeeVersion || (failure.blamed_operator_id ?? null) !== f.blamedOperatorId || failure.reason !== f.reason;
|
|
165
|
+
if (differs)
|
|
166
|
+
return 'last_failure';
|
|
167
|
+
}
|
|
168
|
+
return undefined;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Verify one keeper's custody-health reply and return its signed statement. Refused, as a
|
|
172
|
+
* `CustodyHealthError`: `unsigned` (no attestation), `malformed`, `mismatch` (another chain, slot
|
|
173
|
+
* or operator, a key other than the registered one, or an unsigned field that contradicts the
|
|
174
|
+
* signed statement), `bad-signature`, and `stale` (older or newer than the allowed age).
|
|
175
|
+
* @param reply The parsed JSON reply.
|
|
176
|
+
* @param expected What the reply must be about and the operator's registered key.
|
|
177
|
+
*/
|
|
178
|
+
export function verifyCustodyHealthReply(reply, expected) {
|
|
179
|
+
if (!isAddress(expected.operator, { strict: false }))
|
|
180
|
+
throw new TasraError(`custody-health: operator ${JSON.stringify(expected.operator)} is not an address`);
|
|
181
|
+
const operator = getAddress(expected.operator);
|
|
182
|
+
if (typeof reply !== 'object' || reply === null || Array.isArray(reply))
|
|
183
|
+
throw malformed('custody-health reply is not an object', operator);
|
|
184
|
+
const body = reply;
|
|
185
|
+
if (body.attestation === undefined || body.attestation === null) {
|
|
186
|
+
throw new CustodyHealthError('unsigned', `custody-health reply of ${operator} carries no signed attestation; it is not counted`, { operator });
|
|
187
|
+
}
|
|
188
|
+
const registered = typeof expected.registeredPublicKey === 'string' ? hexToBytes(expected.registeredPublicKey) : expected.registeredPublicKey;
|
|
189
|
+
if (registered.length !== 32)
|
|
190
|
+
throw new TasraError(`custody-health: the registered key of ${operator} is not 32 bytes`);
|
|
191
|
+
let statement, signature, claimedKey;
|
|
192
|
+
try {
|
|
193
|
+
const att = record(body.attestation, 'attestation', ['statement', 'pubkey', 'signature'], ['statement', 'pubkey', 'signature']);
|
|
194
|
+
statement = parseCustodyStatement(att.statement);
|
|
195
|
+
signature = hexToBytes(hex(att.signature, 'signature', 64));
|
|
196
|
+
claimedKey = hex(att.pubkey, 'pubkey', 32);
|
|
197
|
+
}
|
|
198
|
+
catch (e) {
|
|
199
|
+
if (e instanceof CustodyHealthError)
|
|
200
|
+
throw new CustodyHealthError(e.code, `${e.message} (operator ${operator})`, { operator, cause: e });
|
|
201
|
+
throw e;
|
|
202
|
+
}
|
|
203
|
+
const mismatch = (what) => new CustodyHealthError('mismatch', `custody-health reply of ${operator}: ${what}`, { operator });
|
|
204
|
+
if (statement.chainId !== expected.chainId)
|
|
205
|
+
throw mismatch(`statement names chain ${statement.chainId}, not ${expected.chainId}`);
|
|
206
|
+
if (!same(statement.slot, expected.slotId))
|
|
207
|
+
throw mismatch(`statement names slot ${statement.slot}, not ${expected.slotId}`);
|
|
208
|
+
if (!same(statement.operator, operator))
|
|
209
|
+
throw mismatch(`statement names operator ${statement.operator}`);
|
|
210
|
+
if (!same(claimedKey, bytesToHex(registered)))
|
|
211
|
+
throw mismatch('it names an identity key other than the one NodeRegistry holds for the operator');
|
|
212
|
+
if (!verifyCustodyStatement(statement, registered, signature)) {
|
|
213
|
+
throw new CustodyHealthError('bad-signature', `custody-health statement of ${operator} does not verify under its registered key`, { operator });
|
|
214
|
+
}
|
|
215
|
+
const now = expected.nowSecs ?? Math.floor(Date.now() / 1000);
|
|
216
|
+
const maxAge = expected.maxAgeSecs ?? CUSTODY_STATEMENT_MAX_AGE_SECS;
|
|
217
|
+
if (Math.abs(now - statement.observedAt) > maxAge) {
|
|
218
|
+
throw new CustodyHealthError('stale', `custody-health statement of ${operator} was made at ${statement.observedAt}, more than ${maxAge}s from ${now}`, { operator });
|
|
219
|
+
}
|
|
220
|
+
const field = agrees(body, statement);
|
|
221
|
+
if (field)
|
|
222
|
+
throw mismatch(`its unsigned ${field} contradicts the signed statement`);
|
|
223
|
+
return { operator, statement };
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Whether a verified statement proves the keeper holds a share of the chain's current generation:
|
|
227
|
+
* `current`, a share of the chain's key, at the chain's committee version. The rule the keepers
|
|
228
|
+
* apply before retiring old shares.
|
|
229
|
+
* @param s A verified statement.
|
|
230
|
+
* @param chain The chain's committee version and public key.
|
|
231
|
+
*/
|
|
232
|
+
export function custodyStatementIsCurrent(s, chain) {
|
|
233
|
+
return s.reshare === 'current' && s.shareMatchesChainKey === true && s.shareCommitteeVersion === chain.committeeVersion
|
|
234
|
+
&& s.committeeVersion === chain.committeeVersion && same(s.publicKey, chain.publicKey);
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Classify a committee by its live members: `frozen` below `k`, `ok` when all are live or more
|
|
238
|
+
* than one above `k`, `at_risk` otherwise. The keepers' reshare monitor rule with a margin of one.
|
|
239
|
+
* @param live Live committee members.
|
|
240
|
+
* @param k Signing threshold.
|
|
241
|
+
* @param n Committee size.
|
|
242
|
+
*/
|
|
243
|
+
export function assessCustodyHealth(live, k, n) {
|
|
244
|
+
if (live < k)
|
|
245
|
+
return 'frozen';
|
|
246
|
+
if (live >= n)
|
|
247
|
+
return 'ok';
|
|
248
|
+
return live <= k + 1 ? 'at_risk' : 'ok';
|
|
249
|
+
}
|
|
250
|
+
async function readBounded(response, signal) {
|
|
251
|
+
if (Number(response.headers.get('content-length')) > MAX_REPLY_BYTES) {
|
|
252
|
+
void response.body?.cancel().catch(() => { });
|
|
253
|
+
throw new Error(`reply exceeds ${MAX_REPLY_BYTES} bytes`);
|
|
254
|
+
}
|
|
255
|
+
const reader = response.body?.getReader();
|
|
256
|
+
if (!reader)
|
|
257
|
+
return '';
|
|
258
|
+
const chunks = [];
|
|
259
|
+
let size = 0;
|
|
260
|
+
const cancel = () => { void reader.cancel().catch(() => { }); };
|
|
261
|
+
signal.addEventListener('abort', cancel, { once: true });
|
|
262
|
+
try {
|
|
263
|
+
for (;;) {
|
|
264
|
+
const { done, value } = await reader.read();
|
|
265
|
+
if (done)
|
|
266
|
+
break;
|
|
267
|
+
size += value.length;
|
|
268
|
+
if (size > MAX_REPLY_BYTES) {
|
|
269
|
+
cancel();
|
|
270
|
+
throw new Error(`reply exceeds ${MAX_REPLY_BYTES} bytes`);
|
|
271
|
+
}
|
|
272
|
+
chunks.push(value);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
finally {
|
|
276
|
+
signal.removeEventListener('abort', cancel);
|
|
277
|
+
}
|
|
278
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(concatBytes(...chunks));
|
|
279
|
+
}
|
|
280
|
+
function endpoint(url, chainId, allowLocalHttp) {
|
|
281
|
+
const u = new URL(url);
|
|
282
|
+
const local = ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname);
|
|
283
|
+
if (u.username || u.password || u.search || u.hash || (u.protocol !== 'https:' && !(u.protocol === 'http:' && allowLocalHttp && chainId === 43112 && local))) {
|
|
284
|
+
throw new Error('keeper endpoint violates the transport policy (HTTPS only; loopback HTTP only on chain 43112 when allowed)');
|
|
285
|
+
}
|
|
286
|
+
return u.toString().replace(/\/$/, '');
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Poll every assigned keeper of a slot for its custody health and verify each reply against the
|
|
290
|
+
* operator's registered identity key. The committee's liveness, margin, health and rotation lock
|
|
291
|
+
* come from the SDK's own chain reads; the keepers contribute only their signed statements.
|
|
292
|
+
* A keeper whose reply is refused is listed in `refused` and never counted. Refuses `no-slot`.
|
|
293
|
+
* @param chain Reader for the deployment that owns the slot.
|
|
294
|
+
* @param slotId Slot to poll.
|
|
295
|
+
* @param options Expected chain, transport, cancellation and freshness policy.
|
|
296
|
+
*/
|
|
297
|
+
export async function readCustodyHealth(chain, slotId, options = {}) {
|
|
298
|
+
const read = chain.client.readContract;
|
|
299
|
+
const keyRegistry = requireAddress(chain.addresses, 'KeyRegistry'), nodeRegistry = requireAddress(chain.addresses, 'NodeRegistry');
|
|
300
|
+
const chainId = options.chainId ?? await chainIdOf(chain.client);
|
|
301
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
302
|
+
const slot = await read({ address: keyRegistry, abi: keyRegistryAbi, functionName: 'getKeySlot', args: [slotId] });
|
|
303
|
+
if (!slot.exists)
|
|
304
|
+
throw new CustodyHealthError('no-slot', `slot ${slotId} does not exist on this KeyRegistry; check the slot id and the network`);
|
|
305
|
+
const mode = Number(slot.mode);
|
|
306
|
+
let rotationLocked;
|
|
307
|
+
try {
|
|
308
|
+
const last = await read({ address: keyRegistry, abi: keyRegistryAbi, functionName: 'lastRotatedAt', args: [slotId] });
|
|
309
|
+
rotationLocked = last === ROTATION_LOCK_SENTINEL || mode === 2 || mode === 4;
|
|
310
|
+
}
|
|
311
|
+
catch (e) {
|
|
312
|
+
if (!viemErrorChainHas(e, ['ContractFunctionRevertedError', 'ContractFunctionZeroDataError']))
|
|
313
|
+
throw e;
|
|
314
|
+
rotationLocked = null;
|
|
315
|
+
}
|
|
316
|
+
const assigned = await read({ address: keyRegistry, abi: keyRegistryAbi, functionName: 'assignedNodes', args: [slotId] });
|
|
317
|
+
const k = Number(slot.threshold.k), n = Number(slot.threshold.n);
|
|
318
|
+
const chainView = { mode, publicKey: slot.publicKey.toLowerCase(), epoch: Number(slot.epoch), committeeVersion: Number(slot.committeeVersion),
|
|
319
|
+
k, n, cancelled: slot.cancelled, rotationLocked };
|
|
320
|
+
const outcomes = await withNetworkDeadline(signal => resolveKeeperMembers(assigned, async (member) => {
|
|
321
|
+
const operator = getAddress(member);
|
|
322
|
+
const [node, tagged] = await Promise.all([
|
|
323
|
+
read({ address: nodeRegistry, abi: nodeRegistryAbi, functionName: 'nodeOf', args: [operator] }),
|
|
324
|
+
read({ address: nodeRegistry, abi: nodeRegistryAbi, functionName: 'hasTag', args: [operator, KEEPER_TAG] }),
|
|
325
|
+
]);
|
|
326
|
+
const live = node.active && tagged;
|
|
327
|
+
if (!node.active || !/^0x[0-9a-fA-F]{64}$/.test(node.pubkey)) {
|
|
328
|
+
return { operator, live, error: new CustodyHealthError('not-registered', `${operator} is not an active registered operator; its reply would not be counted`, { operator }) };
|
|
329
|
+
}
|
|
330
|
+
let body;
|
|
331
|
+
try {
|
|
332
|
+
const base = endpoint(options.route ? options.route(node.url) : node.url, chainId, options.allowLocalHttp === true);
|
|
333
|
+
const response = await fetchImpl(`${base}/v1/keys/${slotId}/custody-health`, { signal, redirect: 'error', credentials: 'omit' });
|
|
334
|
+
const text = await readBounded(response, signal);
|
|
335
|
+
if (!response.ok)
|
|
336
|
+
throw new Error(`HTTP ${response.status}`);
|
|
337
|
+
body = JSON.parse(text);
|
|
338
|
+
}
|
|
339
|
+
catch (e) {
|
|
340
|
+
signal.throwIfAborted();
|
|
341
|
+
return { operator, live, error: new CustodyHealthError('unreachable', `custody-health of ${operator} could not be read: ${e instanceof Error ? e.message : String(e)}`, { operator, cause: e }) };
|
|
342
|
+
}
|
|
343
|
+
try {
|
|
344
|
+
return { operator, live, report: verifyCustodyHealthReply(body, { chainId, slotId, operator, registeredPublicKey: node.pubkey,
|
|
345
|
+
nowSecs: options.nowSecs, maxAgeSecs: options.maxAgeSecs }) };
|
|
346
|
+
}
|
|
347
|
+
catch (e) {
|
|
348
|
+
if (!(e instanceof CustodyHealthError))
|
|
349
|
+
throw e;
|
|
350
|
+
return { operator, live, error: e };
|
|
351
|
+
}
|
|
352
|
+
}, signal), options.signal);
|
|
353
|
+
const liveMembers = outcomes.filter(o => o.live).length;
|
|
354
|
+
const reports = outcomes.flatMap(o => o.report ? [o.report] : []);
|
|
355
|
+
const current = reports.filter(r => custodyStatementIsCurrent(r.statement, chainView)).map(r => r.operator);
|
|
356
|
+
return {
|
|
357
|
+
slotId, chainId, chain: chainView,
|
|
358
|
+
committee: { members: assigned.length, liveMembers, margin: liveMembers - k, notLive: outcomes.filter(o => !o.live).map(o => o.operator) },
|
|
359
|
+
health: assessCustodyHealth(liveMembers, k, n),
|
|
360
|
+
current, proven: current.length >= k,
|
|
361
|
+
pending: reports.filter(r => r.statement.reshare === 'pending').map(r => r.operator),
|
|
362
|
+
reports,
|
|
363
|
+
refused: outcomes.flatMap(o => o.error ? [{ operator: o.operator, error: o.error }] : []),
|
|
364
|
+
};
|
|
365
|
+
}
|
|
@@ -177,6 +177,8 @@ const ENV_ALIASES = {
|
|
|
177
177
|
VERIFIER_SET_REGISTRY: 'VerifierSetRegistry',
|
|
178
178
|
ACCOUNTANT_SET_REGISTRY: 'AccountantSetRegistry',
|
|
179
179
|
KEEPER_SHARE_REGISTRY: 'KeeperShareRegistry',
|
|
180
|
+
// Separate immutable slasher for prepaid payout faults (not an AccountantSlashing alias).
|
|
181
|
+
PREPAID_FAULT_ORACLE: 'PrepaidFaultOracle',
|
|
180
182
|
PLATFORM_EXECUTOR: 'PlatformExecutor',
|
|
181
183
|
PRICE_ORACLE: 'FixedTasraPriceOracle',
|
|
182
184
|
EURC: 'MockEurc',
|
package/dist/chain/events.js
CHANGED
|
@@ -34,6 +34,8 @@ export const CONTRACT_CATEGORY = {
|
|
|
34
34
|
// governance: what it anchors is who held a settle shard at epoch E, which
|
|
35
35
|
// is what the wrong-bundle witness reads before slashing a settlement.
|
|
36
36
|
AccountantSetRegistry: 'settlement',
|
|
37
|
+
// Threshold-signed prepaid payout fault verdicts; each resolution slashes through NodeRegistry.
|
|
38
|
+
PrepaidFaultOracle: 'slashing',
|
|
37
39
|
};
|
|
38
40
|
// A few events live on a "node" contract but are conceptually slashing - the
|
|
39
41
|
// Slashing Center surfaces them alongside the dedicated oracle verdicts.
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { Hex, PublicClient } from 'viem';
|
|
2
|
+
import type { PinnedBlock } from './pinnedReads.js';
|
|
3
|
+
/** A followed header. */
|
|
4
|
+
export interface FollowedHead extends PinnedBlock {
|
|
5
|
+
/** Hash of the parent block. */
|
|
6
|
+
parentHash: Hex;
|
|
7
|
+
}
|
|
8
|
+
/** Head follower options. */
|
|
9
|
+
export interface HeadFollowerOptions {
|
|
10
|
+
/** `instant` (an accepted block never reorganizes: Avalanche C-Chain) lets `isCanonical` answer; default `probabilistic` (it never does). */
|
|
11
|
+
finality?: 'instant' | 'probabilistic';
|
|
12
|
+
/** Headers held, 2..1024 (default 64); also the deepest reorg or gap it links back. */
|
|
13
|
+
window?: number;
|
|
14
|
+
/** A follower whose tip no head or poll confirmed for this long is not live (default and maximum 2000 ms). */
|
|
15
|
+
liveAfterMs?: number;
|
|
16
|
+
/** Opt-in: also refuse a tip whose block timestamp is older than this (1..2000 ms; default off). */
|
|
17
|
+
maxTipAgeMs?: number;
|
|
18
|
+
/** Poll interval on HTTP transports, below `liveAfterMs` (default min(1000, liveAfterMs / 2) ms). WebSocket transports subscribe instead. */
|
|
19
|
+
pollMs?: number;
|
|
20
|
+
/** Clock in ms (tests). */
|
|
21
|
+
now?: () => number;
|
|
22
|
+
}
|
|
23
|
+
/** A started (or startable) head follower for one client. */
|
|
24
|
+
export interface HeadFollower {
|
|
25
|
+
/** The finality the deployment was declared with. */
|
|
26
|
+
readonly finality: 'instant' | 'probabilistic';
|
|
27
|
+
/** The newest header while live, otherwise undefined. */
|
|
28
|
+
tip(): FollowedHead | undefined;
|
|
29
|
+
/** True only when `at` is provably canonical (see module comment); false or undefined means: recheck by RPC. */
|
|
30
|
+
isCanonical(at: PinnedBlock): boolean | undefined;
|
|
31
|
+
/** Whether a head or poll confirmed the tip within `liveAfterMs` (and, when opted in, its block is at most `maxTipAgeMs` old). */
|
|
32
|
+
live(): boolean;
|
|
33
|
+
/** Feed one header (the poller, a newHeads subscription or tests). Serialized; never throws. */
|
|
34
|
+
ingest(header: unknown): Promise<void>;
|
|
35
|
+
/** Feed the RPC's current `finalized` header (read beside `latest`). Serialized; never throws. */
|
|
36
|
+
ingestFinalized(header: unknown): Promise<void>;
|
|
37
|
+
/** Run `listener` after every new tip; returns the unsubscribe function. */
|
|
38
|
+
onHead(listener: (tip: FollowedHead) => void): () => void;
|
|
39
|
+
/**
|
|
40
|
+
* A block this process saw one of its own transactions mined in. Until the followed tip reaches
|
|
41
|
+
* it, `tip()` answers undefined (callers read the RPC head): an older tip cannot show that
|
|
42
|
+
* transaction's effects, so a read at it would contradict what the caller just observed.
|
|
43
|
+
*/
|
|
44
|
+
noteMinedBlock(blockNumber: bigint): void;
|
|
45
|
+
/** Number of gaps (unlinkable headers) seen; diagnostics only. */
|
|
46
|
+
gaps(): number;
|
|
47
|
+
/** Start polling (HTTP) or subscribing (WebSocket). Idempotent. */
|
|
48
|
+
start(): void;
|
|
49
|
+
/** Stop and forget every header. */
|
|
50
|
+
stop(): void;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Create a head follower for `client`. It does nothing until started or fed.
|
|
54
|
+
* @param client Trusted client of the deployment (the same RPC the operation reads).
|
|
55
|
+
* @param options Finality, window, liveness and polling.
|
|
56
|
+
*/
|
|
57
|
+
export declare function createHeadFollower(client: PublicClient, options?: HeadFollowerOptions): HeadFollower;
|
|
58
|
+
/**
|
|
59
|
+
* The follower attached to `client`, if any.
|
|
60
|
+
* @param client Client the follower was attached to.
|
|
61
|
+
*/
|
|
62
|
+
export declare function headFollowerOf(client: PublicClient): HeadFollower | undefined;
|
|
63
|
+
/**
|
|
64
|
+
* Follow `client`'s chain head: paid operations on this client then read block-pinned facts from
|
|
65
|
+
* the followed tip and its pre-reads, falling back to RPC whenever the follower cannot vouch.
|
|
66
|
+
* Replaces (and stops) a follower attached before. Returns the started follower.
|
|
67
|
+
* @param client Trusted client of the deployment.
|
|
68
|
+
* @param options Finality (declare `instant` only for a chain whose accepted blocks are final), window, liveness, polling.
|
|
69
|
+
*/
|
|
70
|
+
export declare function followHeads(client: PublicClient, options?: HeadFollowerOptions): HeadFollower;
|
|
71
|
+
/**
|
|
72
|
+
* Detach and stop the follower of `client`.
|
|
73
|
+
* @param client Client whose follower to stop.
|
|
74
|
+
*/
|
|
75
|
+
export declare function unfollowHeads(client: PublicClient): void;
|
|
76
|
+
/** Internal (tests and fixtures): attach an unstarted follower. */
|
|
77
|
+
export declare function attachHeadFollower(client: PublicClient, follower: HeadFollower): void;
|