import { Logger } from 'besonders-logger' import { CID } from 'multiformats' import { CarBlockIterator, CarReader, CarWriter } from '@ipld/car' import * as dagCbor from '@ipld/dag-cbor' import * as dagJson from '@ipld/dag-json' import type { BlockStoreish } from '@wovin/core/ipfs' import { SignedDelegation } from './types.ts' import { delegationToBase64 } from './delegation.ts' import { stripUrlOfTrailingSlash } from './utils.ts' const { WARN, LOG, DEBUG, VERBOSE, ERROR } = Logger.setup(Logger.INFO, { prefix: '[car-mirror]' }) // eslint-disable-line no-unused-vars // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- export interface CarMirrorBlock { cid: CID bytes: Uint8Array } /** * Minimal blockstore interface for pull operations. * Compatible with IDBBlockstore and standard Blockstore interfaces. */ export interface BlockStoreForPull { has(key: CID): Promise get(key: CID): Promise put(key: CID, val: Uint8Array): Promise /** * Optional bulk write, one transaction for many blocks instead of one * transaction per `put()` call. On a cold pull of a large thread, per-block * `put()` (e.g. IDBBlockstore's default, which opens a fresh IndexedDB * transaction per call) dominates total pull time — measured at ~95% of a * ~294s round for ~94K blocks (~280s in `put()` alone vs ~9s combined for * hash verification + link extraction + network). `carMirrorPull` buffers * blocks and calls this every `PUT_BATCH_SIZE` blocks (and once more at * round end) when the caller provides it, falling back to sequential * `put()` otherwise — see note3's `putManyBlocks` for the same pattern * already used on the gateway-fetch write path. */ putMany?(pairs: { cid: CID; bytes: Uint8Array }[]): Promise } export interface CarMirrorOptions { signal?: AbortSignal delegation?: SignedDelegation maxRounds?: number headers?: Record /** * Maximum bytes per CAR round (default 30MB, just under the proxy's 32MB * receive_maximum). Push auto-falls-back to 1.9MB rounds against old servers. */ sendMaximum?: number /** Live progress callback, invoked each round and on completion. See CarMirrorProgress. */ onProgress?: (progress: CarMirrorProgress) => void /** * The root CID of the last snapshot the *receiving* side is known to already have * completely (wovin invariant: having a snapshot root implies having its whole DAG). * Typically the previous successful push's `rootCid` (push) or the subscription's * `lastCID` (pull) for this same DAG/thread — NOT the current operation's own root. * * Push: seeds the send walk's skip-root set with it, so the walk prunes at that * snapshot's subtree instead of descending the entire `prev` chain on every push. * The server's own advertised skip roots (PushResponse.ss — its pinned history) * extend the set from round 2 on. * * Pull: seeds the local have-set with it (if the block is present locally), so the * want-discovery walk stops at the boundary instead of re-walking the entire local * history — and asserts it on the wire (PullRequest.ss), so the SERVER prunes its * send walk below it too: round 1 of a new snapshot transfers only the delta * instead of the whole shared history. * * Self-healing if stale or wrong: explicitly requested subgraph roots always * bypass both the bloom and skip claims (on either side), so a stale boundary * costs extra round-trips, never incorrect data. Omit if there is no known * prior sync. */ prevBoundary?: CID /** * Pull only. Cross-call memoization for the local-store walk — see * `DagLinkCache`. Pass the SAME instance across every pull done by a given * worker/session (create one with `createDagLinkCache()` at that scope) so * re-pulling an already-partially-or-fully-synced thread (e.g. reopening a * preview) doesn't re-walk blocks already proven present. Omit for a * one-shot pull with no benefit from memoization. */ dagLinkCache?: DagLinkCache } /** * Live progress for a car-mirror pull or push, emitted each round + on completion. * * Note: car-mirror discovers the DAG as it walks, so `frontier` (the count of blocks * still wanted for a pull) is a moving frontier — NOT a known total. There is no * reliable "percent complete" until the final round; prefer showing live counts, * throughput and round number over a fake progress ratio. */ export interface CarMirrorProgress { direction: 'pull' | 'push' /** 'round-start' before a request, 'round-done' after blocks are processed, 'complete' when finished */ phase: 'round-start' | 'round-done' | 'complete' /** 1-based round number */ round: number maxRounds: number /** cumulative blocks transferred (received for pull / sent for push) */ blocks: number /** blocks transferred in the most recent round */ blocksThisRound: number /** cumulative CAR bytes transferred over the wire */ bytes: number /** CAR bytes in the most recent round */ bytesThisRound: number /** remaining frontier: wanted blocks (pull) or subgraph roots the server still needs (push) */ frontier: number /** bloom filter size in bytes for the current round (0 if none) */ bloomBytes: number /** bloom hash count k for the current round (0 if none) */ bloomK: number /** HTTP round-trips issued so far */ requests: number } /** Wire format for PushResponse (DAG-CBOR from server) */ interface PushResponseWire { /** Subgraph roots — CID strings */ sr: string[] /** Bloom hash count (k) */ bk: number /** Bloom bytes */ bb: Uint8Array /** * Skip-subgraph roots — CID strings (optional; absent on old servers). * Roots whose entire subgraphs the sender should neither walk nor send: * the receiver (server, on push) holds them completely. See PullRequestWire.ss. */ ss?: string[] } /** Wire format for PullRequest (DAG-CBOR to server) */ interface PullRequestWire { /** Roots requested — CID strings */ rs: string[] /** Bloom hash count (k) */ bk: number /** Bloom bytes */ bb: Uint8Array /** * Skip-subgraph roots — CID strings (optional; omitted when empty so the * encoding stays byte-identical to the legacy format for old servers). * * Reason-agnostic "do not send below these" instruction: the receiver has * the subgraph completely (previously fully-synced snapshot root) or * deliberately doesn't want it. Unlike a bloom hit (one flat block), the * server prunes its send walk below these — this is what makes round 1 of * a warm pull transfer only the delta. Explicitly requested roots (rs) * always take precedence over a skip claim. */ ss?: string[] } // --------------------------------------------------------------------------- // Bloom filter (deterministic-bloom compatible) // --------------------------------------------------------------------------- // Lazy singleton — avoids a repeated `await import()` (a promise + module-registry // lookup on every call, even once cached) inside the per-block hot path in // `verifyAndStoreBlock`, which runs once per block on a cold pull (tens of // thousands of times). let _sha256: typeof import('multiformats/hashes/sha2')['sha256'] | null = null async function getSha256() { if (_sha256) return _sha256 ;({ sha256: _sha256 } = await import('multiformats/hashes/sha2')) return _sha256 } type Xxh3Fn = (input: Uint8Array, seed: bigint) => Promise let _xxh3: Xxh3Fn | null = null async function getXxh3(): Promise { if (_xxh3) return _xxh3 const { xxhash3 } = await import('hash-wasm') _xxh3 = async (input: Uint8Array, seed: bigint): Promise => { // hash-wasm takes seed as two 32-bit unsigned integers (lo, hi) const seedLow = Number(seed & 0xFFFFFFFFn) const seedHigh = Number((seed >> 32n) & 0xFFFFFFFFn) const hexHash = await xxhash3(input, seedLow, seedHigh) return BigInt('0x' + hexHash) } return _xxh3 } function nextPow2(n: number): number { if (n <= 1) return 1 return 1 << (32 - Math.clz32(n - 1)) } export class BloomFilter { readonly bytes: Uint8Array readonly hashCount: number readonly bitSize: number private xxh3: Xxh3Fn private constructor(bytes: Uint8Array, hashCount: number, bitSize: number, xxh3: Xxh3Fn) { this.bytes = bytes this.hashCount = hashCount this.bitSize = bitSize this.xxh3 = xxh3 } /** * Create a bloom filter sized for `itemCount` items with the car-mirror FPR formula. */ static async create(itemCount: number): Promise { const xxh3 = await getXxh3() // car-mirror FPR: min(0.001, 0.1 / n) const fpr = Math.min(0.001, 0.1 / Math.max(1, itemCount)) // optimal bit size: -n * ln(fpr) / (ln(2)^2) const m = Math.max(8, Math.ceil(-itemCount * Math.log(fpr) / (Math.LN2 * Math.LN2))) // round to byte boundary const byteSize = Math.ceil(m / 8) const bitSize = byteSize * 8 // optimal k: max(ceil((m/n) * ln(2)), 1) const k = Math.max(Math.ceil((bitSize / Math.max(1, itemCount)) * Math.LN2), 1) return new BloomFilter(new Uint8Array(byteSize), k, bitSize, xxh3) } /** * Reconstruct a bloom filter from wire data. */ static async fromWire(hashCount: number, bytes: Uint8Array): Promise { const xxh3 = await getXxh3() const bitSize = bytes.length * 8 return new BloomFilter(bytes, hashCount, bitSize, xxh3) } /** * Insert an item (raw CID bytes). */ async insert(item: Uint8Array): Promise { for (const idx of await this.hashIndices(item)) { // LSB0 bit ordering const byteIdx = idx >>> 3 const bitIdx = idx & 7 this.bytes[byteIdx] |= 1 << bitIdx } } /** * Check if an item is (probably) in the set. */ async has(item: Uint8Array): Promise { for (const idx of await this.hashIndices(item)) { const byteIdx = idx >>> 3 const bitIdx = idx & 7 if ((this.bytes[byteIdx] & (1 << bitIdx)) === 0) return false } return true } /** * Compute hash indices using xxh3_64 with sequential seeds + rejection sampling. */ private async hashIndices(item: Uint8Array): Promise { const indices: number[] = [] const mask = nextPow2(this.bitSize) let seed = 0 let found = 0 while (found < this.hashCount) { const hash = await this.xxh3(item, BigInt(seed)) seed++ // rejection sampling: hash mod next_pow2, reject if >= bitSize const pos = Number(hash % BigInt(mask)) if (pos < this.bitSize) { indices.push(pos) found++ } } return indices } toWire(): { bk: number; bb: Uint8Array } { return { bk: this.hashCount, bb: this.bytes } } } // --------------------------------------------------------------------------- // Protocol message encoding/decoding // --------------------------------------------------------------------------- function encodePullRequest(roots: CID[], bloom?: BloomFilter, skipRoots?: CID[]): Uint8Array { const wire: PullRequestWire = { rs: roots.map(c => c.toString()), bk: bloom?.hashCount ?? 0, bb: bloom?.bytes ?? new Uint8Array(0), } // Omit when empty — keeps the bytes identical to the legacy encoding // (mirrors Rust's skip_serializing_if) so old servers see no change. if (skipRoots && skipRoots.length > 0) { wire.ss = skipRoots.map(c => c.toString()) } return dagCbor.encode(wire) } function decodePushResponse( bytes: Uint8Array, ): { subgraphRoots: CID[]; bloom: Promise; skipSubgraphRoots: CID[] } { const wire = dagCbor.decode(bytes) return { subgraphRoots: wire.sr.map(s => CID.parse(s)), bloom: BloomFilter.fromWire(wire.bk, wire.bb), skipSubgraphRoots: (wire.ss ?? []).map(s => CID.parse(s)), } } // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- function buildAuthHeaders(delegation?: SignedDelegation): Record { if (!delegation) return {} const base64Delegation = delegationToBase64(delegation) const allTokens = [base64Delegation] for (const proof of delegation.proofs) { allTokens.push(delegationToBase64(proof)) } return { 'Authorization': `Bearer ${base64Delegation}`, 'ucans': allTokens.join(', '), } } async function blocksToCarBlob(rootCid: CID, blocks: CarMirrorBlock[]): Promise { const { writer, out } = CarWriter.create([rootCid]) const chunks: Uint8Array[] = [] const drain = (async () => { for await (const chunk of out) { chunks.push(chunk) } })() for (const block of blocks) { await writer.put(block) } await writer.close() await drain return new Blob(chunks as BlobPart[], { type: 'application/vnd.ipld.car' }) } function cidToBytes(cid: CID): Uint8Array { return cid.bytes } /** * Recursively extract CID instances from a decoded IPLD value. * Works with output from dagJson.decode() and dagCbor.decode() which preserve CID instances. * * Uses CID.asCID() instead of `instanceof CID`: @ipld/dag-json and @ipld/dag-cbor can resolve * to a different copy of the `multiformats` package than the one imported here, which makes * `instanceof` fail across the two CID classes even though they represent the same CID. asCID() * is multiformats' documented cross-version-safe duck-typing check (relies on the `asCID` getter * every CID instance carries, regardless of which package copy constructed it) — see * https://github.com/multiformats/js-multiformats#dealing-with-block-instances. */ function extractCids(value: unknown): CID[] { const asCid = CID.asCID(value) if (asCid) return [asCid] if (Array.isArray(value)) return value.flatMap(extractCids) if (value && typeof value === 'object') return Object.values(value).flatMap(extractCids) return [] } /** * Codec-aware CID link extraction. Dispatches on CID codec code: * - 0x0129 (DAG-JSON): decode with @ipld/dag-json, walk for CIDs * - 0x71 (DAG-CBOR): decode with @ipld/dag-cbor, walk for CIDs * - 0x70 (DAG-PB): extract links from protobuf wire format * - 0x55 (raw): no links * - Other: no links, log warning */ /** * Extract CID links from DAG-PB (protobuf) encoded bytes. * DAG-PB wire format: repeated Link { Hash bytes = 1; ... } = 2 * We parse the protobuf minimally to extract Hash fields from Link messages. */ function extractDagPbLinks(bytes: Uint8Array): CID[] { const links: CID[] = [] let offset = 0 while (offset < bytes.length) { // Read varint field tag const [tag, tagLen] = readVarint(bytes, offset) offset += tagLen const fieldNumber = tag >> 3 const wireType = tag & 0x7 if (wireType === 2) { // Length-delimited const [len, lenLen] = readVarint(bytes, offset) offset += lenLen if (fieldNumber === 2) { // Link submessage — parse inner fields to find Hash (field 1) const end = offset + len let inner = offset while (inner < end) { const [innerTag, innerTagLen] = readVarint(bytes, inner) inner += innerTagLen const innerField = innerTag >> 3 const innerWire = innerTag & 0x7 if (innerWire === 2) { const [innerLen, innerLenLen] = readVarint(bytes, inner) inner += innerLenLen if (innerField === 1) { // Hash field — raw CID bytes links.push(CID.decode(bytes.subarray(inner, inner + innerLen))) } inner += innerLen } else if (innerWire === 0) { const [, vLen] = readVarint(bytes, inner) inner += vLen } else { throw new Error(`extractDagPbLinks: unexpected wire type ${innerWire} in Link submessage`) } } } offset += len } else if (wireType === 0) { const [, vLen] = readVarint(bytes, offset) offset += vLen } else { throw new Error(`extractDagPbLinks: unexpected wire type ${wireType} at top level`) } } return links } /** Encode an unsigned integer as a varint. */ function encodeVarint(value: number): Uint8Array { const bytes: number[] = [] while (value > 0x7f) { bytes.push((value & 0x7f) | 0x80) value >>>= 7 } bytes.push(value & 0x7f) return new Uint8Array(bytes) } /** Read an unsigned varint from bytes at offset. Returns [value, bytesRead]. */ function readVarint(bytes: Uint8Array, offset: number): [number, number] { let result = 0 let shift = 0 let pos = offset while (pos < bytes.length) { const byte = bytes[pos] result |= (byte & 0x7f) << shift pos++ if ((byte & 0x80) === 0) return [result, pos - offset] shift += 7 if (shift > 35) throw new Error('readVarint: varint too long') } throw new Error('readVarint: unexpected end of data') } function extractCidLinks(cid: CID, bytes: Uint8Array): CID[] { switch (cid.code) { case 0x0129: // dag-json return extractCids(dagJson.decode(bytes)) case 0x71: // dag-cbor return extractCids(dagCbor.decode(bytes)) case 0x70: // dag-pb return extractDagPbLinks(bytes) case 0x55: // raw return [] default: throw new Error(`extractCidLinks: unsupported codec 0x${cid.code.toString(16)} for ${cid}`) } } /** * Adapt a fetch response body (ReadableStream) into an AsyncIterable of chunks, * invoking `onChunk` every time a chunk arrives. Used to drive an idle timeout * that resets on progress instead of a fixed wall-clock deadline for the whole * round — see `carMirrorPull`'s use of this with `armIdleTimeout`. Mirrors the * Rust client's (n3-rs) idle-based `read_timeout`, which resets per chunk * instead of bounding the whole request/response. */ async function* streamBodyChunks(body: ReadableStream, onChunk: () => void): AsyncGenerator { const reader = body.getReader() try { while (true) { const { done, value } = await reader.read() if (done) return onChunk() yield value } } finally { reader.releaseLock() } } function uint8ArrayEquals(a: Uint8Array, b: Uint8Array): boolean { if (a.length !== b.length) return false for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) return false } return true } // --------------------------------------------------------------------------- // DAG link cache (cross-call memoization for the pull-side local-store walk) // --------------------------------------------------------------------------- /** * Memoizes "children of a confirmed-present block" across repeated calls to * `IncrementalDagVerification` (separate rounds, separate `carMirrorPull` * invocations, e.g. re-previewing the same thread within one tab session). * * Why this is sound as a *permanent* cache: blocks are immutable and * content-addressed, so "block X is present locally and links to * [Y, Z]" is a fact that, once true, never becomes false or needs * invalidation — the store only ever gains blocks, never mutates or (today) * garbage-collects them. Only *presence* is memoized, never *absence*: a * block that's missing now may be pulled a moment later, so cache misses * always re-check the real store rather than caching a negative result. * * Deliberately just a link-adjacency cache, not a "this whole subtree is * complete" cache: the existing BFS walk in `updateHaveCids` already dedupes * per-call via its own `visited` set, so a subtree-completeness cache would * duplicate that bookkeeping for no extra benefit while adding real * complexity (recursion/post-order marking). Caching just the links lets a * warm walk skip the IndexedDB `get()` + block-parse for every previously-seen * CID — the dominant cost — while staying a simple flat Map. * * Share one instance across every pull done by the same worker/session (see * callers) so e.g. re-opening a preview you already partially or fully synced * doesn't re-walk blocks already proven present. */ export class DagLinkCache { private links = new Map() get(cidStr: string): string[] | undefined { return this.links.get(cidStr) } set(cidStr: string, childrenCidStrs: string[]): void { this.links.set(cidStr, childrenCidStrs) } } export function createDagLinkCache(): DagLinkCache { return new DagLinkCache() } const DEFAULT_WALK_CONCURRENCY = 32 // --------------------------------------------------------------------------- // Incremental DAG verification (pull-side state machine) // --------------------------------------------------------------------------- /** * Ports the Rust `IncrementalDagVerification` logic for pull: * BFS walk from roots, tracking which CIDs we have vs want. */ class IncrementalDagVerification { wantCids: Set // CID strings we still need haveCids: Set // CID strings we already have /** * Boundaries from `knownComplete` that were accepted (block present * locally). Asserted on the wire as PullRequest.ss every round, so the * server prunes its send walk below them instead of re-sending shared * history the moment the new root links into it. */ seededBoundaries: CID[] = [] private constructor() { this.wantCids = new Set() this.haveCids = new Set() } /** * Initialize by walking from roots, populating haveCids and wantCids. * * `knownComplete` (optional): roots of subtrees we already have completely * (e.g. the previous snapshot chain — wovin invariant: having a snapshot root * implies having its whole DAG). Locally-present ones are pre-seeded into * haveCids, which stops the walk at the boundary (both here and when received * blocks link to it) instead of re-walking the entire history below it. * * `linkCache` (optional): see `DagLinkCache` — pass the same instance across * calls (same worker/session) to skip re-reading+re-parsing blocks the walk * has already proven present, on this or an earlier call. */ static async init( roots: CID[], store: BlockStoreForPull, knownComplete?: CID[], linkCache?: DagLinkCache, ): Promise { const dag = new IncrementalDagVerification() for (const boundary of knownComplete ?? []) { if (await store.has(boundary)) { dag.haveCids.add(boundary.toString()) dag.seededBoundaries.push(boundary) } else { DEBUG(`init: knownComplete boundary ${boundary} not in local store, ignoring`) } } for (const root of roots) { const rootStr = root.toString() if (!dag.haveCids.has(rootStr)) dag.wantCids.add(rootStr) } await dag.updateHaveCids(store, linkCache) return dag } /** * BFS from wantCids: for each CID, read the block (a single `store.get()` — * a miss is treated as "don't have" rather than issuing a separate `has()` * probe first, halving the common-case IndexedDB round-trips) → * present: move to haveCids, extract children (from cache if we've * already parsed this exact CID before), continue walk * missing: stays in wantCids (frontier) * * Bounded-concurrency worker pool instead of one-at-a-time `await`s in a * loop: for a large local store this walk was previously fully sequential, * which could take minutes purely on IndexedDB per-call latency before the * first network round-trip. Nodes are marked `visited` synchronously the * moment they're claimed by a worker (before any `await`), so concurrent * workers never double-process the same CID — no extra in-flight dedup * bookkeeping needed. */ async updateHaveCids(store: BlockStoreForPull, linkCache?: DagLinkCache): Promise { // One flat worker pool for the WHOLE walk (not a fresh limited batch per BFS // level — nesting limited batches inside each other compounds to // concurrency^depth, defeating the bound). All workers pull from the same // `queue` array via a shared cursor; newly-discovered children are pushed onto // that same array, which already-running workers pick up as they advance past // the current end — no recursion, so no call-stack-depth risk on a deep chain. const queue = [...this.wantCids] const visited = new Set([...this.haveCids, ...queue]) if (queue.length === 0) return let nextIndex = 0 const worker = async () => { while (nextIndex < queue.length) { const cidStr = queue[nextIndex++] const cid = CID.parse(cidStr) let children: string[] | undefined = linkCache?.get(cidStr) if (children === undefined) { let bytes: Uint8Array | undefined try { bytes = await store.get(cid) } catch { bytes = undefined // treat any read failure (incl. not-found) as "don't have" } if (!bytes) continue // stays in wantCids as frontier children = extractCidLinks(cid, bytes).map(c => c.toString()) linkCache?.set(cidStr, children) } this.wantCids.delete(cidStr) this.haveCids.add(cidStr) for (const childStr of children) { if (!this.haveCids.has(childStr) && !visited.has(childStr)) { visited.add(childStr) // claim synchronously so no other worker re-queues it this.wantCids.add(childStr) queue.push(childStr) } } } } const workerCount = Math.min(DEFAULT_WALK_CONCURRENCY, queue.length) await Promise.all(Array.from({ length: workerCount }, worker)) } blockState(cid: CID): 'have' | 'want' | 'unexpected' { const cidStr = cid.toString() if (this.haveCids.has(cidStr)) return 'have' if (this.wantCids.has(cidStr)) return 'want' return 'unexpected' } /** * Cumulative per-phase timings across every `verifyAndStoreBlock` call on this * instance (ms). Diagnostic only — see `carMirrorPull`'s perf summary log. */ perfStats = { hashMs: 0, putMs: 0, extractMs: 0, blocks: 0 } /** * Verify CID hash matches bytes and incrementally update want/have state * from the block's direct links — WITHOUT persisting to the store. Callers * that need to batch writes (see `BlockStoreForPull.putMany`) call this * directly and buffer `bytes` themselves; `verifyAndStoreBlock` below * (single-block persistence) is a thin wrapper for callers that don't. * * Note: this does NOT re-walk the local store (that would be O(DAG) per block * = O(n²) per round). Links to subtrees that are already fully local stay in * wantCids until the caller runs `updateHaveCids` once per round. */ async verifyBlock(cid: CID, bytes: Uint8Array): Promise { const state = this.blockState(cid) if (state !== 'want') { throw new Error(`Cannot store block ${cid}: state is '${state}', expected 'want'`) } this.perfStats.blocks++ // Verify CID hash matches bytes const t0 = performance.now() const { code } = cid.multihash let hashBytes: Uint8Array if (code === 0x12) { // SHA-256 const sha256 = await getSha256() const digest = await sha256.digest(bytes) hashBytes = digest.bytes } else if (code === 0x00) { // identity hash — the digest IS the data; encode as <0x00> const lenVarint = encodeVarint(bytes.length) hashBytes = new Uint8Array(1 + lenVarint.length + bytes.length) hashBytes[0] = 0x00 hashBytes.set(lenVarint, 1) hashBytes.set(bytes, 1 + lenVarint.length) } else { throw new Error(`Block ${cid}: unsupported hash function code 0x${code.toString(16)}, cannot verify`) } if (!uint8ArrayEquals(hashBytes, cid.multihash.bytes)) { throw new Error(`Block ${cid}: hash verification failed`) } const t1 = performance.now() this.perfStats.hashMs += t1 - t0 // Move from want to have this.wantCids.delete(cid.toString()) this.haveCids.add(cid.toString()) // Extract children and add to wantCids const children = extractCidLinks(cid, bytes) this.perfStats.extractMs += performance.now() - t1 for (const child of children) { const childStr = child.toString() if (!this.haveCids.has(childStr)) { this.wantCids.add(childStr) } } } /** Verify + persist a single block. See `verifyBlock` for the batched-write alternative. */ async verifyAndStoreBlock(cid: CID, bytes: Uint8Array, store: BlockStoreForPull): Promise { await this.verifyBlock(cid, bytes) const t0 = performance.now() await store.put(cid, bytes) this.perfStats.putMs += performance.now() - t0 } /** * Convert to receiver state for building next PullRequest. */ toReceiverState(): { missingSubgraphRoots: CID[]; bloomPromise: Promise | null } { const roots = [...this.wantCids].map(s => CID.parse(s)).slice(0, MAX_ROOTS_PER_ROUND) if (this.haveCids.size === 0) { return { missingSubgraphRoots: roots, bloomPromise: null } } const haveCidsCopy = [...this.haveCids] const bloomPromise = (async () => { const bloom = await BloomFilter.create(haveCidsCopy.length) for (const cidStr of haveCidsCopy) { await bloom.insert(CID.parse(cidStr).bytes) } return bloom })() return { missingSubgraphRoots: roots, bloomPromise } } } // Pull round idle timeouts (see carMirrorPull's use of armIdleTimer). Unlike a flat // AbortSignal.timeout() for the whole round, these reset on every byte received, so // a round streaming a large cold-pull DAG never times out just for being big/slow — // only a genuine stall (no bytes at all for this long) aborts it. CONNECT_TIMEOUT_MS // bounds the wait for response headers; PULL_IDLE_TIMEOUT_MS bounds the gap between // body chunks once streaming starts. const CONNECT_TIMEOUT_MS = 30_000 const PULL_IDLE_TIMEOUT_MS = 60_000 // Push round timeout: work-proportional, NOT idle-based. Unlike pull, a push round // uploads its whole CAR up front and then waits for the server to write thousands of // blocks into a (possibly loaded) IPFS node before it sends response headers back — // there is legitimately no data flowing during that wait, so an idle timer would abort // a perfectly healthy push. Instead we budget wall-clock time proportional to the // number of blocks sent in the round. Observed in production: a 7,054-block/1.77MB // push was still writing at ~300s (killed by the old flat AbortSignal.timeout(300_000) // with an undiagnosable bare "Signal timed out"), i.e. server write throughput is on // the order of 100ms/block under load — PUSH_PER_BLOCK_TIMEOUT_MS below. The floor // keeps small pushes behaved exactly as before (they never approach 300s anyway); the // ceiling still aborts a genuinely wedged server instead of waiting forever. const PUSH_MIN_TIMEOUT_MS = 300_000 const PUSH_PER_BLOCK_TIMEOUT_MS = 100 const PUSH_MAX_TIMEOUT_MS = 30 * 60_000 // How many verified-but-unpersisted blocks to buffer before flushing via // `blockStore.putMany` (one IndexedDB transaction per batch). Sized so a single // batch stays a reasonable size in memory (a few MB even for large blocks) while // keeping the number of transactions for a ~94K-block cold pull down to ~50 // instead of ~94K — see BlockStoreForPull.putMany's doc comment for the measured // impact. const PUT_BATCH_SIZE = 2000 // Round budget for push CARs — must stay under the server's receive_maximum (32MB on // current ucan-store-proxy) with margin for CAR overhead. Sized so a whole wovin // thread of tiny applog blocks pushes in one round instead of many 2MB rounds, each // of which forced want-CID enumeration + bloom rebuilds. carMirrorPush falls back to // LEGACY_SEND_MAXIMUM automatically when the server still enforces the old 2MB limit. const DEFAULT_SEND_MAXIMUM = 30_000_000 const LEGACY_SEND_MAXIMUM = 1_900_000 // pre-32MB servers (receive_maximum = 2MB) // Cap frontier size per round. The proxy's own max_roots_per_round is 10K, but the // client can request a wider frontier than the server reports back in one go — the // Rust client (n3-rs) requests up to 100K roots per round for the same reason. With // the old 1000 cap, cold pulls of large threads needed ~1 round per 1000 tiny blocks // and blew through maxRounds; keeping this well above the server's per-round ceiling // avoids the client itself becoming the bottleneck on wide frontiers. const MAX_ROOTS_PER_ROUND = 100_000 /** * Validate server-supplied subgraph roots by BFS from originalRoot. * Matches Rust's verify_missing_subgraph_roots: walks local store, * errors on missing blocks, returns only reachable requested roots. */ async function validateSubgraphRoots( originalRoot: CID, requestedRoots: CID[], blockStore: BlockStoreish, ): Promise { const requested = new Set(requestedRoots.map(c => c.toString())) const found: CID[] = [] const visited = new Set() const queue: CID[] = [originalRoot] while (queue.length > 0) { const cid = queue.shift()! const cidStr = cid.toString() if (visited.has(cidStr)) continue visited.add(cidStr) if (requested.has(cidStr)) found.push(cid) // Get block from local store — error if missing (sender must have complete DAG) let bytes: Uint8Array try { bytes = await blockStore.get(cid) } catch { throw new Error(`validateSubgraphRoots: block ${cidStr} missing from local store`) } if (!bytes) { throw new Error(`validateSubgraphRoots: block ${cidStr} missing from local store`) } for (const child of extractCidLinks(cid, bytes)) { if (!visited.has(child.toString())) queue.push(child) } } if (found.length < requestedRoots.length) { const missing = requestedRoots.filter(r => !found.some(f => f.toString() === r.toString())) WARN(`push: server requested ${missing.length} DAG-unrelated blocks, ignoring`) } return found } /** * BFS walk from roots, fetching blocks from blockStore and building a CAR. * Skips blocks the server already has (via bloom filter). */ async function walkAndBuildCar( roots: CID[], blockStore: BlockStoreish, bloom: BloomFilter | null, maxBytes: number, skipRoots?: Set, ): Promise<{ car: Blob; blocksSent: number }> { const visited = new Set() const rootSet = new Set(roots.map(c => c.toString())) const queue: CID[] = [...roots] const collectedBlocks: CarMirrorBlock[] = [] let estimatedSize = 0 while (queue.length > 0) { const cid = queue.shift()! const cidStr = cid.toString() if (visited.has(cidStr)) continue visited.add(cidStr) // Skip root: the receiver holds this entire subgraph (its own pinned // snapshot history, advertised via PushResponse.ss, or our prevBoundary // seed) — prune: don't send, don't descend. Unlike a bloom hit (one // flat block, walk continues through it) this cuts the whole subtree, // so pushing a new snapshot never walks the historic chain at all. // Explicitly requested roots always win over a skip claim. if (skipRoots?.has(cidStr) && !rootSet.has(cidStr)) { continue } // Check bloom: skip if server has it AND it's not a subgraph root if (bloom && !rootSet.has(cidStr) && await bloom.has(cidToBytes(cid))) { continue } let bytes: Uint8Array try { bytes = await blockStore.get(cid) } catch (err) { throw new Error(`[walkAndBuildCar] block not found in local store: ${cidStr}`) } if (!bytes) { throw new Error(`[walkAndBuildCar] block not found in local store: ${cidStr}`) } // Check size limit (rough estimate: CID bytes + block bytes + framing overhead) const blockSize = cid.bytes.length + bytes.length + 16 if (estimatedSize > 0 && estimatedSize + blockSize > maxBytes) { // Put it back — will be picked up in next round break } collectedBlocks.push({ cid, bytes }) estimatedSize += blockSize // Walk children (extract CID links from dag-json encoded bytes) const childCids = extractCidLinks(cid, bytes) for (const child of childCids) { if (!visited.has(child.toString())) { queue.push(child) } } } // Build CAR with the root CID in header (always the original root) const car = await blocksToCarBlob(roots[0], collectedBlocks) return { car, blocksSent: collectedBlocks.length } } // --------------------------------------------------------------------------- // Push // --------------------------------------------------------------------------- /** * Push a DAG to a car-mirror server using multi-round bloom-filtered sync. * * Lazily walks the DAG from the blockStore each round, skipping blocks * the server already has (via bloom filter from previous round's response). * * @param baseUrl - Base URL of the car-mirror endpoint (e.g. "https://store.example.com") * @param rootCid - Root CID of the DAG to push * @param blockStore - Block store to lazily fetch blocks from * @param opts - Options (signal, delegation, maxRounds, headers, sendMaximum) */ export async function carMirrorPush( baseUrl: string, rootCid: CID, blockStore: BlockStoreish, opts: CarMirrorOptions = {}, ): Promise { baseUrl = stripUrlOfTrailingSlash(baseUrl) const { signal, delegation, maxRounds = 50, headers: extraHeaders, sendMaximum = DEFAULT_SEND_MAXIMUM, onProgress, prevBoundary } = opts const authHeaders = buildAuthHeaders(delegation) const endpoint = `${baseUrl}/dag/push/${rootCid}` let bloom: BloomFilter | null = null // Skip roots prune the send walk's descent entirely (see walkAndBuildCar). // Seeded with prevBoundary (the previous snapshot root the server is known // to have completely) — replacing the old single-CID have-bloom seed, which // only skipped that one block while the walk still descended the whole // chain — and extended each round with the server's own advertised // skip roots from PushResponse.ss (its pinned snapshot history). const skipRoots = new Set() if (prevBoundary) { skipRoots.add(prevBoundary.toString()) } let subgraphRoots: CID[] = [rootCid] let round = 0 let cumulativeBlocks = 0 let cumulativeBytes = 0 let effectiveSendMaximum = sendMaximum while (round < maxRounds) { round++ const { car: carBlob, blocksSent } = await walkAndBuildCar(subgraphRoots, blockStore, bloom, effectiveSendMaximum, skipRoots) DEBUG(`push round ${round}: sending ${blocksSent} blocks`) if (blocksSent === 0) { DEBUG(`push: no blocks to send, done`) onProgress?.({ direction: 'push', phase: 'complete', round, maxRounds, blocks: cumulativeBlocks, blocksThisRound: 0, bytes: cumulativeBytes, bytesThisRound: 0, frontier: 0, bloomBytes: bloom?.bytes.length ?? 0, bloomK: bloom?.hashCount ?? 0, requests: round - 1, }) return } onProgress?.({ direction: 'push', phase: 'round-start', round, maxRounds, blocks: cumulativeBlocks, blocksThisRound: 0, bytes: cumulativeBytes, bytesThisRound: carBlob.size, frontier: subgraphRoots.length, bloomBytes: bloom?.bytes.length ?? 0, bloomK: bloom?.hashCount ?? 0, requests: round, }) // Budget this round's timeout on blocksSent, not carBlob size — server write // cost is per-block, not per-byte (see PUSH_PER_BLOCK_TIMEOUT_MS comment above). const roundTimeoutMs = Math.min( Math.max(blocksSent * PUSH_PER_BLOCK_TIMEOUT_MS, PUSH_MIN_TIMEOUT_MS), PUSH_MAX_TIMEOUT_MS, ) DEBUG(`push round ${round}: timeout budget ${roundTimeoutMs}ms for ${blocksSent} blocks`) // An explicit external signal always wins and fully replaces the internal // timeout (matches the previous `signal ?? AbortSignal.timeout(...)` contract). // Otherwise build our own controller so the abort reason is descriptive // (AbortSignal.timeout() only ever throws a bare TimeoutError). let roundTimer: ReturnType | undefined let fetchSignal = signal if (!fetchSignal) { const controller = new AbortController() roundTimer = setTimeout( () => controller.abort( new Error(`car-mirror push round ${round}: no response after ${roundTimeoutMs}ms for ${blocksSent} blocks`), ), roundTimeoutMs, ) fetchSignal = controller.signal } let response: Response try { response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/vnd.ipld.car', ...authHeaders, ...extraHeaders, }, body: carBlob, mode: 'cors', signal: fetchSignal, }) } finally { if (roundTimer !== undefined) clearTimeout(roundTimer) } cumulativeBlocks += blocksSent cumulativeBytes += carBlob.size if (response.status === 200) { DEBUG(`push complete after ${round} round(s)`) onProgress?.({ direction: 'push', phase: 'round-done', round, maxRounds, blocks: cumulativeBlocks, blocksThisRound: blocksSent, bytes: cumulativeBytes, bytesThisRound: carBlob.size, frontier: 0, bloomBytes: bloom?.bytes.length ?? 0, bloomK: bloom?.hashCount ?? 0, requests: round, }) onProgress?.({ direction: 'push', phase: 'complete', round, maxRounds, blocks: cumulativeBlocks, blocksThisRound: 0, bytes: cumulativeBytes, bytesThisRound: 0, frontier: 0, bloomBytes: 0, bloomK: 0, requests: round, }) return } if (response.status === 202) { // Server needs more rounds — decode bloom + subgraph roots from response const respBytes = new Uint8Array(await response.arrayBuffer()) const parsed = decodePushResponse(respBytes) bloom = await parsed.bloom // Server-advertised skip roots (its pinned, complete snapshot // history) — prune our send walk below them from now on. for (const skip of parsed.skipSubgraphRoots) { skipRoots.add(skip.toString()) } // Validate server-supplied roots by BFS from original root through local store const validRoots = await validateSubgraphRoots(rootCid, parsed.subgraphRoots, blockStore) if (validRoots.length === 0 && parsed.subgraphRoots.length > 0) { throw ERROR(`push: server requested only DAG-unrelated blocks`) } subgraphRoots = validRoots.length > 0 ? validRoots : [rootCid] DEBUG(`push round ${round}: server wants more, ${subgraphRoots.length} subgraph roots`) onProgress?.({ direction: 'push', phase: 'round-done', round, maxRounds, blocks: cumulativeBlocks, blocksThisRound: blocksSent, bytes: cumulativeBytes, bytesThisRound: carBlob.size, frontier: subgraphRoots.length, bloomBytes: bloom?.bytes.length ?? 0, bloomK: bloom?.hashCount ?? 0, requests: round, }) continue } // Unexpected status const errText = await response.text().catch(() => '') // Old servers enforce receive_maximum = 2MB per round — detect the rejection // (nothing was stored server-side; the size check happens before processing) // and retry the same round with the legacy budget. if (response.status === 500 && errText.includes('Expected to receive no more than') && effectiveSendMaximum > LEGACY_SEND_MAXIMUM) { WARN( `push round ${round}: server rejected ${effectiveSendMaximum} byte round, falling back to legacy ${LEGACY_SEND_MAXIMUM} byte rounds`, ) cumulativeBlocks -= blocksSent cumulativeBytes -= carBlob.size effectiveSendMaximum = LEGACY_SEND_MAXIMUM continue } throw ERROR(`push failed with status ${response.status}: ${errText}`) } throw ERROR(`push did not complete within ${maxRounds} rounds`) } // --------------------------------------------------------------------------- // Pull // --------------------------------------------------------------------------- /** * Pull a DAG from a car-mirror server using multi-round bloom-filtered sync. * * Incrementally verifies and stores blocks into the provided blockStore. * Uses IncrementalDagVerification to track which blocks we have/want, * sending bloom-filtered PullRequests with frontier CIDs each round. * * @param baseUrl - Base URL of the car-mirror endpoint * @param rootCid - Root CID of the DAG to pull * @param blockStore - Block store to verify against and store received blocks into * @param opts - Options (signal, delegation, maxRounds, headers) */ export async function carMirrorPull( baseUrl: string, rootCid: CID, blockStore: BlockStoreForPull, opts: CarMirrorOptions = {}, ): Promise { baseUrl = stripUrlOfTrailingSlash(baseUrl) // 50 matches carMirrorPush's default and the Rust client (n3-rs) — the previous // default of 10 caused cold pulls of large threads (tens of thousands of blocks, // wide frontiers) to blow the round budget and throw, forcing a fallback to the // much slower gateway CAR-fetch path instead of completing via car-mirror. const { signal, delegation, maxRounds = 50, headers: extraHeaders, onProgress, prevBoundary, dagLinkCache } = opts const authHeaders = buildAuthHeaders(delegation) const endpoint = `${baseUrl}/dag/pull/${rootCid}` // Initialize DAG verification — walks from root, finds what we have/want. // prevBoundary (e.g. the last successfully pulled snapshot root) stops the walk // at the already-complete history instead of re-walking it (see init docs). // dagLinkCache (if the caller shares one across calls) skips re-walking blocks // already proven present on an earlier pull in this session. const initT0 = performance.now() const dag = await IncrementalDagVerification.init([rootCid], blockStore, prevBoundary ? [prevBoundary] : undefined, dagLinkCache) LOG( `pull init perf: local-store walk took ${ (performance.now() - initT0).toFixed(0) }ms, ${dag.haveCids.size} have / ${dag.wantCids.size} want`, ) let round = 0 let cumulativeBlocks = 0 let cumulativeBytes = 0 while (round < maxRounds) { // Check if we're done (no more wanted CIDs) if (dag.wantCids.size === 0) { DEBUG(`pull complete after ${round} round(s) — all blocks present`) onProgress?.({ direction: 'pull', phase: 'complete', round, maxRounds, blocks: cumulativeBlocks, blocksThisRound: 0, bytes: cumulativeBytes, bytesThisRound: 0, frontier: 0, bloomBytes: 0, bloomK: 0, requests: round, }) return } round++ // Build PullRequest from receiver state const { missingSubgraphRoots, bloomPromise } = dag.toReceiverState() const bloom = bloomPromise ? await bloomPromise : undefined let body: BodyInit | undefined let contentType: string | undefined // Asserted skip roots ride every round's request (the server is // stateless): it prunes its send walk below them, so shared history // below the boundary is neither walked nor re-sent — round 1 included. if (bloom) { body = new Blob([encodePullRequest(missingSubgraphRoots, bloom, dag.seededBoundaries) as BlobPart], { type: 'application/vnd.ipld.dag-cbor', }) contentType = 'application/vnd.ipld.dag-cbor' } else { // No local blocks — send frontier roots without bloom body = new Blob([encodePullRequest(missingSubgraphRoots, undefined, dag.seededBoundaries) as BlobPart], { type: 'application/vnd.ipld.dag-cbor', }) contentType = 'application/vnd.ipld.dag-cbor' } const reqHeaders: Record = { 'Content-Type': contentType, 'Accept': 'application/vnd.ipld.car', ...authHeaders, ...extraHeaders, } DEBUG(`pull round ${round}: requesting ${missingSubgraphRoots.length} roots, ${dag.haveCids.size} known CIDs`) const roundT0 = performance.now() onProgress?.({ direction: 'pull', phase: 'round-start', round, maxRounds, blocks: cumulativeBlocks, blocksThisRound: 0, bytes: cumulativeBytes, bytesThisRound: 0, frontier: dag.wantCids.size, bloomBytes: bloom?.bytes.length ?? 0, bloomK: bloom?.hashCount ?? 0, requests: round, }) // Idle-timeout (not a fixed wall-clock deadline) covering both "waiting for // headers" and "waiting for the next body chunk": armed at CONNECT_TIMEOUT_MS // before the request is sent, then re-armed at PULL_IDLE_TIMEOUT_MS on every // chunk received. A round that keeps streaming — however large or slow the // underlying DAG walk — never times out; only a genuine stall does. This // replaces a flat `AbortSignal.timeout(300_000)`, which aborted (or, worse, // silently hung past its own deadline while still "connected") regardless of // whether the server was actively streaming a large cold pull. const controller = new AbortController() if (signal) { if (signal.aborted) controller.abort() else signal.addEventListener('abort', () => controller.abort(), { once: true }) } let idleTimer: ReturnType const armIdleTimer = (ms: number) => { clearTimeout(idleTimer) idleTimer = setTimeout(() => controller.abort(new Error(`car-mirror pull round ${round}: no data received for ${ms}ms`)), ms) } armIdleTimer(CONNECT_TIMEOUT_MS) let response: Response try { response = await fetch(endpoint, { method: 'POST', headers: reqHeaders, body, mode: 'cors', signal: controller.signal, }) } catch (err) { clearTimeout(idleTimer) throw err } const headersMs = performance.now() - roundT0 if (!response.ok) { clearTimeout(idleTimer) const errText = await response.text().catch(() => '') throw ERROR(`pull failed with status ${response.status}: ${errText}`) } if (!response.body) { clearTimeout(idleTimer) if (dag.wantCids.size > 0) { throw ERROR(`pull round ${round}: server returned empty response but ${dag.wantCids.size} blocks still missing`) } return } armIdleTimer(PULL_IDLE_TIMEOUT_MS) // Stream + parse the CAR incrementally (CarBlockIterator, not CarReader — // verifies/stores each block as it arrives instead of buffering the whole // round's response before any processing can start). Matches the Rust // client's (n3-rs) chunked read + incremental parse. // // Writes are buffered and flushed via `blockStore.putMany` (one IndexedDB // transaction per batch) instead of one `put()` per block — measured as // ~95% of total pull time on a cold ~94K-block pull (put() alone: ~280s of // a ~294s round) before this batching existed. Falls back to sequential // `put()` when the store doesn't implement `putMany`. let newBlockCount = 0 let blocksSeen = 0 let roundBytes = 0 const perfBefore = { ...dag.perfStats } const pendingWrites: { cid: CID; bytes: Uint8Array }[] = [] const flushWrites = async () => { if (pendingWrites.length === 0) return const t0 = performance.now() if (blockStore.putMany) { await blockStore.putMany(pendingWrites) } else { for (const { cid, bytes } of pendingWrites) await blockStore.put(cid, bytes) } dag.perfStats.putMs += performance.now() - t0 pendingWrites.length = 0 } try { const carIterator = await CarBlockIterator.fromIterable( streamBodyChunks(response.body, () => armIdleTimer(PULL_IDLE_TIMEOUT_MS)), ) for await (const { cid, bytes } of carIterator) { blocksSeen++ roundBytes += bytes.length const state = dag.blockState(cid) if (state === 'have') { DEBUG(`pull round ${round}: already have ${cid}, skipping`) continue } if (state === 'unexpected') { DEBUG(`pull round ${round}: unexpected block ${cid}, skipping`) continue } // state === 'want' — verify hash + update links incrementally now; // persistence is buffered and flushed in batches (see above). await dag.verifyBlock(cid, bytes) pendingWrites.push({ cid, bytes }) if (pendingWrites.length >= PUT_BATCH_SIZE) await flushWrites() newBlockCount++ } } finally { // Best-effort flush even on early exit (idle timeout, thrown error): blocks // already verified above have their bookkeeping (wantCids/haveCids) updated // in memory regardless, so an unflushed buffer would otherwise make the dag // believe blocks are stored when they aren't. Not persisting a duplicate // concern here — clearTimeout must still run even if this throws. try { await flushWrites() } finally { clearTimeout(idleTimer) } } const streamDoneMs = performance.now() - roundT0 if (blocksSeen === 0 && dag.wantCids.size > 0) { throw ERROR(`pull round ${round}: server returned empty response but ${dag.wantCids.size} blocks still missing`) } // Once per round (NOT per block): walk the local store from the remaining // wants to discover subtrees that are already fully local, so we don't // request blocks we already have. const updateHaveT0 = performance.now() if (newBlockCount > 0) { await dag.updateHaveCids(blockStore, dagLinkCache) } const updateHaveMs = performance.now() - updateHaveT0 // Perf summary (LOG, not DEBUG, so it's visible without FORCE_DISABLE_LOGLEVEL): // headersMs = time-to-first-byte (server round-trip before any body arrives); // streamMs - headersMs = time spent receiving + processing the body, of which // hashMs/putMs/extractMs (this round's share) are the client-side per-block // costs — the remainder is network transfer + iterator/parsing overhead. const hashMs = dag.perfStats.hashMs - perfBefore.hashMs const putMs = dag.perfStats.putMs - perfBefore.putMs const extractMs = dag.perfStats.extractMs - perfBefore.extractMs LOG( `pull round ${round} perf: ${newBlockCount} new / ${blocksSeen} seen blocks, ${(roundBytes / 1e6).toFixed(1)}MB — ` + `headers=${headersMs.toFixed(0)}ms stream-total=${(streamDoneMs - headersMs).toFixed(0)}ms ` + `(hash=${hashMs.toFixed(0)}ms put=${putMs.toFixed(0)}ms extract=${extractMs.toFixed(0)}ms ` + `other/network=${(streamDoneMs - headersMs - hashMs - putMs - extractMs).toFixed(0)}ms) ` + `updateHaveCids=${updateHaveMs.toFixed(0)}ms`, ) DEBUG(`pull round ${round}: received and stored ${newBlockCount} new blocks`) cumulativeBlocks += newBlockCount cumulativeBytes += roundBytes onProgress?.({ direction: 'pull', phase: 'round-done', round, maxRounds, blocks: cumulativeBlocks, blocksThisRound: newBlockCount, bytes: cumulativeBytes, bytesThisRound: roundBytes, frontier: dag.wantCids.size, bloomBytes: bloom?.bytes.length ?? 0, bloomK: bloom?.hashCount ?? 0, requests: round, }) if (newBlockCount === 0) { DEBUG(`pull round ${round}: no new blocks (bloom false positives?), continuing`) // Don't return — continue to next round, maxRounds will terminate if stuck } } if (dag.wantCids.size > 0) { throw ERROR(`pull did not complete within ${maxRounds} rounds, still want ${dag.wantCids.size} blocks`) } } // --------------------------------------------------------------------------- // Has CID (quick existence check) // --------------------------------------------------------------------------- /** * Quick check whether the server has the DAG for a given root CID. * * Sends a single pull round to check if the server can serve blocks for this root. * Relies on the application invariant that if the server has a root CID, * it has the complete DAG. This is NOT a general car-mirror protocol guarantee. */ export async function carMirrorHasCid( baseUrl: string, rootCid: CID, opts: CarMirrorOptions = {}, ): Promise { baseUrl = stripUrlOfTrailingSlash(baseUrl) const { signal, delegation, headers: extraHeaders } = opts const authHeaders = buildAuthHeaders(delegation) const endpoint = `${baseUrl}/dag/pull/${rootCid}` // Build bloom with just the root CID const bloom = await BloomFilter.create(1) await bloom.insert(cidToBytes(rootCid)) const body = new Blob([encodePullRequest([rootCid], bloom) as BlobPart], { type: 'application/vnd.ipld.dag-cbor' }) try { const response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/vnd.ipld.dag-cbor', 'Accept': 'application/vnd.ipld.car', ...authHeaders, ...extraHeaders, }, body, mode: 'cors', signal: signal ?? AbortSignal.timeout(30_000), }) if (!response.ok) return false const carBytes = new Uint8Array(await response.arrayBuffer()) if (carBytes.length === 0) return false // If server sends blocks, it means the DAG is not complete on our side // but the server has it — the question is whether the server has the root const reader = await CarReader.fromBytes(carBytes) let blockCount = 0 for await (const _ of reader.blocks()) { blockCount++ } // Server responded with blocks → it has the DAG (it's sending us what we're "missing") return true } catch (err) { DEBUG('hasCid check failed:', err) return false } }