@fangorn-network/sdk 0.2.1 → 0.2.3

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/lib/config.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as viem_chains0 from "viem/chains";
2
2
  import * as viem0 from "viem";
3
- import { Chain, Hex } from "viem";
3
+ import { Chain, Hex, HttpTransportConfig } from "viem";
4
4
 
5
5
  //#region src/config.d.ts
6
6
 
@@ -19,6 +19,7 @@ interface NetworkConfig {
19
19
  caip2: number;
20
20
  ipfsGateway: string;
21
21
  logWindow?: bigint;
22
+ rpcRetry?: Pick<HttpTransportConfig, "retryCount" | "retryDelay">;
22
23
  signedUrlWorker?: string;
23
24
  keyServer?: string;
24
25
  }
@@ -146,7 +146,9 @@ declare class ChainRegistry implements Registry {
146
146
  log(filter: LogFilter, from: bigint, to?: bigint): Promise<UpdateEntry[]>;
147
147
  /**
148
148
  * Old-version logs don't carry their block's timestamp: one block read per
149
- * distinct block. New-version logs carry it.
149
+ * distinct block. New-version logs carry it. At most TIMESTAMP_READS at a time:
150
+ * a first catch-up reads hundreds, and a public RPC throttles them all at once
151
+ * (each retry wave was another burst). A failed read stops the rest.
150
152
  */
151
153
  private withTimestamps;
152
154
  watch(filter: LogFilter, onEntry: (entry: UpdateEntry) => void, onError?: (err: Error) => void, pollingInterval?: number): () => void;
@@ -13,6 +13,8 @@ const ZERO_HEAD = "0x00000000000000000000000000000000000000000000000000000000000
13
13
  const EPOCH_SECONDS = 3600;
14
14
  /** W: how many epochs a commit may lag the ordering's clock. */
15
15
  const WINDOW = 24;
16
+ /** How many block reads `log` keeps in flight for old-version timestamps. */
17
+ const TIMESTAMP_READS = 8;
16
18
  function epochOf(unixSeconds) {
17
19
  return Math.floor(Number(unixSeconds) / EPOCH_SECONDS);
18
20
  }
@@ -154,11 +156,23 @@ var ChainRegistry = class {
154
156
  }
155
157
  /**
156
158
  * Old-version logs don't carry their block's timestamp: one block read per
157
- * distinct block. New-version logs carry it.
159
+ * distinct block. New-version logs carry it. At most TIMESTAMP_READS at a time:
160
+ * a first catch-up reads hundreds, and a public RPC throttles them all at once
161
+ * (each retry wave was another burst). A failed read stops the rest.
158
162
  */
159
163
  async withTimestamps(logs) {
160
- const blocks = [...new Set(logs.filter((l) => l.args.timestamp === void 0).map((l) => l.blockNumber))];
161
- const times = new Map(await Promise.all(blocks.map(async (n) => [n, (await this.publicClient.getBlock({ blockNumber: n })).timestamp])));
164
+ const queue = [...new Set(logs.filter((l) => l.args.timestamp === void 0).map((l) => l.blockNumber))];
165
+ const times = /* @__PURE__ */ new Map();
166
+ const read = async () => {
167
+ for (let n = queue.shift(); n !== void 0; n = queue.shift()) try {
168
+ const block = await this.publicClient.getBlock({ blockNumber: n });
169
+ times.set(n, block.timestamp);
170
+ } catch (e) {
171
+ queue.length = 0;
172
+ throw e;
173
+ }
174
+ };
175
+ await Promise.all(Array.from({ length: Math.min(TIMESTAMP_READS, queue.length) }, read));
162
176
  return logs.map((l) => toEntry(l, l.args.timestamp ?? times.get(l.blockNumber) ?? 0n));
163
177
  }
164
178
  watch(filter, onEntry, onError, pollingInterval) {
@@ -232,12 +232,22 @@ declare class FangornEngine {
232
232
  * stitch to read only the log since it, and upload only the nodes it doesn't have
233
233
  * (one CAR). Returns the stitch block's CID, its name; with nothing new, `prev`.
234
234
  * Use the same `filter` every time for one stitch. `fromBlock` is where the log
235
- * starts (the registry's deploy block).
235
+ * starts (the registry's deploy block). `upTo` stops the fold at that block (the
236
+ * head if later or unset), so a long catch-up can be taken in bounded steps: a
237
+ * step always moves the stitch to its end, even with nothing in it.
238
+ * Throws, writing nothing, if the folded log doesn't match the contract's log root
239
+ * at the fold's end: an RPC that left out or altered an entry (a lagging node
240
+ * behind a load balancer). The next restitch from `prev` folds that range again.
241
+ * That check reads the log root as of the fold's end block, so a step that ends
242
+ * before the head needs an RPC that serves historical state (an archive node; Base
243
+ * Sepolia's default, publicnode, does). Most RPCs keep only recent state, and on
244
+ * those an older step fails with the RPC's error rather than skipping the check.
236
245
  * ponytail: rehashes the whole tree (O(repos)); and readers walk back one CAR per
237
246
  * stitch to find old nodes, so checkpoint with a full CAR (`prev = null`) when the
238
247
  * chain gets long.
239
248
  */
240
- restitch(prev: CID | null, filter?: (publisher: Address, repo: RepoName) => boolean, fromBlock?: bigint): Promise<CID>;
249
+ restitch(prev: CID | null, filter?: (publisher: Address, repo: RepoName) => boolean, fromBlock?: bigint, upTo?: bigint): Promise<CID>;
250
+ private writeStitch;
241
251
  /** A stitch block: its tree root, and the log it was folded from (n entries, root `logRoot`). */
242
252
  readStitch(stitch: CID): Promise<{
243
253
  root: CID;
@@ -476,38 +476,60 @@ var FangornEngine = class {
476
476
  * stitch to read only the log since it, and upload only the nodes it doesn't have
477
477
  * (one CAR). Returns the stitch block's CID, its name; with nothing new, `prev`.
478
478
  * Use the same `filter` every time for one stitch. `fromBlock` is where the log
479
- * starts (the registry's deploy block).
479
+ * starts (the registry's deploy block). `upTo` stops the fold at that block (the
480
+ * head if later or unset), so a long catch-up can be taken in bounded steps: a
481
+ * step always moves the stitch to its end, even with nothing in it.
482
+ * Throws, writing nothing, if the folded log doesn't match the contract's log root
483
+ * at the fold's end: an RPC that left out or altered an entry (a lagging node
484
+ * behind a load balancer). The next restitch from `prev` folds that range again.
485
+ * That check reads the log root as of the fold's end block, so a step that ends
486
+ * before the head needs an RPC that serves historical state (an archive node; Base
487
+ * Sepolia's default, publicnode, does). Most RPCs keep only recent state, and on
488
+ * those an older step fails with the RPC's error rather than skipping the check.
480
489
  * ponytail: rehashes the whole tree (O(repos)); and readers walk back one CAR per
481
490
  * stitch to find old nodes, so checkpoint with a full CAR (`prev = null`) when the
482
491
  * chain gets long.
483
492
  */
484
- async restitch(prev, filter, fromBlock = 0n) {
493
+ async restitch(prev, filter, fromBlock = 0n, upTo) {
485
494
  const base = prev ? await this.readStitch(prev) : null;
486
- const to = await this.registry.clock();
495
+ const head = await this.registry.clock();
496
+ const to = upTo !== void 0 && upTo < head ? upTo : head;
487
497
  const entries = await this.registry.log({}, base ? base.t + 1n : fromBlock, to);
488
- if (prev && entries.length === 0) return prev;
498
+ if (prev && entries.length === 0 && to === head) return prev;
499
+ let mmr = base ?? EMPTY_MMR;
500
+ for (const e of entries) mmr = mmrAppend(mmr, logLeaf(e));
501
+ const onChain = await this.registry.logRoot(to);
502
+ if (mmrRoot(mmr) !== onChain) throw new Error(`the log read up to block ${String(to)} (${String(mmr.n)} entries) doesn't match the contract's log root there: an entry is missing or altered`);
503
+ if (base && prev && entries.length === 0) return this.writeStitch({
504
+ parent: prev,
505
+ root: base.root,
506
+ car: null,
507
+ n: mmr.n,
508
+ t: Number(to),
509
+ peaks: mmr.peaks
510
+ });
489
511
  const old = base && prev ? await readMst(base.root, (c) => this.getBlock(c, prev)) : {
490
512
  state: /* @__PURE__ */ new Map(),
491
513
  nodeCids: /* @__PURE__ */ new Set()
492
514
  };
493
515
  const state = new Map(old.state);
494
- let mmr = base ?? EMPTY_MMR;
495
- for (const e of entries) {
496
- mmr = mmrAppend(mmr, logLeaf(e));
497
- if (!filter || filter(e.publisher, e.repo)) state.set(stitchKey(e.publisher, e.repo), this.hexToRootCid(e.head));
498
- }
516
+ for (const e of entries) if (!filter || filter(e.publisher, e.repo)) state.set(stitchKey(e.publisher, e.repo), this.hexToRootCid(e.head));
499
517
  const { root, nodes } = await buildMst(state);
500
518
  const fresh = /* @__PURE__ */ new Map();
501
519
  for (const n of nodes) if (!old.nodeCids.has(n.cid.toString())) fresh.set(n.cid.toString(), n);
502
520
  for (const n of fresh.values()) this.putLocal(n);
503
- const block = await encodeBlock({
521
+ const car = fresh.size ? fileCid(await this.storage.putFile(await packCar(root, fresh.values()), `${root.toString()}.car`)) : null;
522
+ return this.writeStitch({
504
523
  parent: prev,
505
524
  root,
506
- car: fresh.size ? fileCid(await this.storage.putFile(await packCar(root, fresh.values()), `${root.toString()}.car`)) : null,
525
+ car,
507
526
  n: mmr.n,
508
527
  t: Number(to),
509
528
  peaks: mmr.peaks
510
529
  });
530
+ }
531
+ async writeStitch(stitch) {
532
+ const block = await encodeBlock(stitch);
511
533
  await this.storage.putBlock(block);
512
534
  this.putLocal(block);
513
535
  this.loadedCars.add(block.cid.toString());
package/lib/fangorn.d.ts CHANGED
@@ -289,12 +289,19 @@ declare class Fangorn {
289
289
  /**
290
290
  * Build or update a stitch across the repos `patterns` match (see `stitchFilter`),
291
291
  * from the update log. Pass the previous stitch to update it. Returns the stitch's CID.
292
+ * `upTo` folds only up to that block, for a catch-up in bounded steps; a step that ends
293
+ * before the head needs an RPC that serves historical state. Throws if the log read
294
+ * doesn't match the contract's log root (see `FangornEngine.restitch`).
295
+ */
296
+ restitch(patterns: string[], prev?: string, upTo?: bigint): Promise<string>;
297
+ /**
298
+ * A stitch's tree root, and the log it was folded from: n entries up to block t,
299
+ * with root `logRoot`.
292
300
  */
293
- restitch(patterns: string[], prev?: string): Promise<string>;
294
- /** A stitch's tree root, and the log it was folded from: n entries, with root `logRoot`. */
295
301
  readStitch(stitch: string): Promise<{
296
302
  root: string;
297
303
  n: number;
304
+ t: bigint;
298
305
  logRoot: `0x${string}`;
299
306
  }>;
300
307
  /** Check a stitch against the contract's log root, rebuilding it under the same patterns. */
package/lib/fangorn.js CHANGED
@@ -77,7 +77,7 @@ var Fangorn = class Fangorn {
77
77
  });
78
78
  const publicClient = createPublicClient({
79
79
  chain: config.chain,
80
- transport: http(config.rpcUrl)
80
+ transport: http(config.rpcUrl, config.rpcRetry)
81
81
  });
82
82
  const ctx = {
83
83
  config,
@@ -442,16 +442,23 @@ var Fangorn = class Fangorn {
442
442
  /**
443
443
  * Build or update a stitch across the repos `patterns` match (see `stitchFilter`),
444
444
  * from the update log. Pass the previous stitch to update it. Returns the stitch's CID.
445
+ * `upTo` folds only up to that block, for a catch-up in bounded steps; a step that ends
446
+ * before the head needs an RPC that serves historical state. Throws if the log read
447
+ * doesn't match the contract's log root (see `FangornEngine.restitch`).
445
448
  */
446
- async restitch(patterns, prev) {
447
- return (await this.engine.restitch(prev ? CID.parse(prev) : null, stitchFilter(patterns), this.ctx.config.fromBlock)).toString();
449
+ async restitch(patterns, prev, upTo) {
450
+ return (await this.engine.restitch(prev ? CID.parse(prev) : null, stitchFilter(patterns), this.ctx.config.fromBlock, upTo)).toString();
448
451
  }
449
- /** A stitch's tree root, and the log it was folded from: n entries, with root `logRoot`. */
452
+ /**
453
+ * A stitch's tree root, and the log it was folded from: n entries up to block t,
454
+ * with root `logRoot`.
455
+ */
450
456
  async readStitch(stitch) {
451
457
  const s = await this.engine.readStitch(CID.parse(stitch));
452
458
  return {
453
459
  root: s.root.toString(),
454
460
  n: s.n,
461
+ t: s.t,
455
462
  logRoot: s.logRoot
456
463
  };
457
464
  }
@@ -20,6 +20,46 @@ function assertStoredBlock(returned, block) {
20
20
  const want = CID.createV1(RAW_CODE, block.cid.multihash);
21
21
  if (!cid?.equals(want)) throw new Error(`storage stored block ${block.cid.toString()} as ${JSON.stringify(returned)}, expected ${want.toString()}: readers could not fetch it`);
22
22
  }
23
+ /**
24
+ * The root CID of `content` imported as a UnixFS file in kubo's layout (CIDv1, raw leaves of 256 KiB, balanced,
25
+ * `fanout` links a node), which is how Pinata stores an upload. Built from the bytes alone, so a match proves the
26
+ * CID commits to them without fetching anything.
27
+ */
28
+ async function kuboFileRoot(content, fanout) {
29
+ const CHUNK = 262144;
30
+ let level = [];
31
+ for (let o = 0; o < content.length; o += CHUNK) {
32
+ const leaf = content.subarray(o, o + CHUNK);
33
+ level.push({
34
+ cid: CID.createV1(RAW_CODE, await sha256.digest(leaf)),
35
+ size: leaf.length,
36
+ tsize: leaf.length
37
+ });
38
+ }
39
+ while (level.length > 1) {
40
+ const next = [];
41
+ for (let i = 0; i < level.length; i += fanout) {
42
+ const kids = level.slice(i, i + fanout);
43
+ const file = new UnixFS({ type: "file" });
44
+ for (const k of kids) file.addBlockSize(BigInt(k.size));
45
+ const node = dagPb.encode(dagPb.prepare({
46
+ Data: file.marshal(),
47
+ Links: kids.map((k) => ({
48
+ Hash: k.cid,
49
+ Name: "",
50
+ Tsize: k.tsize
51
+ }))
52
+ }));
53
+ next.push({
54
+ cid: CID.createV1(dagPb.code, await sha256.digest(node)),
55
+ size: kids.reduce((s, k) => s + k.size, 0),
56
+ tsize: node.length + kids.reduce((s, k) => s + k.tsize, 0)
57
+ });
58
+ }
59
+ level = next;
60
+ }
61
+ return level[0]?.cid;
62
+ }
23
63
  /** Verify the file reference before including it in a commit or paid handle. */
24
64
  async function assertStoredFile(returned, bytes, storage) {
25
65
  const root = CID.parse(returned.replace(/^ipfs:\/\//, ""));
@@ -47,6 +87,9 @@ async function assertStoredFile(returned, bytes, storage) {
47
87
  offset = end;
48
88
  }
49
89
  }
90
+ if (root.code === dagPb.code) {
91
+ for (const fanout of [174, 1024]) if ((await kuboFileRoot(bytes, fanout))?.equals(root)) return;
92
+ }
50
93
  await verify(root, bytes, 0);
51
94
  }
52
95
 
@@ -7307,6 +7307,7 @@ declare function chainNetwork(): Promise<{
7307
7307
  }, undefined, chainOverride, calls>) => Promise<{
7308
7308
  id: string;
7309
7309
  chainId: number;
7310
+ version: string;
7310
7311
  atomic: boolean;
7311
7312
  capabilities?: {
7312
7313
  [key: string]: any;
@@ -7314,7 +7315,6 @@ declare function chainNetwork(): Promise<{
7314
7315
  [x: string]: any;
7315
7316
  } | undefined;
7316
7317
  receipts?: viem237.WalletCallReceipt<bigint, "success" | "reverted">[] | undefined;
7317
- version: string;
7318
7318
  statusCode: number;
7319
7319
  status: "pending" | "success" | "failure" | undefined;
7320
7320
  }>;
@@ -8595,11 +8595,8 @@ declare function chainNetwork(): Promise<{
8595
8595
  [x: `address[${string}]`]: undefined;
8596
8596
  [x: `bool[${string}]`]: undefined;
8597
8597
  [x: `bytes[${string}]`]: undefined;
8598
- [x: `bytes32[${string}]`]: undefined;
8599
- [x: `bytes12[${string}]`]: undefined;
8600
- [x: `bytes16[${string}]`]: undefined;
8601
- [x: `bytes1[${string}]`]: undefined;
8602
8598
  [x: `bytes18[${string}]`]: undefined;
8599
+ [x: `bytes1[${string}]`]: undefined;
8603
8600
  [x: `bytes2[${string}]`]: undefined;
8604
8601
  [x: `bytes3[${string}]`]: undefined;
8605
8602
  [x: `bytes4[${string}]`]: undefined;
@@ -8610,9 +8607,11 @@ declare function chainNetwork(): Promise<{
8610
8607
  [x: `bytes9[${string}]`]: undefined;
8611
8608
  [x: `bytes10[${string}]`]: undefined;
8612
8609
  [x: `bytes11[${string}]`]: undefined;
8610
+ [x: `bytes12[${string}]`]: undefined;
8613
8611
  [x: `bytes13[${string}]`]: undefined;
8614
8612
  [x: `bytes14[${string}]`]: undefined;
8615
8613
  [x: `bytes15[${string}]`]: undefined;
8614
+ [x: `bytes16[${string}]`]: undefined;
8616
8615
  [x: `bytes17[${string}]`]: undefined;
8617
8616
  [x: `bytes19[${string}]`]: undefined;
8618
8617
  [x: `bytes20[${string}]`]: undefined;
@@ -8627,11 +8626,12 @@ declare function chainNetwork(): Promise<{
8627
8626
  [x: `bytes29[${string}]`]: undefined;
8628
8627
  [x: `bytes30[${string}]`]: undefined;
8629
8628
  [x: `bytes31[${string}]`]: undefined;
8629
+ [x: `bytes32[${string}]`]: undefined;
8630
8630
  [x: `int[${string}]`]: undefined;
8631
- [x: `int32[${string}]`]: undefined;
8632
- [x: `int16[${string}]`]: undefined;
8633
8631
  [x: `int8[${string}]`]: undefined;
8632
+ [x: `int16[${string}]`]: undefined;
8634
8633
  [x: `int24[${string}]`]: undefined;
8634
+ [x: `int32[${string}]`]: undefined;
8635
8635
  [x: `int40[${string}]`]: undefined;
8636
8636
  [x: `int48[${string}]`]: undefined;
8637
8637
  [x: `int56[${string}]`]: undefined;
@@ -8661,10 +8661,10 @@ declare function chainNetwork(): Promise<{
8661
8661
  [x: `int248[${string}]`]: undefined;
8662
8662
  [x: `int256[${string}]`]: undefined;
8663
8663
  [x: `uint[${string}]`]: undefined;
8664
- [x: `uint32[${string}]`]: undefined;
8665
- [x: `uint16[${string}]`]: undefined;
8666
8664
  [x: `uint8[${string}]`]: undefined;
8665
+ [x: `uint16[${string}]`]: undefined;
8667
8666
  [x: `uint24[${string}]`]: undefined;
8667
+ [x: `uint32[${string}]`]: undefined;
8668
8668
  [x: `uint40[${string}]`]: undefined;
8669
8669
  [x: `uint48[${string}]`]: undefined;
8670
8670
  [x: `uint56[${string}]`]: undefined;
@@ -8697,11 +8697,8 @@ declare function chainNetwork(): Promise<{
8697
8697
  address?: undefined;
8698
8698
  bool?: undefined;
8699
8699
  bytes?: undefined;
8700
- bytes32?: undefined;
8701
- bytes12?: undefined;
8702
- bytes16?: undefined;
8703
- bytes1?: undefined;
8704
8700
  bytes18?: undefined;
8701
+ bytes1?: undefined;
8705
8702
  bytes2?: undefined;
8706
8703
  bytes3?: undefined;
8707
8704
  bytes4?: undefined;
@@ -8712,9 +8709,11 @@ declare function chainNetwork(): Promise<{
8712
8709
  bytes9?: undefined;
8713
8710
  bytes10?: undefined;
8714
8711
  bytes11?: undefined;
8712
+ bytes12?: undefined;
8715
8713
  bytes13?: undefined;
8716
8714
  bytes14?: undefined;
8717
8715
  bytes15?: undefined;
8716
+ bytes16?: undefined;
8718
8717
  bytes17?: undefined;
8719
8718
  bytes19?: undefined;
8720
8719
  bytes20?: undefined;
@@ -8729,10 +8728,11 @@ declare function chainNetwork(): Promise<{
8729
8728
  bytes29?: undefined;
8730
8729
  bytes30?: undefined;
8731
8730
  bytes31?: undefined;
8732
- int32?: undefined;
8733
- int16?: undefined;
8731
+ bytes32?: undefined;
8734
8732
  int8?: undefined;
8733
+ int16?: undefined;
8735
8734
  int24?: undefined;
8735
+ int32?: undefined;
8736
8736
  int40?: undefined;
8737
8737
  int48?: undefined;
8738
8738
  int56?: undefined;
@@ -8761,10 +8761,10 @@ declare function chainNetwork(): Promise<{
8761
8761
  int240?: undefined;
8762
8762
  int248?: undefined;
8763
8763
  int256?: undefined;
8764
- uint32?: undefined;
8765
- uint16?: undefined;
8766
8764
  uint8?: undefined;
8765
+ uint16?: undefined;
8767
8766
  uint24?: undefined;
8767
+ uint32?: undefined;
8768
8768
  uint40?: undefined;
8769
8769
  uint48?: undefined;
8770
8770
  uint56?: undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fangorn-network/sdk",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "decentralized, verifiable and platformless version control for data",
5
5
  "repository": {
6
6
  "type": "git",