@t3foundry/tasra-sdk 0.3.1-next.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.
Files changed (255) hide show
  1. package/CHANGELOG.md +1067 -28
  2. package/README.md +15 -0
  3. package/dist/app/approvals.d.ts +66 -4
  4. package/dist/app/approvals.js +153 -16
  5. package/dist/app/authorization.d.ts +1 -1
  6. package/dist/app/authorization.js +1 -1
  7. package/dist/app/browser.d.ts +63 -0
  8. package/dist/app/browser.js +242 -0
  9. package/dist/app/client.d.ts +114 -13
  10. package/dist/app/client.js +302 -76
  11. package/dist/app/identity.js +21 -9
  12. package/dist/app/index.d.ts +28 -3
  13. package/dist/app/index.js +16 -1
  14. package/dist/app/memory-store.d.ts +7 -0
  15. package/dist/app/memory-store.js +55 -0
  16. package/dist/app/node.d.ts +34 -6
  17. package/dist/app/node.js +387 -64
  18. package/dist/app/paid-allowance.d.ts +325 -0
  19. package/dist/app/paid-allowance.js +1290 -0
  20. package/dist/app/paid-approval.d.ts +122 -0
  21. package/dist/app/paid-approval.js +379 -0
  22. package/dist/app/paid-journal.d.ts +51 -0
  23. package/dist/app/paid-journal.js +117 -0
  24. package/dist/app/paid-keys.d.ts +12 -0
  25. package/dist/app/paid-keys.js +20 -0
  26. package/dist/app/paid-operation.d.ts +821 -0
  27. package/dist/app/paid-operation.js +1720 -0
  28. package/dist/app/paid-reservation.d.ts +157 -0
  29. package/dist/app/paid-reservation.js +323 -0
  30. package/dist/app/paid-session.d.ts +147 -0
  31. package/dist/app/paid-session.js +578 -0
  32. package/dist/app/payer-queue.d.ts +11 -0
  33. package/dist/app/payer-queue.js +27 -0
  34. package/dist/app/policy-bootstrap.d.ts +342 -0
  35. package/dist/app/policy-bootstrap.js +365 -0
  36. package/dist/app/policy-operation.d.ts +47 -0
  37. package/dist/app/policy-operation.js +101 -0
  38. package/dist/app/ready-slot.d.ts +12 -0
  39. package/dist/app/ready-slot.js +5 -2
  40. package/dist/app/rotation-lock.d.ts +38 -0
  41. package/dist/app/rotation-lock.js +42 -0
  42. package/dist/app/session-decrypt.d.ts +135 -0
  43. package/dist/app/session-decrypt.js +335 -0
  44. package/dist/app/session-grants.d.ts +349 -0
  45. package/dist/app/session-grants.js +811 -0
  46. package/dist/app/signing-intents.d.ts +78 -0
  47. package/dist/app/signing-intents.js +95 -0
  48. package/dist/app/store-commit.d.ts +63 -0
  49. package/dist/app/store-commit.js +126 -0
  50. package/dist/app/store-errors.d.ts +8 -0
  51. package/dist/app/store-errors.js +11 -0
  52. package/dist/app/tasra-client.d.ts +2 -0
  53. package/dist/app/tasra-client.js +1 -1
  54. package/dist/app/wallet.js +4 -1
  55. package/dist/auth/holderProof.d.ts +3 -0
  56. package/dist/auth/holderProof.js +8 -7
  57. package/dist/auth/verifier.d.ts +4 -2
  58. package/dist/auth/verifier.js +5 -2
  59. package/dist/chain/abis/index.d.ts +6178 -4101
  60. package/dist/chain/abis/index.js +3 -0
  61. package/dist/chain/abis/keyRegistry.d.ts +256 -0
  62. package/dist/chain/abis/keyRegistry.js +333 -0
  63. package/dist/chain/abis/prepaidFaultOracle.d.ts +321 -0
  64. package/dist/chain/abis/prepaidFaultOracle.js +413 -0
  65. package/dist/chain/abis/settlement.d.ts +2203 -703
  66. package/dist/chain/abis/settlement.js +2685 -764
  67. package/dist/chain/allowance.d.ts +358 -0
  68. package/dist/chain/allowance.js +800 -0
  69. package/dist/chain/billing.d.ts +85 -0
  70. package/dist/chain/billing.js +197 -0
  71. package/dist/chain/chainId.d.ts +13 -0
  72. package/dist/chain/chainId.js +26 -0
  73. package/dist/chain/client.d.ts +15 -1
  74. package/dist/chain/client.js +57 -1
  75. package/dist/chain/commitmentRecovery.d.ts +51 -0
  76. package/dist/chain/commitmentRecovery.js +38 -0
  77. package/dist/chain/committeeClient.d.ts +17 -10
  78. package/dist/chain/committeeClient.js +64 -16
  79. package/dist/chain/committeeDraw.d.ts +12 -0
  80. package/dist/chain/committeeDraw.js +56 -0
  81. package/dist/chain/custodyHealth.d.ts +212 -0
  82. package/dist/chain/custodyHealth.js +365 -0
  83. package/dist/chain/deployments.js +2 -0
  84. package/dist/chain/events.js +2 -0
  85. package/dist/chain/headFollower.d.ts +77 -0
  86. package/dist/chain/headFollower.js +219 -0
  87. package/dist/chain/headPrefetch.d.ts +23 -0
  88. package/dist/chain/headPrefetch.js +67 -0
  89. package/dist/chain/index.d.ts +50 -8
  90. package/dist/chain/index.js +28 -3
  91. package/dist/chain/keeperExecution.d.ts +44 -0
  92. package/dist/chain/keeperExecution.js +127 -0
  93. package/dist/chain/keeperRecovery.d.ts +78 -0
  94. package/dist/chain/keeperRecovery.js +91 -0
  95. package/dist/chain/node.d.ts +24 -1
  96. package/dist/chain/node.js +88 -43
  97. package/dist/chain/offchain.d.ts +2 -0
  98. package/dist/chain/paidAgentTransport.d.ts +38 -0
  99. package/dist/chain/paidAgentTransport.js +1 -0
  100. package/dist/chain/paidEpoch.d.ts +66 -0
  101. package/dist/chain/paidEpoch.js +139 -0
  102. package/dist/chain/paidPacing.d.ts +81 -0
  103. package/dist/chain/paidPacing.js +136 -0
  104. package/dist/chain/pinnedReads.d.ts +49 -0
  105. package/dist/chain/pinnedReads.js +218 -0
  106. package/dist/chain/prepaid.d.ts +383 -0
  107. package/dist/chain/prepaid.js +1046 -0
  108. package/dist/chain/prepaidEscape.d.ts +274 -0
  109. package/dist/chain/prepaidEscape.js +432 -0
  110. package/dist/chain/prepaidFault.d.ts +94 -0
  111. package/dist/chain/prepaidFault.js +148 -0
  112. package/dist/chain/receipt.d.ts +24 -0
  113. package/dist/chain/receipt.js +82 -0
  114. package/dist/chain/registeredAgent.d.ts +68 -3
  115. package/dist/chain/registeredAgent.js +143 -42
  116. package/dist/chain/registeredOperation.d.ts +10 -1
  117. package/dist/chain/registeredOperation.js +18 -3
  118. package/dist/chain/registeredPaidAgent.d.ts +254 -0
  119. package/dist/chain/registeredPaidAgent.js +889 -0
  120. package/dist/chain/registeredRelay.d.ts +31 -1
  121. package/dist/chain/registeredRelay.js +164 -43
  122. package/dist/chain/relayVoucher.d.ts +64 -0
  123. package/dist/chain/relayVoucher.js +69 -0
  124. package/dist/chain/reservation.d.ts +239 -0
  125. package/dist/chain/reservation.js +746 -0
  126. package/dist/chain/reshareRoster.d.ts +64 -0
  127. package/dist/chain/reshareRoster.js +85 -0
  128. package/dist/chain/revertReason.d.ts +8 -0
  129. package/dist/chain/revertReason.js +2 -1
  130. package/dist/chain/rotationLock.d.ts +130 -0
  131. package/dist/chain/rotationLock.js +168 -0
  132. package/dist/chain/serviceRequestPolicy.d.ts +47 -0
  133. package/dist/chain/serviceRequestPolicy.js +86 -0
  134. package/dist/chain/services.d.ts +7 -0
  135. package/dist/chain/services.js +44 -4
  136. package/dist/chain/slotClient.js +11 -2
  137. package/dist/chain/slotHandoff.d.ts +81 -0
  138. package/dist/chain/slotHandoff.js +166 -0
  139. package/dist/chain/slotSeed.d.ts +47 -5
  140. package/dist/chain/slotSeed.js +173 -42
  141. package/dist/chain/verifierSnapshot.d.ts +36 -0
  142. package/dist/chain/verifierSnapshot.js +197 -0
  143. package/dist/chain/write.d.ts +111 -21
  144. package/dist/chain/write.js +378 -146
  145. package/dist/committee/blsSharing.d.ts +53 -0
  146. package/dist/committee/blsSharing.js +90 -0
  147. package/dist/committee/client.d.ts +62 -23
  148. package/dist/committee/client.js +288 -72
  149. package/dist/committee/dual-operation.d.ts +165 -0
  150. package/dist/committee/dual-operation.js +229 -0
  151. package/dist/committee/dual-sign.d.ts +26 -1
  152. package/dist/committee/dual-sign.js +85 -7
  153. package/dist/committee/ecdsa.d.ts +38 -0
  154. package/dist/committee/ecdsa.js +87 -15
  155. package/dist/committee/evidence.d.ts +30 -0
  156. package/dist/committee/evidence.js +65 -0
  157. package/dist/committee/execution.d.ts +414 -0
  158. package/dist/committee/execution.js +446 -0
  159. package/dist/committee/extraction.js +33 -26
  160. package/dist/committee/index.d.ts +30 -7
  161. package/dist/committee/index.js +18 -6
  162. package/dist/committee/keeperExecution.d.ts +37 -0
  163. package/dist/committee/keeperExecution.js +141 -0
  164. package/dist/committee/oauth.d.ts +14 -4
  165. package/dist/committee/oauth.js +17 -5
  166. package/dist/committee/payment.d.ts +369 -0
  167. package/dist/committee/payment.js +339 -0
  168. package/dist/committee/recovery.d.ts +136 -0
  169. package/dist/committee/recovery.js +204 -0
  170. package/dist/committee/recoveryJson.d.ts +2 -0
  171. package/dist/committee/recoveryJson.js +87 -0
  172. package/dist/committee/request.d.ts +63 -27
  173. package/dist/committee/request.js +77 -66
  174. package/dist/committee/session-grant.d.ts +320 -0
  175. package/dist/committee/session-grant.js +397 -0
  176. package/dist/committee/status-refresh.d.ts +257 -0
  177. package/dist/committee/status-refresh.js +619 -0
  178. package/dist/committee/token.d.ts +163 -15
  179. package/dist/committee/token.js +247 -10
  180. package/dist/crypto/bn254.d.ts +70 -0
  181. package/dist/crypto/bn254.js +222 -0
  182. package/dist/crypto/ibe.d.ts +32 -0
  183. package/dist/crypto/ibe.js +56 -8
  184. package/dist/crypto/index.d.ts +1 -1
  185. package/dist/crypto/index.js +1 -1
  186. package/dist/crypto/kem.d.ts +31 -0
  187. package/dist/crypto/kem.js +113 -7
  188. package/dist/crypto/recipient.d.ts +75 -0
  189. package/dist/crypto/recipient.js +107 -0
  190. package/dist/decryption/client.d.ts +10 -16
  191. package/dist/decryption/client.js +8 -76
  192. package/dist/decryption/index.d.ts +2 -0
  193. package/dist/decryption/index.js +2 -0
  194. package/dist/decryption/sealed.d.ts +72 -0
  195. package/dist/decryption/sealed.js +147 -0
  196. package/dist/decryption/session.d.ts +115 -0
  197. package/dist/decryption/session.js +358 -0
  198. package/dist/errors.d.ts +406 -1
  199. package/dist/errors.js +400 -5
  200. package/dist/index.d.ts +9 -2
  201. package/dist/index.js +6 -1
  202. package/dist/internal/bounded.d.ts +66 -0
  203. package/dist/internal/bounded.js +126 -0
  204. package/dist/internal/network.d.ts +4 -0
  205. package/dist/internal/network.js +40 -0
  206. package/dist/internal/retryAfter.d.ts +8 -0
  207. package/dist/internal/retryAfter.js +28 -0
  208. package/dist/internal/sleep.d.ts +6 -0
  209. package/dist/internal/sleep.js +15 -0
  210. package/dist/internal/typedData.d.ts +13 -0
  211. package/dist/internal/typedData.js +77 -0
  212. package/dist/internal/viemErrors.d.ts +26 -0
  213. package/dist/internal/viemErrors.js +49 -0
  214. package/dist/oid4vp/binding.d.ts +27 -1
  215. package/dist/oid4vp/binding.js +36 -1
  216. package/dist/oid4vp/jose.d.ts +4 -2
  217. package/dist/oid4vp/jose.js +39 -7
  218. package/dist/oid4vp/request-object.d.ts +61 -4
  219. package/dist/oid4vp/request-object.js +140 -5
  220. package/dist/oid4vp/verifier-agent.d.ts +18 -8
  221. package/dist/oid4vp/verifier-agent.js +48 -6
  222. package/dist/oid4vp/wallet.d.ts +2 -4
  223. package/dist/oid4vp/wallet.js +1 -0
  224. package/dist/retry.d.ts +78 -0
  225. package/dist/retry.js +137 -0
  226. package/dist/signing/frost.d.ts +1 -1
  227. package/dist/verifier-agent/index.d.ts +41 -5
  228. package/dist/verifier-agent/index.js +124 -9
  229. package/dist/verifier-agent/payment.d.ts +7 -0
  230. package/dist/verifier-agent/payment.js +17 -0
  231. package/docs/api.md +8 -2
  232. package/docs/application-api.md +25 -2
  233. package/docs/chain.md +155 -9
  234. package/docs/consumer-migrations.md +61 -0
  235. package/docs/encrypted-notes.md +3 -2
  236. package/docs/encryption.md +4 -2
  237. package/docs/errors.md +14 -1
  238. package/docs/flows.md +2 -2
  239. package/docs/funding.md +902 -0
  240. package/docs/native-approvals.md +63 -0
  241. package/docs/reference/README.md +9 -8
  242. package/docs/reference/app-browser.md +232 -0
  243. package/docs/reference/app-node.md +38 -8
  244. package/docs/reference/app.md +4621 -805
  245. package/docs/reference/chain-node.md +74 -16
  246. package/docs/reference/chain.md +6740 -1592
  247. package/docs/reference/committee.md +5630 -987
  248. package/docs/reference/main.md +1439 -140
  249. package/docs/reference/oid4vp.md +297 -144
  250. package/docs/reference/verifier-agent.md +77 -35
  251. package/docs/signing.md +6 -0
  252. package/examples/encrypted-notes.ts +21 -6
  253. package/examples/getting-started.ts +2 -7
  254. package/examples/live-config.ts +24 -17
  255. package/package.json +17 -5
@@ -4,18 +4,25 @@
4
4
  // const kk = createCommitteeSlotClient({chain, holder, credentials, holderProof})
5
5
  // const sig = await kk.sign(slotId, message) // committee-authorized FROST
6
6
  // const env = await kk.encrypt(slotId, plaintext) // local (key read from chain)
7
- // const text = await kk.decrypt(slotId, {ciphertext, identity, decryptingSet, blsPeers})
7
+ // const text = await kk.decrypt(slotId, {ciphertext, identity, recipient, ciphertextEpoch, verifyingShares, threshold, binding, approveExecution, payment})
8
8
  import { resolveSlotKeeperUrls, resolveVerifierDirectory, resolveSlotGroupKey, } from './discovery.js';
9
- import { requestCommitteeToken, committeeSign, committeeDecrypt, committeeChainReadsFromClient, } from '../committee/index.js';
9
+ import { requestCommitteeToken, committeeSign, committeeChainReadsFromClient, } from '../committee/index.js';
10
10
  import { encryptEnvelope, toBytes } from '../crypto/envelope.js';
11
11
  import { hexToBytes } from '../crypto/hex.js';
12
+ import { decryptWithCommitteePartials } from '../decryption/sealed.js';
13
+ import { oneBlockDraw } from './committeeDraw.js';
14
+ import { kemContentDigest, recipientPayloadDigest } from '../crypto/recipient.js';
12
15
  /**
13
16
  * Create registry-discovered threshold signing, encryption and decryption operations. Signing and decryption require holder credentials and proofs against an anchored verifier snapshot. Encryption needs only the public group key read from the chain. The master key is not reconstructed by these threshold operations.
14
17
  * @param cfg Chain reader and optional holder credentials and proof callbacks.
15
18
  * @returns Committee client whose operations each take a slot ID.
16
19
  */
17
20
  export function createCommitteeSlotClient(cfg) {
18
- const reads = committeeChainReadsFromClient(cfg.chain.readers);
21
+ // P6: the draw (epoch, its seed, its anchored snapshot) is read at ONE block when the address
22
+ // book names both contracts; the per-call reads remain for the rest.
23
+ const { ThresholdRandomBeacon: beacon, VerifierSetRegistry: verifierSet } = cfg.chain.addresses ?? {};
24
+ const reads = { ...committeeChainReadsFromClient(cfg.chain.readers),
25
+ ...(cfg.chain.client && beacon && verifierSet ? { drawAt: oneBlockDraw(cfg.chain.client, beacon, verifierSet) } : {}) };
19
26
  // The credential fields are validated HERE rather than in the constructor: only
20
27
  // sign/decrypt present credentials to the committee, while encrypt is a local
21
28
  // operation over a public key read from chain. Checking them up front made it
@@ -44,10 +51,19 @@ export function createCommitteeSlotClient(cfg) {
44
51
  holderProof: cfg.holderProof,
45
52
  };
46
53
  }
47
- // The verifier set is network-wide (not per-slot), so discover it once and cache.
54
+ // The verifier set is network-wide (not per-slot), so it is discovered once and shared - but
55
+ // never a FAILED lookup (one RPC error used to poison the client for good), and it is dropped
56
+ // when it no longer reproduces the draw epoch's anchored snapshot (a register, deregister or
57
+ // renumber since it was read), so the next request re-resolves (robustness audit P13).
48
58
  let verifiersPromise;
49
59
  function verifierDirectory() {
50
- return (verifiersPromise ??= resolveVerifierDirectory(cfg.chain));
60
+ if (verifiersPromise)
61
+ return verifiersPromise;
62
+ const lookup = resolveVerifierDirectory(cfg.chain);
63
+ verifiersPromise = lookup;
64
+ lookup.catch(() => { if (verifiersPromise === lookup)
65
+ verifiersPromise = undefined; });
66
+ return lookup;
51
67
  }
52
68
  async function keeperUrl(slotId) {
53
69
  const urls = await resolveSlotKeeperUrls(cfg.chain, slotId);
@@ -59,7 +75,7 @@ export function createCommitteeSlotClient(cfg) {
59
75
  // Resolve keeper + verifiers from chain, gather the committee token, and REQUIRE the
60
76
  // trustless verifier-set proofs (+ an anchored snapshot) so the keeper never validates
61
77
  // against a statically-configured set. Shared by sign + decrypt.
62
- async function tokenFor(slotId, op) {
78
+ async function tokenFor(slotId, op, authorization) {
63
79
  const creds = requireCredentials(op);
64
80
  const [verifiers, nodeUrl] = await Promise.all([verifierDirectory(), keeperUrl(slotId)]);
65
81
  const res = await requestCommitteeToken({
@@ -71,8 +87,8 @@ export function createCommitteeSlotClient(cfg) {
71
87
  holder: creds.holder,
72
88
  credentials: creds.credentials,
73
89
  holderProof: creds.holderProof,
74
- clientSigner: cfg.clientSigner,
75
90
  ttlSecs: cfg.ttlSecs,
91
+ ...authorization,
76
92
  });
77
93
  // `reads.snapshot` throws when VerifierSetRegistry isn't in the address book, and
78
94
  // returns null when no snapshot is anchored (zero root / size 0) - both mean "no
@@ -86,6 +102,8 @@ export function createCommitteeSlotClient(cfg) {
86
102
  `the address book); refusing to fall back to the keeper's configured set`);
87
103
  }
88
104
  if (!res.verifierProofs || res.verifierProofs.length !== res.token.signatures.length) {
105
+ // The cached directory no longer reproduces the anchored roster: re-resolve next time.
106
+ verifiersPromise = undefined;
89
107
  throw new Error(`trustless verifier-set inclusion proofs are not derivable for every signer ` +
90
108
  `(built ${res.verifierProofs?.length ?? 0}/${res.token.signatures.length}); refusing to fall back ` +
91
109
  `to the keeper's configured verifier set`);
@@ -99,13 +117,12 @@ export function createCommitteeSlotClient(cfg) {
99
117
  return committeeSign({
100
118
  nodeUrl,
101
119
  committeeToken: res.token,
120
+ evidenceCt: res.evidenceCt,
102
121
  message,
103
122
  signingSet: opts?.signingSet,
104
123
  userSignature: opts?.userSignature,
105
124
  targetKeykeeper: opts?.targetKeykeeper,
106
125
  verifierProofs: res.verifierProofs,
107
- clientPubkey: res.clientPubkey,
108
- clientSignature: res.clientSignature,
109
126
  });
110
127
  },
111
128
  async encrypt(slotId, plaintext, opts) {
@@ -117,20 +134,51 @@ export function createCommitteeSlotClient(cfg) {
117
134
  return toBytes(encryptEnvelope(slotIdBytes, hexToBytes(publicKey), identity, plaintext, ep));
118
135
  },
119
136
  async decrypt(slotId, opts) {
120
- const { res, nodeUrl } = await tokenFor(slotId, 'decrypt()');
121
- return committeeDecrypt({
122
- nodeUrl,
137
+ opts.signal?.throwIfAborted();
138
+ if (!opts.recipient || !opts.binding || opts.ciphertextEpoch === undefined || !opts.verifyingShares
139
+ || !Number.isSafeInteger(opts.threshold) || opts.threshold < 1 || opts.threshold > opts.verifyingShares.size) {
140
+ throw new Error('Client recipient, bound authorization, epoch and authenticated sharing quorum are required');
141
+ }
142
+ opts = { ...opts, binding: { ...opts.binding, payloadDigest: opts.binding.payloadDigest.slice(), random: opts.binding.random.slice() },
143
+ ciphertext: { u: opts.ciphertext.u.slice(), nonce: opts.ciphertext.nonce.slice(), aeadCt: opts.ciphertext.aeadCt.slice() },
144
+ identity: opts.identity.slice(), verifyingShares: new Map([...opts.verifyingShares].map(([id, share]) => [id, share.slice()])),
145
+ payment: opts.payment ? structuredClone(opts.payment) : undefined };
146
+ const digest = recipientPayloadDigest(kemContentDigest(opts.ciphertext, opts.identity), opts.ciphertextEpoch, opts.recipient.recipient);
147
+ if (opts.binding.action !== 'decrypt' || opts.binding.payloadDigest.length !== digest.length
148
+ || !digest.every((byte, index) => byte === opts.binding.payloadDigest[index])) {
149
+ throw new Error('Authorization preimage differs from client recipient/ciphertext');
150
+ }
151
+ requireCredentials('decrypt()');
152
+ const id = slotId;
153
+ const [slot, nodeUrls, chainId] = await Promise.all([
154
+ cfg.chain.readers.keyRegistry.getKeySlot(id), resolveSlotKeeperUrls(cfg.chain, id), cfg.chain.client.getChainId(),
155
+ ]);
156
+ opts.signal?.throwIfAborted();
157
+ if (BigInt(opts.binding.chainId) !== BigInt(chainId))
158
+ throw new Error('Decryption authorization names another chain');
159
+ if (slot.mode !== 1 || Number(slot.epoch) !== opts.ciphertextEpoch || slot.threshold.k !== opts.threshold
160
+ || nodeUrls.length < opts.threshold || new Set(nodeUrls).size !== nodeUrls.length) {
161
+ throw new Error('Decryption sharing, epoch or assigned keeper quorum differs from the canonical slot');
162
+ }
163
+ const { res } = await tokenFor(id, 'decrypt()', { binding: opts.binding, payment: opts.payment });
164
+ opts.signal?.throwIfAborted();
165
+ return decryptWithCommitteePartials({
166
+ nodeUrls, chainId,
123
167
  committeeToken: res.token,
168
+ evidenceCt: res.evidenceCt,
124
169
  ciphertext: opts.ciphertext,
125
170
  identity: opts.identity,
126
- decryptingSet: opts.decryptingSet,
127
- blsPeers: opts.blsPeers,
171
+ recipient: opts.recipient,
128
172
  userSignature: opts.userSignature,
129
173
  ciphertextEpoch: opts.ciphertextEpoch,
174
+ verifyingShares: opts.verifyingShares,
175
+ threshold: opts.threshold,
176
+ approveExecution: opts.approveExecution,
177
+ signal: opts.signal,
178
+ fetchImpl: opts.fetchImpl,
179
+ requestId: opts.requestId,
130
180
  targetKeykeeper: opts.targetKeykeeper,
131
181
  verifierProofs: res.verifierProofs,
132
- clientPubkey: res.clientPubkey,
133
- clientSignature: res.clientSignature,
134
182
  });
135
183
  },
136
184
  };
@@ -0,0 +1,12 @@
1
+ import { type Address, type PublicClient } from 'viem';
2
+ import type { CommitteeDraw } from '../committee/request.js';
3
+ /**
4
+ * A `CommitteeChainReads.drawAt` reading the beacon epoch, its seed and its anchored verifier
5
+ * snapshot at one canonical block. `epochLag` 1 pins the previous epoch; with 0 the latest epoch is
6
+ * used when it is anchored at that block, else the previous one (its anchor lags the beacon push by
7
+ * a settle tick; keepers and verifiers admit both).
8
+ * @param client - Read client for the deployment.
9
+ * @param beacon - ThresholdRandomBeacon address.
10
+ * @param verifierSet - VerifierSetRegistry address.
11
+ */
12
+ export declare function oneBlockDraw(client: PublicClient, beacon: Address, verifierSet: Address): (epochLag?: number) => Promise<CommitteeDraw>;
@@ -0,0 +1,56 @@
1
+ // One block for the whole committee draw (robustness audit 2026-11-13, P6).
2
+ //
3
+ // A draw is (slot, epoch, seed) over the epoch's anchored verifier snapshot. Read as separate
4
+ // `latest` calls, a beacon push between them paired epoch N with seed N+1 - a draw no verifier
5
+ // derives - and a failed snapshot read silently fell back to the directory size, which no
6
+ // verifier uses either. Here the beacon epoch, its seed and its snapshot are read at ONE block
7
+ // hash (EIP-1898, `requireCanonical`), choosing the newest epoch anchored at that block, as payment
8
+ // discovery does. A missing anchor or a failed read is an error, never a substitute.
9
+ import { decodeFunctionResult, encodeFunctionData } from 'viem';
10
+ import { thresholdRandomBeaconAbi } from './abis/thresholdRandomBeacon.js';
11
+ import { verifierSetRegistryAbi } from './abis/verifierSetRegistry.js';
12
+ const ZERO32 = /^0x0{64}$/i;
13
+ /**
14
+ * A `CommitteeChainReads.drawAt` reading the beacon epoch, its seed and its anchored verifier
15
+ * snapshot at one canonical block. `epochLag` 1 pins the previous epoch; with 0 the latest epoch is
16
+ * used when it is anchored at that block, else the previous one (its anchor lags the beacon push by
17
+ * a settle tick; keepers and verifiers admit both).
18
+ * @param client - Read client for the deployment.
19
+ * @param beacon - ThresholdRandomBeacon address.
20
+ * @param verifierSet - VerifierSetRegistry address.
21
+ */
22
+ export function oneBlockDraw(client, beacon, verifierSet) {
23
+ return async (epochLag = 0) => {
24
+ const head = await client.getBlock({ blockTag: 'latest' });
25
+ if (head.hash === null)
26
+ throw new Error('committee draw: latest block has no hash');
27
+ const blockHash = head.hash;
28
+ const call = async (to, data) => {
29
+ const result = await client.call({ to, data, blockHash, requireCanonical: true, batch: false });
30
+ if (result.data === undefined)
31
+ throw new Error('committee draw: empty chain read');
32
+ return result.data;
33
+ };
34
+ const latest = decodeFunctionResult({ abi: thresholdRandomBeaconAbi, functionName: 'epoch',
35
+ data: await call(beacon, encodeFunctionData({ abi: thresholdRandomBeaconAbi, functionName: 'epoch' })) });
36
+ const at = async (epoch) => {
37
+ const [seed, snapshot] = await Promise.all([
38
+ call(beacon, encodeFunctionData({ abi: thresholdRandomBeaconAbi, functionName: 'seedAt', args: [epoch] }))
39
+ .then(data => decodeFunctionResult({ abi: thresholdRandomBeaconAbi, functionName: 'seedAt', data })),
40
+ call(verifierSet, encodeFunctionData({ abi: verifierSetRegistryAbi, functionName: 'snapshotAt', args: [epoch] }))
41
+ .then(data => decodeFunctionResult({ abi: verifierSetRegistryAbi, functionName: 'snapshotAt', data })),
42
+ ]);
43
+ const [root, size] = snapshot;
44
+ const anchored = !ZERO32.test(seed) && !ZERO32.test(root) && Number(size) > 0;
45
+ return anchored ? { epoch: Number(epoch), seed, root, size: Number(size) } : undefined;
46
+ };
47
+ const lag = BigInt(Math.max(0, Math.min(1, Math.floor(epochLag))));
48
+ let epoch = latest >= lag ? latest - lag : 0n;
49
+ let draw = await at(epoch);
50
+ if (!draw && lag === 0n && epoch > 0n)
51
+ draw = await at(--epoch);
52
+ if (!draw)
53
+ throw new Error(`committee draw: no anchored seed and verifier snapshot at epoch ${epoch} (block ${blockHash})`);
54
+ return { ...draw, blockHash };
55
+ };
56
+ }
@@ -0,0 +1,212 @@
1
+ import { type Address, type Hex } from 'viem';
2
+ import { TasraError } from '../errors.js';
3
+ import type { TasraChainClient } from './client.js';
4
+ /** Domain tag of {@link custodyStatementHash}; a changed preimage gets a new name on the network. */
5
+ export declare const CUSTODY_HEALTH_DOMAIN = "keykeeper-committee/custody-health/v1";
6
+ /** Default maximum age of a statement, in seconds; the keepers count a peer's statement for 900 s. */
7
+ export declare const CUSTODY_STATEMENT_MAX_AGE_SECS = 900;
8
+ /** The reshare states a keeper reports for its own share. */
9
+ export type CustodyReshareState = 'current' | 'pending' | 'not_member' | 'no_key' | 'unknown';
10
+ /** The last threshold-ECDSA reshare the keeper failed for the slot, as it signed it. */
11
+ export interface CustodyFailure {
12
+ /** Committee version the failed reshare targeted. */
13
+ committeeVersion: number;
14
+ /** On-chain operator id of the party the refusal named, or `null` when it named none. */
15
+ blamedOperatorId: number | null;
16
+ /** The keeper's reason text; diagnostic, never parse it. */
17
+ reason: string;
18
+ }
19
+ /** What one keeper signed about one slot. Hex fields are lowercase. */
20
+ export interface CustodyStatement {
21
+ /** Chain the keeper read. */
22
+ chainId: number;
23
+ /** Slot the statement is about. */
24
+ slot: Hex;
25
+ /** Operator address of the signing keeper. */
26
+ operator: Address;
27
+ /** The chain's key epoch as the keeper read it. */
28
+ epoch: number;
29
+ /** The chain's committee version as the keeper read it. */
30
+ committeeVersion: number;
31
+ /** The chain's anchored public key as the keeper read it; `0x` before a key exists. */
32
+ publicKey: Hex;
33
+ /** Whether the keeper's share is at the chain's generation; `pending` means a reshare it has not finished. */
34
+ reshare: CustodyReshareState;
35
+ /** Committee version of the share the keeper holds, or `null` when it holds none or cannot tell. */
36
+ shareCommitteeVersion: number | null;
37
+ /** Whether the keeper's share belongs to the chain's key, or `null` when it cannot tell. */
38
+ shareMatchesChainKey: boolean | null;
39
+ /** Older share generations the keeper still holds, or `null` when it cannot tell. */
40
+ retainedGenerations: number | null;
41
+ /** The keeper's last failed reshare of this slot, or `null`. */
42
+ lastFailure: CustodyFailure | null;
43
+ /** Unix seconds at which the keeper made the statement. */
44
+ observedAt: number;
45
+ }
46
+ /**
47
+ * Stable refusal categories of a custody-health reply; branch on `code`, never on the message.
48
+ * `unreachable` and `stale` may pass on a later poll; the others need a different keeper or reply.
49
+ */
50
+ export type CustodyHealthErrorCode = 'unsigned' | 'malformed' | 'bad-signature' | 'stale' | 'mismatch' | 'not-registered' | 'unreachable' | 'no-slot';
51
+ /** A custody-health reply that was not counted, or a slot that could not be read. */
52
+ export declare class CustodyHealthError extends TasraError {
53
+ /** Refusal category; never infer it from the message. */
54
+ readonly code: CustodyHealthErrorCode;
55
+ /** Operator whose reply was refused, when the refusal is about one keeper. */
56
+ readonly operator?: Address;
57
+ constructor(code: CustodyHealthErrorCode, message: string, opts?: {
58
+ operator?: Address;
59
+ cause?: unknown;
60
+ });
61
+ }
62
+ /**
63
+ * `keccak256(domain || fields)`, every field fixed-width or length-prefixed and every optional
64
+ * field tagged: the 32 bytes a keeper signs. Identical to the network's `custody_statement_hash`.
65
+ * @param s Statement to hash; integers must be non-negative safe integers.
66
+ */
67
+ export declare function custodyStatementHash(s: CustodyStatement): Uint8Array;
68
+ /**
69
+ * Whether `signature` is the operator's ed25519 signature over the statement. Take `publicKey`
70
+ * from NodeRegistry for `statement.operator`, never from the reply.
71
+ * @param statement Statement as parsed from the reply.
72
+ * @param publicKey The operator's registered 32-byte identity key.
73
+ * @param signature 64-byte signature from the reply.
74
+ */
75
+ export declare function verifyCustodyStatement(statement: CustodyStatement, publicKey: Uint8Array, signature: Uint8Array): boolean;
76
+ /**
77
+ * Parse a statement as the network serializes it (snake case). Refuses unknown fields: they would
78
+ * not be covered by the signature. Throws `CustodyHealthError` with code `malformed`.
79
+ * @param raw The `attestation.statement` value of a reply.
80
+ */
81
+ export declare function parseCustodyStatement(raw: unknown): CustodyStatement;
82
+ /** What a reply must be about, and the key it must be signed with. */
83
+ export interface ExpectedCustodyReply {
84
+ /** Chain the statement must name. */
85
+ chainId: number;
86
+ /** Slot that was polled. */
87
+ slotId: Hex;
88
+ /** Operator whose keeper was polled. */
89
+ operator: Address;
90
+ /** The operator's identity key as NodeRegistry holds it (32 bytes, or its hex). */
91
+ registeredPublicKey: Uint8Array | Hex;
92
+ /** Current Unix seconds; defaults to the local clock. */
93
+ nowSecs?: number;
94
+ /** Maximum statement age in either direction, in seconds; defaults to {@link CUSTODY_STATEMENT_MAX_AGE_SECS}. */
95
+ maxAgeSecs?: number;
96
+ }
97
+ /** A keeper's custody statement whose signature verified under the operator's registered key. */
98
+ export interface VerifiedCustodyReport {
99
+ /** Operator that signed it (checksummed). */
100
+ operator: Address;
101
+ /** The signed statement; nothing outside it is returned. */
102
+ statement: CustodyStatement;
103
+ }
104
+ /**
105
+ * Verify one keeper's custody-health reply and return its signed statement. Refused, as a
106
+ * `CustodyHealthError`: `unsigned` (no attestation), `malformed`, `mismatch` (another chain, slot
107
+ * or operator, a key other than the registered one, or an unsigned field that contradicts the
108
+ * signed statement), `bad-signature`, and `stale` (older or newer than the allowed age).
109
+ * @param reply The parsed JSON reply.
110
+ * @param expected What the reply must be about and the operator's registered key.
111
+ */
112
+ export declare function verifyCustodyHealthReply(reply: unknown, expected: ExpectedCustodyReply): VerifiedCustodyReport;
113
+ /**
114
+ * Whether a verified statement proves the keeper holds a share of the chain's current generation:
115
+ * `current`, a share of the chain's key, at the chain's committee version. The rule the keepers
116
+ * apply before retiring old shares.
117
+ * @param s A verified statement.
118
+ * @param chain The chain's committee version and public key.
119
+ */
120
+ export declare function custodyStatementIsCurrent(s: CustodyStatement, chain: {
121
+ committeeVersion: number;
122
+ publicKey: Hex;
123
+ }): boolean;
124
+ /** How a committee fares against its threshold: the keepers' own classification. */
125
+ export type CustodyHealthLevel = 'ok' | 'at_risk' | 'frozen';
126
+ /**
127
+ * Classify a committee by its live members: `frozen` below `k`, `ok` when all are live or more
128
+ * than one above `k`, `at_risk` otherwise. The keepers' reshare monitor rule with a margin of one.
129
+ * @param live Live committee members.
130
+ * @param k Signing threshold.
131
+ * @param n Committee size.
132
+ */
133
+ export declare function assessCustodyHealth(live: number, k: number, n: number): CustodyHealthLevel;
134
+ /** Transport and policy for {@link readCustodyHealth}. */
135
+ export interface ReadCustodyHealthOptions {
136
+ /** Expected chain; defaults to the chain the client's RPC answers. */
137
+ chainId?: number;
138
+ /** Fetch used for the keeper requests; defaults to the global fetch. */
139
+ fetchImpl?: typeof fetch;
140
+ /** Map a registered keeper URL to the address to request, for an application with mapped keeper routes. */
141
+ route?: (url: string) => string;
142
+ /** Allow loopback HTTP on the disposable local chain 43112 only. Default false. */
143
+ allowLocalHttp?: boolean;
144
+ /** Cancel the poll. The complete poll is bounded to 15 seconds. */
145
+ signal?: AbortSignal;
146
+ /** Current Unix seconds for the freshness check; defaults to the local clock. */
147
+ nowSecs?: number;
148
+ /** Maximum statement age in seconds; defaults to {@link CUSTODY_STATEMENT_MAX_AGE_SECS}. */
149
+ maxAgeSecs?: number;
150
+ }
151
+ /** A slot's custody health: chain state read by the SDK, and the keepers' verified statements. */
152
+ export interface CustodyHealthReport {
153
+ /** Slot that was polled. */
154
+ slotId: Hex;
155
+ /** Chain the statements were checked against. */
156
+ chainId: number;
157
+ /** The slot as the chain records it. */
158
+ chain: {
159
+ /** `KeyRegistry.Mode` ordinal. */
160
+ mode: number;
161
+ /** Anchored public key; `0x` before a key exists. */
162
+ publicKey: Hex;
163
+ /** Key epoch. */
164
+ epoch: number;
165
+ /** Committee version; a reshare raises it. */
166
+ committeeVersion: number;
167
+ /** Signing threshold. */
168
+ k: number;
169
+ /** Committee size. */
170
+ n: number;
171
+ /** Whether the slot is cancelled. */
172
+ cancelled: boolean;
173
+ /** Whether no rotation can change the key; `null` on a KeyRegistry without the lock. */
174
+ rotationLocked: boolean | null;
175
+ };
176
+ /** The committee's liveness, from NodeRegistry: a live member is an active, keeper-tagged operator. */
177
+ committee: {
178
+ /** Assigned members. */
179
+ members: number;
180
+ /** Members that are live keepers. */
181
+ liveMembers: number;
182
+ /** `liveMembers - k`: further losses the slot survives; negative means it cannot sign. */
183
+ margin: number;
184
+ /** Members that are not live keepers, the ones a reshare should replace. */
185
+ notLive: Address[];
186
+ };
187
+ /** Classification from `liveMembers`, `k` and `n`. */
188
+ health: CustodyHealthLevel;
189
+ /** Members whose verified statement proves a share of the chain's current generation. */
190
+ current: Address[];
191
+ /** Whether at least `k` members proved it, so the current generation can sign without any older one. */
192
+ proven: boolean;
193
+ /** Members whose verified statement reports a reshare they have not finished. */
194
+ pending: Address[];
195
+ /** Every verified statement, one per member that answered. */
196
+ reports: VerifiedCustodyReport[];
197
+ /** Members whose reply was refused or not received; none of these is counted. */
198
+ refused: {
199
+ operator: Address;
200
+ error: CustodyHealthError;
201
+ }[];
202
+ }
203
+ /**
204
+ * Poll every assigned keeper of a slot for its custody health and verify each reply against the
205
+ * operator's registered identity key. The committee's liveness, margin, health and rotation lock
206
+ * come from the SDK's own chain reads; the keepers contribute only their signed statements.
207
+ * A keeper whose reply is refused is listed in `refused` and never counted. Refuses `no-slot`.
208
+ * @param chain Reader for the deployment that owns the slot.
209
+ * @param slotId Slot to poll.
210
+ * @param options Expected chain, transport, cancellation and freshness policy.
211
+ */
212
+ export declare function readCustodyHealth(chain: TasraChainClient, slotId: Hex, options?: ReadCustodyHealthOptions): Promise<CustodyHealthReport>;