import { Logger } from 'besonders-logger' import { CID } from 'multiformats' import { 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 } 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 round 1's bloom filter with it, so the sender skips that snapshot's * whole subtree instead of re-walking the entire `prev` chain from true root on * every push. Mirrors Rust's `ReceiverState::with_have_cids` seeding. * * 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 the request bloom stays proportional to the delta. * * Self-healing if stale or wrong: if the receiver's actual DAG diverges from this * boundary, the next round reports the real gap as subgraph roots — which always * bypass the bloom (see `walkAndBuildCar`'s `rootSet` check) — so a stale boundary * costs at most one extra round-trip, never incorrect data. Omit if there is no * known prior sync. */ prevBoundary?: CID } /** * 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 } /** 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 } // --------------------------------------------------------------------------- // Bloom filter (deterministic-bloom compatible) // --------------------------------------------------------------------------- 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): Uint8Array { const wire: PullRequestWire = { rs: roots.map(c => c.toString()), bk: bloom?.hashCount ?? 0, bb: bloom?.bytes ?? new Uint8Array(0), } return dagCbor.encode(wire) } function decodePushResponse(bytes: Uint8Array): { subgraphRoots: CID[]; bloom: Promise } { const wire = dagCbor.decode(bytes) return { subgraphRoots: wire.sr.map(s => CID.parse(s)), bloom: BloomFilter.fromWire(wire.bk, wire.bb), } } // --------------------------------------------------------------------------- // 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}`) } } 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 } // --------------------------------------------------------------------------- // 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 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. */ static async init(roots: CID[], store: BlockStoreForPull, knownComplete?: CID[]): Promise { const dag = new IncrementalDagVerification() for (const boundary of knownComplete ?? []) { if (await store.has(boundary)) { dag.haveCids.add(boundary.toString()) } 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) return dag } /** * BFS from wantCids: for each CID, check store.has() → * have: move to haveCids, extract children, continue walk * not have: stays in wantCids (frontier) */ async updateHaveCids(store: BlockStoreForPull): Promise { const queue = [...this.wantCids] const visited = new Set([...this.haveCids]) while (queue.length > 0) { const cidStr = queue.shift()! if (visited.has(cidStr)) continue visited.add(cidStr) const cid = CID.parse(cidStr) const hasBlock = await store.has(cid) if (hasBlock) { this.wantCids.delete(cidStr) this.haveCids.add(cidStr) // Extract children and continue walk const bytes = await store.get(cid) const children = extractCidLinks(cid, bytes) for (const child of children) { const childStr = child.toString() if (!this.haveCids.has(childStr)) { this.wantCids.add(childStr) queue.push(childStr) } } } // else: stays in wantCids as frontier } } 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' } /** * Verify CID hash matches bytes, store the block, and incrementally update * want/have state from the block's direct links. * * 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 verifyAndStoreBlock(cid: CID, bytes: Uint8Array, store: BlockStoreForPull): Promise { const state = this.blockState(cid) if (state !== 'want') { throw new Error(`Cannot store block ${cid}: state is '${state}', expected 'want'`) } // Verify CID hash matches bytes const { code } = cid.multihash let hashBytes: Uint8Array if (code === 0x12) { // SHA-256 const { sha256 } = await import('multiformats/hashes/sha2') 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`) } // Store the block await store.put(cid, bytes) // 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) for (const child of children) { const childStr = child.toString() if (!this.haveCids.has(childStr)) { this.wantCids.add(childStr) } } } /** * 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 } } } // 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, matching the proxy's max_roots_per_round (10K, sized to // wovin's up-to-10K-CID applog chunks). With the old 1000 cap, cold pulls of large // threads needed ~1 round per 1000 tiny blocks and blew through maxRounds. const MAX_ROOTS_PER_ROUND = 10_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, ): 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) // 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 if (prevBoundary) { bloom = await BloomFilter.create(1) await bloom.insert(cidToBytes(prevBoundary)) } 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) 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, }) const response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/vnd.ipld.car', ...authHeaders, ...extraHeaders, }, body: carBlob, mode: 'cors', signal: signal ?? AbortSignal.timeout(300_000), }) 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 // 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) const { signal, delegation, maxRounds = 10, headers: extraHeaders, onProgress, prevBoundary } = 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). const dag = await IncrementalDagVerification.init([rootCid], blockStore, prevBoundary ? [prevBoundary] : undefined) 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 if (bloom) { body = new Blob([encodePullRequest(missingSubgraphRoots, bloom) 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) 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`) 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, }) const response = await fetch(endpoint, { method: 'POST', headers: reqHeaders, body, mode: 'cors', signal: signal ?? AbortSignal.timeout(300_000), }) if (!response.ok) { const errText = await response.text().catch(() => '') throw ERROR(`pull failed with status ${response.status}: ${errText}`) } // Parse CAR response const carBytes = new Uint8Array(await response.arrayBuffer()) if (carBytes.length === 0) { if (dag.wantCids.size > 0) { throw ERROR(`pull round ${round}: server returned empty response but ${dag.wantCids.size} blocks still missing`) } return } const reader = await CarReader.fromBytes(carBytes) let newBlockCount = 0 for await (const { cid, bytes } of reader.blocks()) { 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, store, update links incrementally await dag.verifyAndStoreBlock(cid, bytes, blockStore) newBlockCount++ } // 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. if (newBlockCount > 0) { await dag.updateHaveCids(blockStore) } DEBUG(`pull round ${round}: received and stored ${newBlockCount} new blocks`) cumulativeBlocks += newBlockCount cumulativeBytes += carBytes.length onProgress?.({ direction: 'pull', phase: 'round-done', round, maxRounds, blocks: cumulativeBlocks, blocksThisRound: newBlockCount, bytes: cumulativeBytes, bytesThisRound: carBytes.length, 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 } }