@integraledger/profile-facilitator 0.1.0 → 0.2.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/dist/polkadot.js CHANGED
@@ -5,9 +5,10 @@
5
5
  */
6
6
  import { ApiPromise } from "@polkadot/api";
7
7
  import { blake2b } from "@noble/hashes/blake2.js";
8
+ import { isRefusal } from "@integraledger/lcp";
8
9
  import { decodeProfileCall, exactPolkadotRemark, extrinsicHash, polkadotPairingOf, ss58Decode, } from "@integraledger/lcp/polkadot";
9
10
  import { failed, invalid, isObject, isPending, operatorLog, pending, } from "./answers.js";
10
- import { NODE_TIMEOUT_MS, NodeError, postJson, sleep, within } from "./http.js";
11
+ import { NODE_MAX_BYTES, NODE_TIMEOUT_MS, NodeError, Slots, postJson, sleep, within } from "./http.js";
11
12
  import { answerReserve, inTime } from "./store.js";
12
13
  const POLL_MS = 1_000;
13
14
  /** The longest a metadata load may take: its calls are each bounded, and this bounds them together. */
@@ -16,12 +17,25 @@ const INIT_TIMEOUT_MS = 30_000;
16
17
  const SLOW_BLOCK_MS = 12_000;
17
18
  /** `TransactionSource::External`. */
18
19
  const EXTERNAL = "02";
20
+ /**
21
+ * How many `chain_getBlock` reads, each bounded by the runtime's `System.BlockLength`, run at once in this process:
22
+ * for Polkadot Asset Hub's runtime 2005000, at most 4 × 28,504,064 = 114,016,256 bytes of block answers.
23
+ */
24
+ export const BLOCK_READS = 4;
25
+ /** The slots of `BLOCK_READS`, shared by every network and every scan in this process. */
26
+ export const blockReads = new Slots(BLOCK_READS);
19
27
  /** The JSON-RPC error `author_submitExtrinsic` gives for an extrinsic already in the pool. */
20
28
  const ALREADY_IMPORTED = 1013;
21
29
  /** The JSON-RPC error for an extrinsic the pool refuses as invalid; its message or data names the reason. */
22
30
  const INVALID_TRANSACTION = 1010;
23
31
  /** The JSON-RPC error for an extrinsic the pool has recently seen and will not take again for a while. */
24
32
  const TEMPORARILY_BANNED = 1012;
33
+ /** No slot of `blockReads` came free before the pass's deadline, so block `n` was not read. */
34
+ class NoBlockReadSlot extends Error {
35
+ constructor(n) {
36
+ super(`block ${n}: no block read slot before the deadline`);
37
+ }
38
+ }
25
39
  /** A JSON-RPC error answer: the node read the call and refused it. */
26
40
  class RpcError extends Error {
27
41
  code;
@@ -41,8 +55,8 @@ function seenBefore(e) {
41
55
  return true;
42
56
  return e.code === INVALID_TRANSACTION && /outdated|stale/i.test(`${e.message} ${e.data}`);
43
57
  }
44
- async function rpc(url, method, params, timeoutMs) {
45
- const answer = await postJson(url, { jsonrpc: "2.0", id: 1, method, params }, timeoutMs);
58
+ async function rpc(url, method, params, timeoutMs, maxBytes) {
59
+ const answer = await postJson(url, { jsonrpc: "2.0", id: 1, method, params }, timeoutMs, maxBytes);
46
60
  if (!isObject(answer))
47
61
  throw new NodeError("malformed", true, `${method}: not a JSON-RPC answer`);
48
62
  const error = answer["error"];
@@ -92,6 +106,24 @@ function blockNumber(header) {
92
106
  return Number.parseInt(n, 16);
93
107
  return undefined;
94
108
  }
109
+ function isCount(v) {
110
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
111
+ }
112
+ /** `System.BlockLength` and `System.BlockHashCount` from the metadata; undefined when either is missing or malformed. */
113
+ function runtimeBounds(api) {
114
+ const system = api.consts["system"];
115
+ const length = system?.["blockLength"]?.toJSON();
116
+ const count = Number(system?.["blockHashCount"]?.toString());
117
+ if (!isObject(length) || !isObject(length["max"]) || !isCount(count) || count === 0)
118
+ return undefined;
119
+ const classes = [length["max"]["normal"], length["max"]["operational"], length["max"]["mandatory"]];
120
+ if (!classes.every(isCount))
121
+ return undefined;
122
+ const header = length["maxHeaderSize"];
123
+ const headerBytes = isCount(header) ? header : 0;
124
+ const body = Math.max(...classes);
125
+ return { blockAnswerBytes: NODE_MAX_BYTES + Math.ceil((9 * body) / 2) + 7 * headerBytes, blockHashCount: count };
126
+ }
95
127
  export function createPolkadot(nodes, s, settleWaitMs) {
96
128
  const byNetwork = new Map(nodes.map((n) => [n.network, n]));
97
129
  const apis = new Map();
@@ -148,7 +180,7 @@ export function createPolkadot(nodes, s, settleWaitMs) {
148
180
  return "invalid_payload";
149
181
  const profile = decodeProfileCall(Buffer.from(call.slice(2), "hex"));
150
182
  const dest = ss58Decode(req.payTo);
151
- if ("refused" in profile || "refused" in dest)
183
+ if (isRefusal(profile) || isRefusal(dest))
152
184
  return "invalid_payload";
153
185
  if (profile.assetId !== Number(req.asset) || profile.amount !== BigInt(req.amount))
154
186
  return "invalid_payload";
@@ -195,7 +227,8 @@ export function createPolkadot(nodes, s, settleWaitMs) {
195
227
  if (!xt.era.isMortalEra)
196
228
  return "invalid_payload";
197
229
  const eventsKey = api.query["system"]?.["events"]?.key();
198
- if (eventsKey === undefined)
230
+ const bounds = runtimeBounds(api);
231
+ if (eventsKey === undefined || bounds === undefined)
199
232
  return "unexpected_verify_error";
200
233
  return {
201
234
  network: l.node.network,
@@ -207,11 +240,22 @@ export function createPolkadot(nodes, s, settleWaitMs) {
207
240
  remarkHash: l.remarkHash,
208
241
  era: xt.era.asMortalEra,
209
242
  eventsKey,
243
+ bounds,
210
244
  };
211
245
  }
246
+ /**
247
+ * The last block that can include the extrinsic, for a block `at` from its era's birth to that last block: the era's
248
+ * last block, and no later than `BlockHashCount` + 1 blocks after its birth. Each block's execution keeps the hashes of
249
+ * the `BlockHashCount` + 1 blocks before it in `System.BlockHash`, and `CheckMortality` refuses an extrinsic whose
250
+ * birth block's hash is not there.
251
+ */
252
+ function lastBlock(c, at) {
253
+ const birth = c.era.birth(at);
254
+ return Math.min(c.era.death(at) - 1, birth + c.bounds.blockHashCount + 1);
255
+ }
212
256
  /**
213
257
  * `TaggedTransactionQueue_validate_transaction` at the best block, within `timeoutMs`: the best block's height, and
214
- * when the era ends.
258
+ * when the last block that can include the extrinsic ends.
215
259
  */
216
260
  async function validate(c, timeoutMs = 3 * NODE_TIMEOUT_MS) {
217
261
  const url = byNetwork.get(c.network).rpc;
@@ -235,7 +279,7 @@ export function createPolkadot(nodes, s, settleWaitMs) {
235
279
  return "unexpected_verify_error";
236
280
  if (!validity.startsWith("0x00"))
237
281
  return "invalid_transaction";
238
- const blocksLeft = Math.max(0, c.era.death(height) - height);
282
+ const blocksLeft = Math.max(0, lastBlock(c, height) + 1 - height);
239
283
  return { best: height, until: new Date(Date.now() + blocksLeft * SLOW_BLOCK_MS) };
240
284
  }
241
285
  async function verify(r) {
@@ -278,64 +322,126 @@ export function createPolkadot(nodes, s, settleWaitMs) {
278
322
  return undefined;
279
323
  }
280
324
  }
281
- /** The extrinsic's index in the block at `n`, and the block's hash; the index is -1 when the block does not hold it. */
325
+ /** The head's height; undefined when the node does not give it. */
326
+ async function headHeight(url, left) {
327
+ try {
328
+ return blockNumber(await rpc(url, "chain_getHeader", [], left()));
329
+ }
330
+ catch {
331
+ return undefined;
332
+ }
333
+ }
334
+ /**
335
+ * The extrinsic's index in the block at `n`, and the block's hash; the index is -1 when the block does not hold it.
336
+ * The block is read in one of `blockReads`' slots, waited for until `left()` ends; a read that cannot start by then
337
+ * throws `NoBlockReadSlot`.
338
+ */
282
339
  async function findIn(c, url, n, left) {
283
340
  const hash = await rpc(url, "chain_getBlockHash", [n], left());
284
- const block = await rpc(url, "chain_getBlock", [hash], left());
341
+ const release = await blockReads.take(left());
342
+ if (release === undefined)
343
+ throw new NoBlockReadSlot(n);
344
+ let block;
345
+ try {
346
+ block = await rpc(url, "chain_getBlock", [hash], left(), c.bounds.blockAnswerBytes);
347
+ }
348
+ finally {
349
+ release();
350
+ }
285
351
  const xts = isObject(block) && isObject(block["block"]) ? block["block"]["extrinsics"] : undefined;
286
352
  if (typeof hash !== "string" || !Array.isArray(xts))
287
353
  throw new NodeError("malformed", true, `block ${n}`);
288
354
  return { hash, index: xts.findIndex((x) => isLowerHex(x) && extrinsicHash(Buffer.from(x.slice(2), "hex")) === c.id) };
289
355
  }
290
356
  /**
291
- * One pass until `deadline`, no further than the era's last block. First the blocks from `at.proven` up to the
292
- * finalized head, which are read at finality; once every block to the era's last is read so, the extrinsic can never
293
- * be included, and the answer is `invalid_transaction_state` with its hash. Then the blocks above them, up to the head,
294
- * where only a success is an answer: a failure there waits until its block is final. Gives the final answer, or where
295
- * the scan has got to.
357
+ * Block `n` read for the extrinsic: the answer when the block holds it, `absent` when it does not, `unreadable` (with
358
+ * the reason) when the node gives neither the block nor, for the block that holds it, its events, or when no block
359
+ * read slot comes free before the deadline, and `stopped` when the deadline ends a read that started.
360
+ */
361
+ async function readBlock(c, url, n, left, final) {
362
+ try {
363
+ const found = await findIn(c, url, n, left);
364
+ if (found.index < 0)
365
+ return "absent";
366
+ return await included(c, url, found.hash, found.index, left(), final);
367
+ }
368
+ catch (e) {
369
+ if (!(e instanceof NoBlockReadSlot) && left() <= 0)
370
+ return "stopped";
371
+ return { unreadable: e instanceof Error ? e.message : String(e) };
372
+ }
373
+ }
374
+ /**
375
+ * One pass until `deadline`, no further than the last block that can include the extrinsic. First the blocks from
376
+ * `at.proven` up to the finalized head, read at finality: a block that cannot be read is recorded as unread and
377
+ * skipped, and the pass goes on to the blocks after it. Then the blocks above them, up to the head, where only a
378
+ * success is an answer: a failure there waits until its block is final, and a block that cannot be read is skipped,
379
+ * since it is read again at finality. Then, with the time left, the blocks recorded as unread before this pass are
380
+ * read again. Once every block to the last is read at finality, and none is unread, the extrinsic can never be
381
+ * included, and the answer is `invalid_transaction_state` with its hash. Gives the final answer, or where the scan has
382
+ * got to.
296
383
  */
297
384
  async function scanOnce(c, since, at, deadline) {
298
385
  const url = byNetwork.get(c.network).rpc;
299
386
  const left = () => deadline - performance.now();
300
- const last = c.era.death(since) - 1;
387
+ const last = lastBlock(c, since);
301
388
  let { proven, next } = at;
302
- try {
303
- const finalized = await finalizedHeight(url, deadline);
304
- while (finalized !== undefined && proven <= Math.min(finalized, last) && left() > 0) {
305
- const found = await findIn(c, url, proven, left);
306
- if (found.index >= 0)
307
- return { answer: await included(c, url, found.hash, found.index, left(), true) };
308
- proven += 1;
389
+ const unread = new Set(at.unread);
390
+ const resolved = new Set(at.resolved);
391
+ const position = () => ({ proven, next, unread: [...unread].sort((a, b) => a - b), resolved: [...resolved] });
392
+ const finalized = await finalizedHeight(url, deadline);
393
+ while (finalized !== undefined && proven <= Math.min(finalized, last) && left() > 0) {
394
+ const read = await readBlock(c, url, proven, left, true);
395
+ if (read === "stopped")
396
+ return position();
397
+ if (typeof read === "object" && "unreadable" in read) {
398
+ unread.add(proven);
399
+ operatorLog({ event: "block-unreadable", network: c.network, transaction: c.id, block: proven, reason: read.unreadable });
309
400
  }
310
- if (proven > last) {
311
- operatorLog({ event: "settlement-expired", network: c.network, transaction: c.id });
312
- return { answer: failed("invalid_transaction_state", c.id, c.network) };
401
+ else if (read !== "absent") {
402
+ return { answer: read };
313
403
  }
314
- next = Math.max(next, proven);
315
- const head = blockNumber(await rpc(url, "chain_getHeader", [], left()));
316
- while (head !== undefined && next <= Math.min(head, last) && left() > 0) {
317
- const found = await findIn(c, url, next, left);
318
- if (found.index >= 0) {
319
- const answer = await included(c, url, found.hash, found.index, left(), false);
320
- if (answer.success)
321
- return { answer };
322
- break;
323
- }
324
- next += 1;
404
+ proven += 1;
405
+ }
406
+ next = Math.max(next, proven);
407
+ const head = await headHeight(url, left);
408
+ while (head !== undefined && next <= Math.min(head, last) && left() > 0) {
409
+ const read = await readBlock(c, url, next, left, false);
410
+ if (read === "stopped")
411
+ return position();
412
+ if (typeof read === "object" && !("unreadable" in read)) {
413
+ if (read.success)
414
+ return { answer: read };
415
+ break;
325
416
  }
417
+ next += 1;
326
418
  }
327
- catch {
328
- // A failed read leaves the scan where it is; the next poll reads again.
419
+ for (const n of at.unread) {
420
+ if (finalized === undefined || n > finalized || left() <= 0)
421
+ break;
422
+ const read = await readBlock(c, url, n, left, true);
423
+ if (read === "stopped")
424
+ return position();
425
+ if (typeof read === "object" && "unreadable" in read)
426
+ continue;
427
+ unread.delete(n);
428
+ resolved.add(n);
429
+ if (read !== "absent")
430
+ return { answer: read };
329
431
  }
330
- return { proven, next };
432
+ if (proven > last && unread.size === 0) {
433
+ operatorLog({ event: "settlement-expired", network: c.network, transaction: c.id });
434
+ return { answer: failed("invalid_transaction_state", c.id, c.network) };
435
+ }
436
+ return position();
331
437
  }
332
438
  /**
333
- * Scans for the extrinsic from `since` every second until `deadline`, reading the stored answer too when `stored` is
334
- * set, and answers with the first final answer either gives. Blocks read at finality that do not hold it move the
335
- * stored `since` on. Submits nothing.
439
+ * Scans for the extrinsic from `since`, with the stored `unread` blocks, every second until `deadline`, reading the
440
+ * stored answer too when `stored` is set, and answers with the first final answer either gives. Where the scan got to
441
+ * at finality is stored: `since` moves on, and the blocks it could not read are recorded. Submits nothing.
336
442
  */
337
- async function scan(c, since, deadline, stored) {
338
- let at = { proven: since, next: since };
443
+ async function scan(c, since, unread, deadline, stored) {
444
+ let at = { proven: since, next: since, unread, resolved: [] };
339
445
  for (;;) {
340
446
  if (stored) {
341
447
  const row = await inTime(s.read(c.network, c.id), deadline).catch(() => undefined);
@@ -347,8 +453,10 @@ export function createPolkadot(nodes, s, settleWaitMs) {
347
453
  return step.answer;
348
454
  at = step;
349
455
  if (performance.now() + POLL_MS > deadline) {
350
- if (at.proven > since)
351
- void s.advance(c.network, c.id, at.proven).catch(() => { });
456
+ if (at.proven > since || at.unread.length > 0 || at.resolved.length > 0) {
457
+ const to = Math.min(at.proven, lastBlock(c, since));
458
+ void s.advance(c.network, c.id, { from: since, to, unread: at.unread, resolved: at.resolved }).catch(() => { });
459
+ }
352
460
  return pending(c.id, c.network);
353
461
  }
354
462
  await sleep(POLL_MS);
@@ -371,30 +479,54 @@ export function createPolkadot(nodes, s, settleWaitMs) {
371
479
  if (!(e instanceof RpcError))
372
480
  return pending(c.id, c.network);
373
481
  }
374
- return scan(c, since, deadline, false);
482
+ return scan(c, since, [], deadline, false);
375
483
  }
376
- /** Stores the answer, unless the row holds a final one; a failed write leaves the row for a later read of the chain. */
484
+ /**
485
+ * What a repeated `/settle` gets for a stored answer. A success is given once, to the settle that stored it, so the
486
+ * payment is consumed: a repeat gets `invalid_transaction_state` with the success's transaction (x402's `exact`
487
+ * family: a consumed primitive produces a settlement failure, never a success). Any other answer is given as stored.
488
+ */
489
+ function repeatOf(stored) {
490
+ if (!stored.success)
491
+ return stored;
492
+ operatorLog({ event: "settlement-consumed", network: stored.network, transaction: stored.transaction });
493
+ return failed("invalid_transaction_state", stored.transaction, stored.network);
494
+ }
495
+ /**
496
+ * Stores the answer, unless the row holds a final one. A success is given only by the settle whose write stored it:
497
+ * when the row already holds a final answer, the answer is what a repeat gets for it, and when the write fails, it is
498
+ * pending with the hash, for a later read of the chain. Any other answer is given whether or not it is stored; a
499
+ * failed write leaves the row for a later read of the chain.
500
+ */
377
501
  async function keep(c, answer, deadline) {
378
- await inTime(s.answer(c.network, c.id, answer), deadline).catch(() => {
502
+ let wrote;
503
+ try {
504
+ wrote = await inTime(s.answer(c.network, c.id, answer), deadline);
505
+ }
506
+ catch {
379
507
  operatorLog({ event: "answer-not-stored", network: c.network, transaction: c.id });
380
- });
381
- return answer;
508
+ return answer.success ? pending(c.id, c.network) : answer;
509
+ }
510
+ if (!answer.success || wrote)
511
+ return answer;
512
+ const row = await inTime(s.read(c.network, c.id), deadline).catch(() => undefined);
513
+ return row?.state === "answered" && !isPending(row.answer) ? repeatOf(row.answer) : pending(c.id, c.network);
382
514
  }
383
515
  /**
384
516
  * Reads a claimed id, or a stored pending answer, again from the chain until the answer's reserve before `deadline`,
385
- * then stores what it read.
517
+ * from the stored `since` and `unread`, then stores what it read.
386
518
  */
387
- async function follow(l, since, deadline) {
519
+ async function follow(l, since, unread, deadline) {
388
520
  const c = await decode(l, deadline - performance.now());
389
521
  if (typeof c === "string" || since === null) {
390
522
  const row = await inTime(s.read(l.node.network, l.id), deadline).catch(() => undefined);
391
- return row?.state === "answered" ? row.answer : pending(l.id, l.node.network);
523
+ return row?.state === "answered" ? repeatOf(row.answer) : pending(l.id, l.node.network);
392
524
  }
393
- return keep(c, await scan(c, since, deadline - answerReserve(settleWaitMs), true), deadline);
525
+ return keep(c, await scan(c, since, unread, deadline - answerReserve(settleWaitMs), true), deadline);
394
526
  }
395
527
  /**
396
528
  * Answers within `settleWaitMs`. The stored answer is read before the node is asked anything, and a final one is
397
- * given as it is. A claimed id, or a stored pending answer, is read again from the chain. An answer with no
529
+ * given as a repeat gets it. A claimed id, or a stored pending answer, is read again from the chain. An answer with no
398
530
  * transaction says nothing was submitted, so it is given only for an id the store does not hold: a submission the node
399
531
  * refused releases the claim, and when nothing is released the answer is pending with its hash. When the store cannot
400
532
  * be read, the facilitator cannot know whether the extrinsic was submitted, so the answer is pending with its hash. The
@@ -417,9 +549,9 @@ export function createPolkadot(nodes, s, settleWaitMs) {
417
549
  return pending(l.id, l.node.network);
418
550
  }
419
551
  if (stored.state === "answered" && !isPending(stored.answer))
420
- return stored.answer;
552
+ return repeatOf(stored.answer);
421
553
  if (stored.state !== "none")
422
- return follow(l, stored.since, deadline);
554
+ return follow(l, stored.since, stored.unread, deadline);
423
555
  const c = await decode(l, left());
424
556
  if (typeof c === "string")
425
557
  return failed(settleReason(c), "", network);
@@ -430,7 +562,7 @@ export function createPolkadot(nodes, s, settleWaitMs) {
430
562
  if (left() <= 0)
431
563
  return failed("unexpected_settle_error", "", network);
432
564
  const birth = c.era.birth(v.best);
433
- const since = finalized === undefined ? birth : Math.max(birth, finalized + 1);
565
+ const since = Math.min(finalized === undefined ? birth : Math.max(birth, finalized + 1), lastBlock(c, v.best));
434
566
  let won;
435
567
  try {
436
568
  won = await inTime(s.claim(c.network, c.id, v.until, since), deadline);
@@ -440,7 +572,8 @@ export function createPolkadot(nodes, s, settleWaitMs) {
440
572
  }
441
573
  if (!won) {
442
574
  const row = await inTime(s.read(c.network, c.id), deadline).catch(() => undefined);
443
- return follow(l, row !== undefined && row.state !== "none" ? row.since : null, deadline);
575
+ const claimed = row !== undefined && row.state !== "none" ? row : undefined;
576
+ return follow(l, claimed?.since ?? null, claimed?.unread ?? [], deadline);
444
577
  }
445
578
  const answer = await submit(c, since, deadline - answerReserve(settleWaitMs));
446
579
  if (answer.success || answer.transaction !== "")
package/dist/store.d.ts CHANGED
@@ -1,36 +1,49 @@
1
1
  import { type SettleAnswer } from "./answers.js";
2
- export declare const SCHEMA = "CREATE TABLE IF NOT EXISTS settlement (\n network text NOT NULL,\n id text NOT NULL,\n answer jsonb,\n until timestamptz NOT NULL,\n since bigint,\n PRIMARY KEY (network, id)\n)";
2
+ /** The table, and the index the sweep reads: the rows whose answer is final, by `until`. */
3
+ export declare const SCHEMA = "CREATE TABLE IF NOT EXISTS settlement (\n network text NOT NULL,\n id text NOT NULL,\n answer jsonb,\n until timestamptz NOT NULL,\n since bigint,\n unread bigint[] NOT NULL DEFAULT '{}',\n PRIMARY KEY (network, id)\n);\nCREATE INDEX IF NOT EXISTS settlement_final_until ON settlement (until) WHERE answer IS NOT NULL AND answer->>'errorReason' IS DISTINCT FROM 'settlement_pending'";
3
4
  /** The bound on acquiring a connection, on each query as the client waits for it, and on each statement in the server. */
4
5
  export declare const STORE_TIMEOUT_MS = 5000;
5
- /** How long a row is kept after `until`. */
6
+ /** How long a row whose answer is final is kept after `until`. */
6
7
  export declare const KEEP_AFTER_UNTIL_MS: number;
7
8
  /**
8
9
  * What the table holds for an id: nothing, a claim whose answer is not written yet, or the answer. `since` is, for a
9
- * Polkadot extrinsic, the first block not yet shown at finality to lack it: at the claim, the block after the finalized
10
- * head read before validation (never before the era's birth), and later moved on past blocks read at finality that do
11
- * not hold it. It is null for Tron.
10
+ * Polkadot extrinsic, the first block the scan has not yet read at finality: at the claim, the block after the finalized
11
+ * head read before validation (never before the era's birth), and later moved on past the blocks read at finality. It
12
+ * is null for Tron. `unread` is, for a Polkadot extrinsic, the finalized blocks below `since` that could not be read:
13
+ * none of them is shown to lack the extrinsic, so each is read again. It is empty for Tron.
12
14
  */
13
15
  export type Stored = {
14
16
  state: "none";
15
17
  } | {
16
18
  state: "claimed";
17
19
  since: number | null;
20
+ unread: number[];
18
21
  } | {
19
22
  state: "answered";
20
23
  answer: SettleAnswer;
21
24
  since: number | null;
25
+ unread: number[];
22
26
  };
23
27
  export interface SettlementStore {
24
28
  read(network: string, id: string): Promise<Stored>;
25
29
  /** True when this call inserted the row, and so owns the submission. */
26
30
  claim(network: string, id: string, until: Date, since?: number): Promise<boolean>;
27
- /** Writes the answer unless the row already holds a final one. */
28
- answer(network: string, id: string, answer: SettleAnswer): Promise<void>;
31
+ /** Writes the answer unless the row already holds a final one. True when this call wrote it. */
32
+ answer(network: string, id: string, answer: SettleAnswer): Promise<boolean>;
29
33
  /** Removes a claim that has no answer: the claimant submitted nothing. True when a row was removed. */
30
34
  release(network: string, id: string): Promise<boolean>;
31
- /** Moves `since` on to `block`, never back. */
32
- advance(network: string, id: string, block: number): Promise<void>;
33
- /** Drops the rows whose `until` is more than `KEEP_AFTER_UNTIL_MS` past. */
35
+ /**
36
+ * Moves `since` on to `to`, never back, after a scan that read every finalized block from `from` up to `to` except
37
+ * `unread`, and read `resolved`, blocks of the stored `unread` it read again. The stored `unread` gains `unread`,
38
+ * and keeps every block this scan did not read: a concurrent scan's record is never lost.
39
+ */
40
+ advance(network: string, id: string, scan: {
41
+ from: number;
42
+ to: number;
43
+ unread: number[];
44
+ resolved: number[];
45
+ }): Promise<void>;
46
+ /** Drops the rows whose answer is final and whose `until` is more than `KEEP_AFTER_UNTIL_MS` past. */
34
47
  drop(): Promise<void>;
35
48
  close(): Promise<void>;
36
49
  }
package/dist/store.js CHANGED
@@ -1,24 +1,32 @@
1
1
  /**
2
2
  * The deduplication table: one row per settled payment, keyed by network and transaction id, holding the answer the
3
3
  * first `/settle` gave. A row is claimed by one conditional insert, so concurrent settles of one payment submit once.
4
- * A final answer is never replaced; a pending one is replaced by what a later read of the chain shows. A row is kept
5
- * until `KEEP_AFTER_UNTIL_MS` after its validity window has ended, so a repeat in that time reads the stored answer and
6
- * the chain before anything is verified again. Every call to the database is bounded by `STORE_TIMEOUT_MS`.
4
+ * A final answer is never replaced; a pending one is replaced by what a later read of the chain shows. A row whose
5
+ * answer is final is kept until `KEEP_AFTER_UNTIL_MS` after its validity window has ended, so a repeat in that time
6
+ * reads the stored answer and the chain before anything is verified again. A row whose answer is not final (a claim
7
+ * with no answer yet, or `settlement_pending`) is kept until a read of the chain makes it final, so a repeat never
8
+ * finds its id missing and never answers that nothing was broadcast. Every call to the database is bounded by
9
+ * `STORE_TIMEOUT_MS`.
7
10
  */
8
11
  import pg from "pg";
9
12
  import { isPending } from "./answers.js";
10
13
  import { within } from "./http.js";
14
+ /** A row's answer is final when it is written and is not `settlement_pending`. */
15
+ const FINAL = "answer IS NOT NULL AND answer->>'errorReason' IS DISTINCT FROM 'settlement_pending'";
16
+ /** The table, and the index the sweep reads: the rows whose answer is final, by `until`. */
11
17
  export const SCHEMA = `CREATE TABLE IF NOT EXISTS settlement (
12
18
  network text NOT NULL,
13
19
  id text NOT NULL,
14
20
  answer jsonb,
15
21
  until timestamptz NOT NULL,
16
22
  since bigint,
23
+ unread bigint[] NOT NULL DEFAULT '{}',
17
24
  PRIMARY KEY (network, id)
18
- )`;
25
+ );
26
+ CREATE INDEX IF NOT EXISTS settlement_final_until ON settlement (until) WHERE ${FINAL}`;
19
27
  /** The bound on acquiring a connection, on each query as the client waits for it, and on each statement in the server. */
20
28
  export const STORE_TIMEOUT_MS = 5_000;
21
- /** How long a row is kept after `until`. */
29
+ /** How long a row whose answer is final is kept after `until`. */
22
30
  export const KEEP_AFTER_UNTIL_MS = 24 * 60 * 60 * 1000;
23
31
  const DROP_EVERY_MS = 60_000;
24
32
  export async function openStore(url) {
@@ -33,34 +41,41 @@ export async function openStore(url) {
33
41
  await pool.query(SCHEMA);
34
42
  const store = {
35
43
  async read(network, id) {
36
- const r = await pool.query("SELECT answer, since FROM settlement WHERE network = $1 AND id = $2", [network, id]);
44
+ const r = await pool.query("SELECT answer, since, unread FROM settlement WHERE network = $1 AND id = $2", [network, id]);
37
45
  const row = r.rows[0];
38
46
  if (row === undefined)
39
47
  return { state: "none" };
40
48
  const since = row.since === null ? null : Number(row.since);
41
- return row.answer === null ? { state: "claimed", since } : { state: "answered", answer: row.answer, since };
49
+ const unread = row.unread.map(Number);
50
+ return row.answer === null
51
+ ? { state: "claimed", since, unread }
52
+ : { state: "answered", answer: row.answer, since, unread };
42
53
  },
43
54
  async claim(network, id, until, since) {
44
55
  const r = await pool.query("INSERT INTO settlement (network, id, answer, until, since) VALUES ($1, $2, NULL, $3, $4) ON CONFLICT DO NOTHING", [network, id, until.toISOString(), since ?? null]);
45
56
  return r.rowCount === 1;
46
57
  },
47
58
  async answer(network, id, answer) {
48
- await pool.query(`UPDATE settlement SET answer = $3 WHERE network = $1 AND id = $2
59
+ const r = await pool.query(`UPDATE settlement SET answer = $3 WHERE network = $1 AND id = $2
49
60
  AND (answer IS NULL OR answer->>'errorReason' = 'settlement_pending')${isPending(answer) ? " AND answer IS NULL" : ""}`, [network, id, JSON.stringify(answer)]);
61
+ return r.rowCount === 1;
50
62
  },
51
63
  async release(network, id) {
52
64
  const r = await pool.query("DELETE FROM settlement WHERE network = $1 AND id = $2 AND answer IS NULL", [network, id]);
53
65
  return r.rowCount === 1;
54
66
  },
55
- async advance(network, id, block) {
56
- await pool.query("UPDATE settlement SET since = GREATEST(since, $3) WHERE network = $1 AND id = $2", [
57
- network,
58
- id,
59
- block,
60
- ]);
67
+ async advance(network, id, scan) {
68
+ await pool.query(`UPDATE settlement SET since = GREATEST(since, $3),
69
+ unread = ARRAY(
70
+ SELECT DISTINCT u FROM unnest(unread || $5::bigint[]) AS u
71
+ WHERE u = ANY($5::bigint[]) OR NOT (u = ANY($6::bigint[]) OR (u >= $4 AND u < $3))
72
+ ORDER BY u)
73
+ WHERE network = $1 AND id = $2`, [network, id, scan.to, scan.from, scan.unread, scan.resolved]);
61
74
  },
62
75
  async drop() {
63
- await pool.query("DELETE FROM settlement WHERE until + $1 * interval '1 millisecond' < now()", [KEEP_AFTER_UNTIL_MS]);
76
+ await pool.query(`DELETE FROM settlement WHERE until < now() - $1 * interval '1 millisecond' AND ${FINAL}`, [
77
+ KEEP_AFTER_UNTIL_MS,
78
+ ]);
64
79
  },
65
80
  async close() {
66
81
  clearInterval(timer);