@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
@@ -1,19 +1,22 @@
1
1
  // accountant-seeded creation: the per-commitment draw seed.
2
2
  //
3
- // Under beacon-epoch creation a slot is committed, then revealed once the beacon has advanced past the
4
- // commit's target epoch. The wait is what makes the committee draw ungrindable - the seed must
5
- // post-date the commitment - and it costs one BEACON EPOCH, which at the production cadence is up
6
- // to an hour.
3
+ // Under the older beacon-epoch creation a slot was committed, then revealed once the beacon had
4
+ // advanced past the commit's target epoch. The wait is what made the committee draw ungrindable -
5
+ // the seed must post-date the commitment - and it cost ONE TO TWO BEACON EPOCHS (the target is
6
+ // `COMMIT_GAP = 2` epochs past the epoch the commit landed in), which at the production cadence of
7
+ // one hour is one to two hours.
7
8
  //
8
9
  // accountant-seeded creation keeps the property and drops the wait: the accountant set threshold-signs
9
10
  // `KeyRegistry.commitSeedDigest(commitment)` on demand, and the reveal derives the draw seed from
10
11
  // that signature. It post-dates the commitment because it is OVER the commitment.
11
12
  //
12
- // This module is the client half. It is deliberately best-effort: when no accountant answers, the
13
- // caller falls back to the epoch wait, which still works and is what every existing deployment
14
- // does. A seed that cannot be fetched is slower, never wrong.
13
+ // This module is the client half, and the ONLY way the SDK creates a slot. There is no fallback to
14
+ // the epoch wait: the epoch seed comes from the same k-of-n accountant set, so a fallback adds no
15
+ // liveness - only a wait of up to two hours. A seed that cannot be had within the bounded window is
16
+ // a typed failure the caller can act on (`SlotSeedUnavailableError`), never a silent wait.
15
17
  import { keyRegistryAbi } from './abis/index.js';
16
18
  import { resolveAccountantUrls } from './discovery.js';
19
+ import { parseRetryAfter } from '../internal/retryAfter.js';
17
20
  /** A 64-byte BN254 G1 point, hex-encoded: the wire size of a threshold signature. */
18
21
  const SIG_HEX_LEN = 2 + 64 * 2;
19
22
  function parseSeed(body, commitment) {
@@ -36,63 +39,191 @@ function parseSeed(body, commitment) {
36
39
  return null;
37
40
  return { commitment, digest: digest.toLowerCase(), signature: signature.toLowerCase() };
38
41
  }
39
- async function askOne(url, commitment, timeoutMs) {
42
+ /**
43
+ * Statuses that mean "not yet" rather than "no":
44
+ * - 404: this accountant's chain view has not reached the commit receipt yet;
45
+ * - 429: it sheds load and says when to come back (`Retry-After`);
46
+ * - 503: its threshold set is not up, or it is already leading a round (one at a time, by design:
47
+ * a queue there is a queue in front of the beacon);
48
+ * - 502/504: it could not read the chain, or a proxy timed out.
49
+ * A 409 is the opposite: the commitment is bound to another reveal path, or already revealed, and
50
+ * no retry can change it.
51
+ */
52
+ const RETRYABLE = new Set([404, 429, 502, 503, 504]);
53
+ /** Default time the creation path keeps re-asking while the set answers "not yet". */
54
+ export const DEFAULT_SLOT_SEED_RETRY_MS = 90_000;
55
+ /**
56
+ * Default stagger between launching the asks of one round. The asks run CONCURRENTLY and the first
57
+ * valid seed wins; the stagger only keeps a healthy set from leading n threshold rounds for one
58
+ * commitment (each accountant leads at most one round at a time and sheds the rest with a 503).
59
+ * An ask that fails launches the next one at once, without waiting for the stagger.
60
+ */
61
+ export const DEFAULT_SLOT_SEED_HEDGE_MS = 750;
62
+ async function askOne(url, commitment, timeoutMs, expectedDigest, signal) {
40
63
  let end = url.length;
41
64
  while (end > 0 && url[end - 1] === '/')
42
65
  end--;
43
66
  const base = url.slice(0, end);
44
- const res = await fetch(`${base}/v1/slot-seed`, {
45
- method: 'POST',
46
- headers: { 'content-type': 'application/json' },
47
- body: JSON.stringify({ commitment }),
48
- signal: AbortSignal.timeout(timeoutMs),
67
+ let res;
68
+ try {
69
+ res = await fetch(`${base}/v1/slot-seed`, {
70
+ method: 'POST',
71
+ headers: { 'content-type': 'application/json' },
72
+ body: JSON.stringify({ commitment }),
73
+ signal: AbortSignal.any([AbortSignal.timeout(timeoutMs), signal]),
74
+ });
75
+ }
76
+ catch (e) {
77
+ // A timeout is "busy", and asked again in the next round. A refused or reset connection is
78
+ // "down", and is not: an accountant that is down is down for longer than the retry window, and
79
+ // a set that is entirely unreachable must fail FAST rather than pay the window to say so.
80
+ const timedOut = e instanceof Error && e.name === 'TimeoutError';
81
+ return { answer: { url, reason: `${timedOut ? 'timed out' : 'unreachable'}: ${e instanceof Error ? e.message : String(e)}` }, retryable: timedOut };
82
+ }
83
+ if (!res.ok) {
84
+ const text = await res.text().catch(() => '');
85
+ const retryable = RETRYABLE.has(res.status);
86
+ return { answer: { url, status: res.status, reason: text.slice(0, 200) || `HTTP ${res.status}` }, retryable, ...retryable ? { retryAfterMs: parseRetryAfter(typeof res.headers?.get === 'function' ? res.headers.get('retry-after') : undefined) } : {} };
87
+ }
88
+ const seed = parseSeed(await res.json().catch(() => null), commitment);
89
+ if (!seed)
90
+ return { answer: { url, status: res.status, reason: 'malformed seed response' }, retryable: false };
91
+ // A digest that is not the registry's own means this accountant is bound to a DIFFERENT
92
+ // registry or chain - its signature could never satisfy the reveal. Skip it rather than
93
+ // spending gas to be told so.
94
+ if (seed.digest !== expectedDigest)
95
+ return { answer: { url, status: res.status, reason: 'digest is not this registry\'s commitSeedDigest' }, retryable: false };
96
+ return { seed };
97
+ }
98
+ /**
99
+ * One round: every accountant asked once, CONCURRENTLY. Asks launch `hedgeMs` apart in `order`, or at
100
+ * once when an earlier ask fails; the first valid seed wins and cancels the rest. A 409 ends the
101
+ * round: it is the chain's answer, not one accountant's state.
102
+ */
103
+ function askRound(order, commitment, timeoutMs, expected, hedgeMs, outer) {
104
+ return new Promise(resolve => {
105
+ const cancel = new AbortController();
106
+ const signal = outer ? AbortSignal.any([cancel.signal, outer]) : cancel.signal;
107
+ const asked = [];
108
+ let next = 0, pending = 0, done = false;
109
+ let timer;
110
+ const finish = (r) => {
111
+ if (done)
112
+ return;
113
+ done = true;
114
+ clearTimeout(timer);
115
+ cancel.abort();
116
+ resolve(r);
117
+ };
118
+ const launch = () => {
119
+ clearTimeout(timer);
120
+ const url = order[next++];
121
+ if (done || url === undefined)
122
+ return;
123
+ pending++;
124
+ void askOne(url, commitment, timeoutMs, expected, signal).then(a => {
125
+ pending--;
126
+ if (done)
127
+ return;
128
+ if ('seed' in a)
129
+ return finish({ seed: a.seed });
130
+ asked.push(a);
131
+ if (a.answer.status === 409)
132
+ return finish({ asked, settled: true });
133
+ if (next < order.length)
134
+ launch();
135
+ else if (pending === 0)
136
+ finish({ asked, settled: false });
137
+ });
138
+ if (next < order.length)
139
+ timer = setTimeout(launch, hedgeMs);
140
+ };
141
+ if (!order.length)
142
+ return finish({ asked, settled: false });
143
+ launch();
49
144
  });
50
- // 503 is the expected answer from an accountant whose threshold set is not up, and 404 from one
51
- // whose chain view has not yet seen the commit. Both mean "ask someone else / try again",
52
- // neither is an error worth surfacing - the caller's fallback is the epoch wait.
53
- if (!res.ok)
54
- return null;
55
- return parseSeed(await res.json(), commitment);
145
+ }
146
+ function pause(ms, signal) {
147
+ signal?.throwIfAborted();
148
+ return new Promise((resolve, reject) => {
149
+ const aborted = () => { clearTimeout(timer); reject(signal?.reason); };
150
+ const timer = setTimeout(() => { signal?.removeEventListener('abort', aborted); resolve(); }, ms);
151
+ signal?.addEventListener('abort', aborted, { once: true });
152
+ });
153
+ }
154
+ function summarise(answers) {
155
+ if (!answers.length)
156
+ return 'no accountant registered';
157
+ const counts = new Map();
158
+ for (const a of answers) {
159
+ const key = a.status !== undefined ? `${a.status} ${a.reason}` : a.reason;
160
+ counts.set(key, (counts.get(key) ?? 0) + 1);
161
+ }
162
+ return [...counts].sort((a, b) => b[1] - a[1]).map(([k, n]) => `${n}x ${k}`).join('; ');
56
163
  }
57
164
  /**
58
- * Request a committee draw seed and compare its digest with the registry. Checks signature encoding and rejects the point at infinity; signature cryptography is verified during the on-chain reveal.
165
+ * Request a committee draw seed and compare its digest with the registry. Checks signature encoding and rejects the point at infinity; signature cryptography is verified during the on-chain reveal. Accountants are asked concurrently and the first valid seed wins.
59
166
  * @param chain Reader for the deployment owning the commitment.
60
167
  * @param keyRegistry Registry that will receive the reveal transaction.
61
168
  * @param commitment Previously submitted creation commitment.
62
- * @param opts Accountant endpoints and request timeout.
63
- * @returns A seed response, or null when no accountant returns an acceptable response.
169
+ * @param opts Accountant endpoints, request timeout, retry window and cancellation.
170
+ * @returns A seed response, or null when no accountant returns an acceptable response within the window.
64
171
  */
65
172
  export async function requestSlotSeed(chain, keyRegistry, commitment, opts = {}) {
66
173
  const timeoutMs = opts.timeoutMs ?? 20_000;
67
174
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120_000) {
68
175
  throw new Error('Invalid slot-seed timeout');
69
176
  }
177
+ const retryForMs = opts.retryForMs ?? 0;
178
+ if (!Number.isSafeInteger(retryForMs) || retryForMs < 0 || retryForMs > 600_000) {
179
+ throw new Error('Invalid slot-seed retry window');
180
+ }
181
+ const hedgeMs = opts.hedgeMs ?? DEFAULT_SLOT_SEED_HEDGE_MS;
182
+ if (!Number.isSafeInteger(hedgeMs) || hedgeMs < 0 || hedgeMs > 60_000) {
183
+ throw new Error('Invalid slot-seed hedge delay');
184
+ }
185
+ opts.signal?.throwIfAborted();
70
186
  const urls = opts.urls ?? (await resolveAccountantUrls(chain).catch(() => []));
71
- if (!urls.length)
187
+ if (!urls.length) {
188
+ opts.onFailure?.({ rounds: 0, answers: [], reason: summarise([]) });
72
189
  return null;
190
+ }
73
191
  const expected = (await chain.client.readContract({
74
192
  address: keyRegistry,
75
193
  abi: keyRegistryAbi,
76
194
  functionName: 'commitSeedDigest',
77
195
  args: [commitment],
78
- }));
79
- for (const url of urls) {
80
- let seed;
81
- try {
82
- seed = await askOne(url, commitment, timeoutMs);
83
- }
84
- catch {
85
- // One unreachable accountant is not a failure of the set. Move on.
86
- continue;
87
- }
88
- if (!seed)
89
- continue;
90
- // A digest that is not the registry's own means this accountant is bound to a DIFFERENT
91
- // registry or chain - its signature could never satisfy the reveal. Skip it rather than
92
- // spending gas to be told so.
93
- if (seed.digest !== expected.toLowerCase())
94
- continue;
95
- return seed;
196
+ })).toLowerCase();
197
+ const deadline = Date.now() + retryForMs;
198
+ // Start at an accountant picked by the commitment, and move one on per round: concurrent
199
+ // creators would otherwise all lead on the first one, whose single lead slot then sheds every
200
+ // caller but one with a 503. Derived, not random, so a given creation asks in a fixed order.
201
+ const offset = Number.parseInt(commitment.slice(-4), 16) % urls.length || 0;
202
+ let delay = 250;
203
+ for (let round = 1;; round++) {
204
+ const order = urls.map((_, i) => urls[(offset + round - 1 + i) % urls.length]).filter((u) => u !== undefined);
205
+ // Inside a window, no ask outlives it by more than a second: the window is the bound a caller
206
+ // was promised, not a floor under a 20 s ask that started just before it closed.
207
+ const askMs = retryForMs > 0 ? Math.max(1_000, Math.min(timeoutMs, deadline - Date.now())) : timeoutMs;
208
+ const r = await askRound(order, commitment, askMs, expected, hedgeMs, opts.signal);
209
+ if ('seed' in r)
210
+ return r.seed;
211
+ opts.signal?.throwIfAborted();
212
+ const answers = r.asked.map(a => a.answer);
213
+ const notYet = r.asked.filter(a => a.retryable);
214
+ const fail = () => {
215
+ opts.onFailure?.({ rounds: round, answers, reason: summarise(answers) });
216
+ return null;
217
+ };
218
+ if (!notYet.length || r.settled)
219
+ return fail();
220
+ // Jittered so a burst of creators that were all shed together does not come back together.
221
+ // When EVERY "not yet" named a Retry-After, nobody will answer sooner than the earliest of them.
222
+ const hinted = notYet.every(a => a.retryAfterMs !== undefined) ? Math.min(...notYet.map(a => a.retryAfterMs ?? 0)) : 0;
223
+ const wait = Math.max(delay / 2 + Math.random() * delay / 2, hinted);
224
+ if (Date.now() + wait > deadline)
225
+ return fail();
226
+ await pause(wait, opts.signal);
227
+ delay = Math.min(delay * 2, 4_000);
96
228
  }
97
- return null;
98
229
  }
@@ -0,0 +1,36 @@
1
+ import { type Address } from 'viem';
2
+ import type { PaymentIntentWire } from '../committee/payment.js';
3
+ import type { PaidVerifierWitness } from './prepaid.js';
4
+ /** The anchored verifier policy fields of an original payment intent. */
5
+ export type OriginalVerifierPolicy = Pick<PaymentIntentWire, 'chain_id' | 'slot' | 'verification_epoch' | 'verification_seed' | 'verification_root' | 'verification_registry_size' | 'verification_committee' | 'verification_quorum'>;
6
+ /**
7
+ * Verify a snapshot artifact against the original payment and return the drawn members with
8
+ * Merkle proofs. Every leaf is checked against the anchored root, operators are strictly
9
+ * ordered and keys distinct; the draw is recomputed locally from the payment's seed.
10
+ * @param value Parsed artifact JSON from an approved host; untrusted.
11
+ * @param original The payment's anchored verifier policy.
12
+ * @param registry Independently approved VerifierSetRegistry address.
13
+ */
14
+ export declare function drawnVerifierWitnesses(value: unknown, original: OriginalVerifierPolicy, registry: Address): PaidVerifierWitness[];
15
+ /**
16
+ * Fetch an epoch's verifier snapshot from the first approved accountant that serves a bounded,
17
+ * identity-encoded JSON body (no redirects), and return the drawn witnesses for the payment.
18
+ * A host whose artifact does not verify is skipped; the call fails if none does.
19
+ * `waitForPublicationMs` defaults to zero. A positive value (at most 150000 ms)
20
+ * permits paced reads only while every host returns 404, using the original
21
+ * policy captured at entry. Invalid artifacts and other failures are not retried.
22
+ * @param hosts Independently approved accountant origins, in preference order.
23
+ * @param original The payment's anchored verifier policy.
24
+ * @param registry Independently approved VerifierSetRegistry address.
25
+ * @param options Cancellation, per-host timeout (default 15000 ms), optional bounded publication wait and a fetch implementation.
26
+ */
27
+ export declare function fetchDrawnVerifierWitnesses(hosts: readonly string[], original: OriginalVerifierPolicy, registry: Address, options?: {
28
+ signal?: AbortSignal;
29
+ timeoutMs?: number;
30
+ waitForPublicationMs?: number;
31
+ fetch?: typeof fetch;
32
+ }): Promise<{
33
+ witnesses: PaidVerifierWitness[];
34
+ artifact: unknown;
35
+ host: string;
36
+ }>;
@@ -0,0 +1,197 @@
1
+ // The drawn verifier witnesses a paid session needs, from a public snapshot artifact.
2
+ //
3
+ // Accountants serve the verifier-set snapshot for an epoch (`GET /v1/verifier-set/{epoch}`).
4
+ // The artifact host supplies only the leaves; their authority is the payment's own anchored
5
+ // root, size, seed and epoch, which the creator signed from a canonical chain read. A host
6
+ // that serves anything else is refused, and the next approved host is tried. Never replace a
7
+ // retained epoch with the live roster.
8
+ import { hexToBytes, toHex } from 'viem';
9
+ import { merkleProof, merkleRoot, selectVerifierCommittee, verifierLeaf } from '../committee/token.js';
10
+ const MAX_SNAPSHOT_BYTES = 8 * 1024 * 1024;
11
+ /**
12
+ * Verified snapshot artifacts, keyed by registry, chain, epoch, anchored root and size. An artifact
13
+ * is kept only after it verified against that root, and every later use verifies it again in full
14
+ * for the payment at hand (its own slot's draw and proofs), so a hit answers exactly what a fresh
15
+ * fetch of the same bytes would. Kept per fetch implementation (one transport's answers are never
16
+ * another's). Bounded; the oldest is evicted first.
17
+ */
18
+ const MAX_KEPT_SNAPSHOTS = 32;
19
+ const keptByFetch = new WeakMap();
20
+ const snapshotKey = (registry, p) => [registry, p.chain_id, p.verification_epoch, p.verification_root, p.verification_registry_size].join('|').toLowerCase();
21
+ function fail(message) { throw new Error(`Verifier snapshot refused: ${message}`); }
22
+ function object(value, fields) {
23
+ if (!value || typeof value !== 'object' || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
24
+ fail('expected a JSON object');
25
+ const record = value;
26
+ if (Object.getOwnPropertySymbols(record).length
27
+ || !Object.values(Object.getOwnPropertyDescriptors(record)).every(d => d.enumerable && Object.hasOwn(d, 'value')))
28
+ fail('objects must contain only JSON properties');
29
+ const keys = Object.keys(record).sort(), expected = [...fields].sort();
30
+ if (keys.length !== expected.length || keys.some((k, i) => k !== expected[i]))
31
+ fail('unexpected or missing fields');
32
+ return record;
33
+ }
34
+ function hex(value, size) {
35
+ if (typeof value !== 'string' || !new RegExp(`^0x[0-9a-fA-F]{${size * 2}}$`).test(value) || /^0x0+$/.test(value))
36
+ fail('identity must be nonzero canonical-length hex');
37
+ return value.toLowerCase();
38
+ }
39
+ /**
40
+ * Verify a snapshot artifact against the original payment and return the drawn members with
41
+ * Merkle proofs. Every leaf is checked against the anchored root, operators are strictly
42
+ * ordered and keys distinct; the draw is recomputed locally from the payment's seed.
43
+ * @param value Parsed artifact JSON from an approved host; untrusted.
44
+ * @param original The payment's anchored verifier policy.
45
+ * @param registry Independently approved VerifierSetRegistry address.
46
+ */
47
+ export function drawnVerifierWitnesses(value, original, registry) {
48
+ const p = structuredClone(original);
49
+ if (!Number.isSafeInteger(p.chain_id) || p.chain_id <= 0 || !Number.isSafeInteger(p.verification_epoch) || p.verification_epoch < 0)
50
+ fail('invalid original deployment or epoch');
51
+ hex(p.slot, 32);
52
+ hex(p.verification_seed, 32);
53
+ hex(p.verification_root, 32);
54
+ hex(registry, 20);
55
+ if (!Number.isSafeInteger(p.verification_registry_size) || p.verification_registry_size <= 0 || p.verification_registry_size > (1 << 20))
56
+ fail('invalid original pool size');
57
+ if (!Number.isSafeInteger(p.verification_committee) || !Number.isSafeInteger(p.verification_quorum)
58
+ || p.verification_quorum <= 0 || p.verification_quorum > p.verification_committee
59
+ || p.verification_committee > Math.min(4096, p.verification_registry_size))
60
+ fail('invalid original quorum');
61
+ const artifact = object(value, ['version', 'chain_id', 'registry', 'epoch', 'root', 'size', 'block_number', 'block_hash', 'entries']);
62
+ if (artifact.version !== 1 || artifact.chain_id !== p.chain_id || artifact.epoch !== p.verification_epoch
63
+ || hex(artifact.registry, 20) !== registry.toLowerCase() || hex(artifact.root, 32) !== p.verification_root.toLowerCase()
64
+ || artifact.size !== p.verification_registry_size)
65
+ fail('differs from the original anchored payment');
66
+ if (!Number.isSafeInteger(artifact.block_number) || Number(artifact.block_number) < 0)
67
+ fail('invalid provenance block');
68
+ hex(artifact.block_hash, 32);
69
+ if (!Array.isArray(artifact.entries) || artifact.entries.length !== p.verification_registry_size)
70
+ fail('leaf count differs');
71
+ let previous = '';
72
+ const keys = new Set();
73
+ const entries = artifact.entries.map((value, index) => {
74
+ const entry = object(value, ['index', 'operator', 'pubkey']);
75
+ const operator = hex(entry.operator, 20), publicKey = hex(entry.pubkey, 32);
76
+ if (entry.index !== index || operator <= previous || keys.has(publicKey))
77
+ fail('indexes, operator order or keys are ambiguous');
78
+ previous = operator;
79
+ keys.add(publicKey);
80
+ return { index, operator, publicKey };
81
+ });
82
+ const leaves = entries.map(m => verifierLeaf(m.index, hexToBytes(m.operator), hexToBytes(m.publicKey)));
83
+ const root = merkleRoot(leaves);
84
+ if (!root || toHex(root) !== p.verification_root.toLowerCase())
85
+ fail('leaves differ from the independently anchored root');
86
+ const drawn = selectVerifierCommittee(hexToBytes(p.slot), p.verification_epoch, hexToBytes(p.verification_seed), p.verification_registry_size, p.verification_committee);
87
+ return drawn.map(index => {
88
+ const member = entries[index], proof = merkleProof(leaves, index);
89
+ if (!proof)
90
+ fail('missing drawn verifier proof');
91
+ return { ...member, proof: proof.map(step => toHex(step)) };
92
+ });
93
+ }
94
+ /**
95
+ * Fetch an epoch's verifier snapshot from the first approved accountant that serves a bounded,
96
+ * identity-encoded JSON body (no redirects), and return the drawn witnesses for the payment.
97
+ * A host whose artifact does not verify is skipped; the call fails if none does.
98
+ * `waitForPublicationMs` defaults to zero. A positive value (at most 150000 ms)
99
+ * permits paced reads only while every host returns 404, using the original
100
+ * policy captured at entry. Invalid artifacts and other failures are not retried.
101
+ * @param hosts Independently approved accountant origins, in preference order.
102
+ * @param original The payment's anchored verifier policy.
103
+ * @param registry Independently approved VerifierSetRegistry address.
104
+ * @param options Cancellation, per-host timeout (default 15000 ms), optional bounded publication wait and a fetch implementation.
105
+ */
106
+ export async function fetchDrawnVerifierWitnesses(hosts, original, registry, options = {}) {
107
+ const list = [...hosts], doFetch = options.fetch ?? globalThis.fetch, timeout = options.timeoutMs ?? 15_000;
108
+ const originalPolicy = structuredClone(original), publicationWait = options.waitForPublicationMs ?? 0;
109
+ if (!list.length || list.length > 16 || !Number.isSafeInteger(timeout) || timeout < 1 || timeout > 60_000)
110
+ throw new Error('Invalid verifier snapshot hosts or timeout');
111
+ if (!Number.isSafeInteger(publicationWait) || publicationWait < 0 || publicationWait > 150_000)
112
+ throw new Error('Invalid verifier snapshot publication wait');
113
+ let keptSnapshots = keptByFetch.get(doFetch);
114
+ if (!keptSnapshots)
115
+ keptByFetch.set(doFetch, keptSnapshots = new Map());
116
+ const key = snapshotKey(registry, originalPolicy), kept = keptSnapshots.get(key);
117
+ if (kept && list.includes(kept.host)) {
118
+ try {
119
+ return { witnesses: drawnVerifierWitnesses(structuredClone(kept.artifact), originalPolicy, registry), artifact: structuredClone(kept.artifact), host: kept.host };
120
+ }
121
+ catch {
122
+ keptSnapshots.delete(key);
123
+ }
124
+ }
125
+ const deadline = Date.now() + publicationWait;
126
+ for (;;) {
127
+ let unpublished = 0;
128
+ for (const host of list) {
129
+ const url = new URL(host);
130
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash)
131
+ throw new Error('Invalid verifier snapshot host');
132
+ }
133
+ for (const host of list) {
134
+ options.signal?.throwIfAborted();
135
+ try {
136
+ const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(timeout)]) : AbortSignal.timeout(timeout);
137
+ const response = await doFetch(host.replace(/\/$/, '') + '/v1/verifier-set/' + originalPolicy.verification_epoch, { redirect: 'error', signal, headers: { accept: 'application/json', 'accept-encoding': 'identity' } });
138
+ if (response.status === 404) {
139
+ unpublished++;
140
+ await response.body?.cancel().catch(() => { });
141
+ continue;
142
+ }
143
+ const encoding = response.headers.get('content-encoding');
144
+ if (response.status !== 200 || response.headers.get('content-type')?.split(';')[0]?.trim() !== 'application/json'
145
+ || (encoding && encoding !== 'identity') || !response.body)
146
+ continue;
147
+ const reader = response.body.getReader(), chunks = [];
148
+ let length = 0;
149
+ try {
150
+ for (;;) {
151
+ const { done, value } = await reader.read();
152
+ if (done)
153
+ break;
154
+ length += value.length;
155
+ if (length > MAX_SNAPSHOT_BYTES)
156
+ throw new Error('Snapshot exceeds the read-only artifact bound');
157
+ chunks.push(value);
158
+ }
159
+ }
160
+ finally {
161
+ await reader.cancel().catch(() => { });
162
+ }
163
+ const bytes = new Uint8Array(length);
164
+ let offset = 0;
165
+ for (const chunk of chunks) {
166
+ bytes.set(chunk, offset);
167
+ offset += chunk.length;
168
+ }
169
+ const artifact = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
170
+ const witnesses = drawnVerifierWitnesses(artifact, originalPolicy, registry);
171
+ keptSnapshots.delete(key);
172
+ if (keptSnapshots.size >= MAX_KEPT_SNAPSHOTS)
173
+ keptSnapshots.delete(keptSnapshots.keys().next().value);
174
+ keptSnapshots.set(key, { artifact: structuredClone(artifact), host });
175
+ return { witnesses, artifact, host };
176
+ }
177
+ catch {
178
+ options.signal?.throwIfAborted();
179
+ }
180
+ }
181
+ // A freshly anchored epoch may reach the public artifact index a tick later.
182
+ // Only unanimous 404s permit another read of this exact original policy.
183
+ // Wrong artifacts, authentication errors and transport failures remain final.
184
+ if (unpublished !== list.length || publicationWait === 0 || Date.now() >= deadline)
185
+ break;
186
+ await publicationDelay(Math.min(1_000, deadline - Date.now()), options.signal);
187
+ }
188
+ throw new Error('No approved accountant served a verifiable original verifier snapshot');
189
+ }
190
+ function publicationDelay(ms, signal) {
191
+ signal?.throwIfAborted();
192
+ return new Promise((resolve, reject) => {
193
+ const abort = () => { clearTimeout(timer); reject(signal.reason); };
194
+ const timer = setTimeout(() => { signal?.removeEventListener('abort', abort); resolve(); }, ms);
195
+ signal?.addEventListener('abort', abort, { once: true });
196
+ });
197
+ }