@ocap/resolver 1.32.2 → 1.32.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.
@@ -84,6 +84,10 @@ interface ILedgerHealthSummary {
84
84
  witnessQuorum: number;
85
85
  witnessCircuitBroken: boolean;
86
86
  witnessFraudAlertCount: number;
87
+ /** Present only when the segment publisher runs in DA mode (#2016); never part of `healthy` */
88
+ daPublisher?: Record<string, unknown>;
89
+ /** Present only on a follower that reads the DA archive (#2017): `{ state: 'ok' }` or `{ state: 'stalled', code: 'DA_GAP', ... }`; never part of `healthy` */
90
+ daArchive?: Record<string, unknown>;
87
91
  entryHashV2From: string | null;
88
92
  latestSequence: number;
89
93
  latestCheckpoint: (Record<string, unknown> & {
package/esm/dashboard.mjs CHANGED
@@ -79,6 +79,8 @@ async function collectLedgerHealthSummary(options) {
79
79
  const proposerPublicKey = options.ledger.getProposerPublicKey?.() || null;
80
80
  const checkpointSigningEnabled = typeof options.ledger.isCheckpointSigningEnabled === "function" ? options.ledger.isCheckpointSigningEnabled() : Boolean(proposerPublicKey);
81
81
  const witnessRegistry = extLedger.getWitnessRegistry?.();
82
+ const daPublisher = extLedger.getDaPublisherStatus?.() ?? null;
83
+ const daArchive = options.runtime?.getDaArchiveStatus?.() ?? null;
82
84
  return {
83
85
  healthy,
84
86
  ...halted ? {
@@ -100,6 +102,8 @@ async function collectLedgerHealthSummary(options) {
100
102
  witnessQuorum: witnessRegistry?.getQuorum() ?? 0,
101
103
  witnessCircuitBroken: witnessRegistry?.isCircuitBroken() ?? false,
102
104
  witnessFraudAlertCount: witnessRegistry?.getFraudAlerts().length ?? 0,
105
+ ...daPublisher ? { daPublisher } : {},
106
+ ...daArchive ? { daArchive } : {},
103
107
  entryHashV2From,
104
108
  latestSequence: health.latestSequence,
105
109
  latestCheckpoint: health.latestCheckpoint ? {
@@ -654,6 +658,7 @@ function createNodeDashboardRouter(options) {
654
658
  witnessQuorum: ledgerHealth.witnessQuorum,
655
659
  witnessCircuitBroken: ledgerHealth.witnessCircuitBroken,
656
660
  witnessFraudAlertCount: ledgerHealth.witnessFraudAlertCount,
661
+ ...ledgerHealth.daPublisher ? { publisher: ledgerHealth.daPublisher } : {},
657
662
  latestAnchorReceipt
658
663
  },
659
664
  pipeline,
@@ -101,6 +101,24 @@ interface FollowerSyncServiceOptions {
101
101
  };
102
102
  }
103
103
  declare function isTransientSqliteLockError(err: unknown): boolean;
104
+ /** The cold catch-up after a `410`: see `FollowerSyncService.coldCatchUpAfterPrune` (a pure function so it can be tested). */
105
+ declare function catchUpAfterPrune(options: {
106
+ isDaReader: boolean;
107
+ run: () => Promise<number>;
108
+ onSwallowed: (err: unknown, imported: number) => void;
109
+ }): Promise<number>;
110
+ /**
111
+ * A cold catch-up that fails after it already imported segments (a DA stall or a transient error at segment N+k) has
112
+ * changed the local database: the error carries how many it imported, so the callers do not treat the cycle as untouched.
113
+ */
114
+ declare function noteColdImports(err: unknown, imported: number): void;
115
+ /** How many segments a failed cold catch-up had imported before it failed (0 when it imported none or is not annotated). */
116
+ declare function coldImportsBefore(err: unknown): number;
117
+ /**
118
+ * `.catch()` handler for a best-effort cold segment lookup (to find a checkpoint, not to import): a miss or a transient
119
+ * error is "not found here", but a fatal DA reader error (`daFatal`, #2017) is never swallowed: it halts the follower.
120
+ */
121
+ declare function coldLookupMiss(err: unknown): null;
104
122
  declare class FollowerSyncService implements INodeRuntimeAdapter {
105
123
  readonly role: TNodeRole;
106
124
  writePolicy: TNodeWritePolicy;
@@ -170,6 +188,10 @@ declare class FollowerSyncService implements INodeRuntimeAdapter {
170
188
  getRuntimeDiagnostics(options?: {
171
189
  includePrivateTopology?: boolean;
172
190
  }): Record<string, unknown>;
191
+ /** The DA reader's status for `/api/health/ledger` (`daArchive`), or null for any other cold reader (#2017). */
192
+ getDaArchiveStatus(): Record<string, unknown> | null;
193
+ /** DA follower only (#2017): `daArchive: { state: 'ok' | 'stalled', ... }`; nothing is added for any other cold reader. */
194
+ private daArchiveDiagnostics;
173
195
  triggerSyncOrProbe(): Promise<Record<string, unknown>>;
174
196
  private haltFailClosed;
175
197
  private resolveActiveUpstreamUrl;
@@ -242,6 +264,12 @@ declare class FollowerSyncService implements INodeRuntimeAdapter {
242
264
  * Stage 1B: Catch up sealed `.zst` checkpoint segments from `coldArchiveStore` when available.
243
265
  */
244
266
  private catchUpFromColdSegments;
267
+ /**
268
+ * The cold catch-up of a `410` (the leader pruned what the follower needs). Only a DA reader's non-fatal failure (a stall)
269
+ * is treated as "no cold source this cycle"; any other cold reader keeps the base behaviour exactly: its error propagates.
270
+ */
271
+ private coldCatchUpAfterPrune;
272
+ private catchUpFromColdSegmentsInner;
245
273
  private sealCaughtUpCheckpoints;
246
274
  private tryEmitHotTailReplayFraudAlert;
247
275
  private parseStrictEntryHashV2From;
@@ -291,4 +319,4 @@ declare class FollowerSyncService implements INodeRuntimeAdapter {
291
319
  close(): Promise<void>;
292
320
  }
293
321
  //#endregion
294
- export { DEFAULT_FOLLOWER_HTTP_TIMEOUT_MS, DEFAULT_FOLLOWER_MAX_SYNC_LAG, DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS, DEFAULT_FOLLOWER_POLL_INTERVAL_MS, FollowerSyncService, FollowerSyncServiceOptions, IColdSegmentReader, ILeaderRouterLike, TFollowerUpstreamFetchInterceptor, TFollowerUpstreamFetchKind, isTransientSqliteLockError };
322
+ export { DEFAULT_FOLLOWER_HTTP_TIMEOUT_MS, DEFAULT_FOLLOWER_MAX_SYNC_LAG, DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS, DEFAULT_FOLLOWER_POLL_INTERVAL_MS, FollowerSyncService, FollowerSyncServiceOptions, IColdSegmentReader, ILeaderRouterLike, TFollowerUpstreamFetchInterceptor, TFollowerUpstreamFetchKind, catchUpAfterPrune, coldImportsBefore, coldLookupMiss, isTransientSqliteLockError, noteColdImports };
package/esm/follower.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createFollowerPeerFetchGuard } from "./node-preferences.mjs";
2
- import { FUTURE_LEDGER_ENTRY_TIMESTAMP, LedgerEntryReplayer } from "./replayer.mjs";
2
+ import { FUTURE_LEDGER_ENTRY_TIMESTAMP, LedgerEntryReplayer, assertReplayEntryChainIdAcceptable, isReplayEntryChainIdAcceptable } from "./replayer.mjs";
3
3
  import { ArchivePayloadDecodeError, EntryHashRunVerifier, HotWindowPruneController, IncrementalMerkleTree, assertValidSegment, computeCheckpointHash, computeEntryHash, computeHotTailEntryCommitment, computeSegmentContentHash, createHotStuffTrustAnchor, createWitnessAttestation, deriveSegmentStateRoot, normalizeHttpBaseUrl, resolveTrustAnchor, verifyCheckpointQuorumCertificate, verifyCheckpointSignature, verifyDidMatchesMultiCurvePublicKey, verifyHotTailBatchSignature, verifyHotTailStatusSignature, verifySegmentCommitmentSignature } from "@arcblock/ledger-core";
4
4
  import { toBuffer } from "@ocap/util";
5
5
  import { CustomError } from "@ocap/util/lib/error";
@@ -215,11 +215,43 @@ function isLocalTrustedStorageHashError(err, depth = 0) {
215
215
  function isFatalVerificationFailure(err) {
216
216
  if (err instanceof ArchivePayloadDecodeError || err?.name === "ArchivePayloadDecodeError") return false;
217
217
  if (isTransientSqliteLockError(err)) return false;
218
+ if (err?.daFatal === true) return true;
218
219
  if (err?.authenticatedLocalFailure === true || err?.localDivergenceFailure === true) return true;
219
220
  const code = err?.code;
220
221
  if (isLocalTrustedStorageHashError(err)) return true;
221
222
  return code === "TRUST_ANCHOR_REQUIRED";
222
223
  }
224
+ /** The cold catch-up after a `410`: see `FollowerSyncService.coldCatchUpAfterPrune` (a pure function so it can be tested). */
225
+ async function catchUpAfterPrune(options) {
226
+ if (!options.isDaReader) return options.run();
227
+ try {
228
+ return await options.run();
229
+ } catch (err) {
230
+ if (isFatalVerificationFailure(err) || err?.mutatedLocalDbTransientLock === true) throw err;
231
+ options.onSwallowed(err, coldImportsBefore(err));
232
+ return coldImportsBefore(err);
233
+ }
234
+ }
235
+ /**
236
+ * A cold catch-up that fails after it already imported segments (a DA stall or a transient error at segment N+k) has
237
+ * changed the local database: the error carries how many it imported, so the callers do not treat the cycle as untouched.
238
+ */
239
+ function noteColdImports(err, imported) {
240
+ if (imported > 0 && err && typeof err === "object") err.coldImportedCount = imported;
241
+ }
242
+ /** How many segments a failed cold catch-up had imported before it failed (0 when it imported none or is not annotated). */
243
+ function coldImportsBefore(err) {
244
+ const n = err?.coldImportedCount;
245
+ return typeof n === "number" && Number.isSafeInteger(n) && n > 0 ? n : 0;
246
+ }
247
+ /**
248
+ * `.catch()` handler for a best-effort cold segment lookup (to find a checkpoint, not to import): a miss or a transient
249
+ * error is "not found here", but a fatal DA reader error (`daFatal`, #2017) is never swallowed: it halts the follower.
250
+ */
251
+ function coldLookupMiss(err) {
252
+ if (err?.daFatal === true) throw err;
253
+ return null;
254
+ }
223
255
  function canonicalizePeerBaseUrl(rawUrl) {
224
256
  const trimmed = rawUrl.trim();
225
257
  if (!trimmed) return "";
@@ -428,6 +460,7 @@ var FollowerSyncService = class {
428
460
  witnessEnabled: Boolean(this.witnessWallet),
429
461
  witnessAddress: this.witnessAddress,
430
462
  coldArchiveConfigured: Boolean(this.coldArchiveStore),
463
+ ...this.daArchiveDiagnostics(),
431
464
  peerCount: this.allowedBaseUrls.size,
432
465
  ...includePrivate ? {
433
466
  upstreamUrl: this.upstreamUrl,
@@ -445,6 +478,15 @@ var FollowerSyncService = class {
445
478
  } : null
446
479
  };
447
480
  }
481
+ /** The DA reader's status for `/api/health/ledger` (`daArchive`), or null for any other cold reader (#2017). */
482
+ getDaArchiveStatus() {
483
+ return this.daArchiveDiagnostics().daArchive ?? null;
484
+ }
485
+ /** DA follower only (#2017): `daArchive: { state: 'ok' | 'stalled', ... }`; nothing is added for any other cold reader. */
486
+ daArchiveDiagnostics() {
487
+ const reader = this.coldArchiveStore;
488
+ return reader?.isDaSegmentReader === true && typeof reader.getStatus === "function" ? { daArchive: reader.getStatus() } : {};
489
+ }
448
490
  async triggerSyncOrProbe() {
449
491
  if (this.halted) throw new CustomError("NODE_HALTED", `Follower node is halted: ${this.haltReason || "verification error"}`);
450
492
  const promoted = this.leaderRouter?.probeAndPromoteLeader ? await this.leaderRouter.probeAndPromoteLeader() : null;
@@ -1068,8 +1110,33 @@ var FollowerSyncService = class {
1068
1110
  * Stage 1B: Catch up sealed `.zst` checkpoint segments from `coldArchiveStore` when available.
1069
1111
  */
1070
1112
  async catchUpFromColdSegments(maxTargetHeight, verifiedHeadCheckpoint) {
1113
+ const progress = { imported: 0 };
1114
+ try {
1115
+ return await this.catchUpFromColdSegmentsInner(maxTargetHeight, verifiedHeadCheckpoint, progress);
1116
+ } catch (err) {
1117
+ if (this.coldArchiveStore?.isDaSegmentReader === true) noteColdImports(err, progress.imported);
1118
+ throw err;
1119
+ }
1120
+ }
1121
+ /**
1122
+ * The cold catch-up of a `410` (the leader pruned what the follower needs). Only a DA reader's non-fatal failure (a stall)
1123
+ * is treated as "no cold source this cycle"; any other cold reader keeps the base behaviour exactly: its error propagates.
1124
+ */
1125
+ async coldCatchUpAfterPrune(maxTargetHeight, verifiedHeadCheckpoint) {
1126
+ return catchUpAfterPrune({
1127
+ isDaReader: this.coldArchiveStore?.isDaSegmentReader === true,
1128
+ run: () => this.catchUpFromColdSegments(maxTargetHeight, verifiedHeadCheckpoint),
1129
+ onSwallowed: (err, imported) => this.resolver.logger.warn("Cold archive segment unavailable after a pruned upstream; not a cold source for this cycle", {
1130
+ chainId: this.chainId,
1131
+ imported,
1132
+ error: err instanceof Error ? err.message : String(err)
1133
+ })
1134
+ });
1135
+ }
1136
+ async catchUpFromColdSegmentsInner(maxTargetHeight, verifiedHeadCheckpoint, progress) {
1071
1137
  if (!this.coldArchiveStore) return 0;
1072
1138
  await this.hydrateDurableTrustRatchet();
1139
+ const isDaCold = this.coldArchiveStore.isDaSegmentReader === true;
1073
1140
  const verifiedColdAncestors = /* @__PURE__ */ new Map();
1074
1141
  if (verifiedHeadCheckpoint && typeof verifiedHeadCheckpoint.hash === "string" && normalizeHexDigest(computeCheckpointHash(verifiedHeadCheckpoint)) === normalizeHexDigest(verifiedHeadCheckpoint.hash)) verifiedColdAncestors.set(verifiedHeadCheckpoint.height, verifiedHeadCheckpoint);
1075
1142
  let importedCount = 0;
@@ -1111,6 +1178,7 @@ var FollowerSyncService = class {
1111
1178
  checkpoint: rawSegment.checkpoint,
1112
1179
  entries: rawSegment.entries
1113
1180
  };
1181
+ if (isDaCold && verifiedHeadCheckpoint && canonicalSegment.checkpoint.height === verifiedHeadCheckpoint.height && (normalizeHexDigest(canonicalSegment.checkpoint.hash) !== normalizeHexDigest(verifiedHeadCheckpoint.hash) || normalizeHexDigest(canonicalSegment.checkpoint.stateRoot ?? "") !== normalizeHexDigest(verifiedHeadCheckpoint.stateRoot ?? ""))) throw Object.assign(new CustomError("DA_LEADER_MISMATCH", `DA segment #${nextHeight} (${canonicalSegment.checkpoint.hash}) is not the leader's signed checkpoint at that height (${verifiedHeadCheckpoint.hash})`), { daFatal: true });
1114
1182
  if ("contentHash" in rawBundle && rawBundle.contentHash !== void 0) {
1115
1183
  if (typeof rawBundle.contentHash !== "string" || rawBundle.contentHash.replace(/^0x/i, "").toLowerCase() !== computeSegmentContentHash(canonicalSegment).replace(/^0x/i, "").toLowerCase()) throw new CustomError("COLD_BUNDLE_WRAPPER_MISMATCH", `Cold segment #${nextHeight} unsigned contentHash wrapper does not match canonical segment digest`);
1116
1184
  }
@@ -1132,7 +1200,7 @@ var FollowerSyncService = class {
1132
1200
  }
1133
1201
  let stepCp = h === nextHeight ? canonicalSegment.checkpoint : verifiedColdAncestors.get(h) ?? null;
1134
1202
  if (!stepCp) {
1135
- const stepSeg = await this.coldArchiveStore.getSegment(this.chainId, h).catch(() => null);
1203
+ const stepSeg = await this.coldArchiveStore.getSegment(this.chainId, h).catch(coldLookupMiss);
1136
1204
  stepCp = stepSeg && stepSeg.chainId === this.chainId ? stepSeg.checkpoint : null;
1137
1205
  }
1138
1206
  if (!stepCp || typeof stepCp.hash !== "string" || normalizeHexDigest(stepCp.hash) !== normalizeHexDigest(expectedHash) || normalizeHexDigest(computeCheckpointHash(stepCp)) !== normalizeHexDigest(expectedHash)) {
@@ -1198,7 +1266,10 @@ var FollowerSyncService = class {
1198
1266
  }
1199
1267
  throw segVerifyErr;
1200
1268
  }
1201
- for (const entry of canonicalSegment.entries) this.replayer.validateWireEntry(entry);
1269
+ for (const entry of canonicalSegment.entries) {
1270
+ this.replayer.validateWireEntry(entry);
1271
+ assertReplayEntryChainIdAcceptable(entry, this.chainId, "Cold segment");
1272
+ }
1202
1273
  const hadPartialLocalEntries = localSeq > canonicalSegment.checkpoint.prevSequence;
1203
1274
  let mutatedLocalDb = false;
1204
1275
  try {
@@ -1287,6 +1358,7 @@ var FollowerSyncService = class {
1287
1358
  verifiedLocalStateRoot: verifiedColdStateRoot
1288
1359
  });
1289
1360
  importedCount++;
1361
+ progress.imported = importedCount;
1290
1362
  if (importedCount >= MAX_PAGES_PER_SYNC_CYCLE) break;
1291
1363
  }
1292
1364
  if (importedCount > 0 && this.pruneController) await this.pruneController.pruneHotWindow(this.resolver.ledger);
@@ -1369,7 +1441,7 @@ var FollowerSyncService = class {
1369
1441
  publicKeyOrVerifier: coldVerifyAnchor,
1370
1442
  requireSignature: !importOpts.allowUnauthenticated,
1371
1443
  allowUnauthenticated: importOpts.allowUnauthenticated
1372
- }).catch(() => null);
1444
+ }).catch(coldLookupMiss);
1373
1445
  if (seg && seg.chainId === this.chainId) {
1374
1446
  targetCp = seg.checkpoint;
1375
1447
  const coldAuth = await this.isColdSegmentAuthenticatedByProposer(seg);
@@ -1516,7 +1588,10 @@ var FollowerSyncService = class {
1516
1588
  hotstuffClusterConfig: importOpts.hotstuffClusterConfig
1517
1589
  });
1518
1590
  if (importOpts.allowUnauthenticated && !trustAnchor) {
1519
- for (let i = 0; i < entries.length; i++) this.replayer.validateWireEntry(entries[i]);
1591
+ for (let i = 0; i < entries.length; i++) {
1592
+ this.replayer.validateWireEntry(entries[i]);
1593
+ assertReplayEntryChainIdAcceptable(entries[i], this.chainId, "Hot-tail");
1594
+ }
1520
1595
  return batchParsedV2From ?? parsedV2From;
1521
1596
  }
1522
1597
  if (!trustAnchor) {
@@ -1531,7 +1606,7 @@ var FollowerSyncService = class {
1531
1606
  const entry = entries[i];
1532
1607
  const expectedSeq = requestedFrom + i;
1533
1608
  if (!entry || entry.sequence !== expectedSeq) throw new CustomError("INVALID_LEDGER_ENTRY", `Hot-tail batch sequence discontinuity at index ${i}: expected ${expectedSeq}, got ${entry?.sequence}`);
1534
- if (entry.chainId !== this.chainId) throw new CustomError("CHAIN_ID_MISMATCH", `Hot-tail entry chainId (${entry.chainId}) !== local chainId (${this.chainId})`);
1609
+ if (!isReplayEntryChainIdAcceptable(entry, this.chainId)) assertReplayEntryChainIdAcceptable(entry, this.chainId, "Hot-tail");
1535
1610
  if (entry.finalized !== true) throw new CustomError("UNFINALIZED_LEDGER_ENTRY", `Hot-tail entry seq=${entry.sequence} is not finalized`);
1536
1611
  if (!Number.isSafeInteger(entry.timestamp) || entry.timestamp < 0 || entry.timestamp > MAX_SAFE_EPOCH_MS) throw new CustomError("INVALID_LEDGER_ENTRY", `Hot-tail entry seq=${entry.sequence} has invalid timestamp: ${String(entry.timestamp)}`);
1537
1612
  if (typeof entry.txRaw !== "string" || !entry.txRaw || entry.txRaw !== entry.txRaw.trim()) throw new CustomError("INVALID_LEDGER_ENTRY", `Hot-tail entry seq=${entry.sequence} has missing or non-canonical txRaw`);
@@ -1675,7 +1750,7 @@ var FollowerSyncService = class {
1675
1750
  publicKeyOrVerifier: coldVerifyAnchor,
1676
1751
  requireSignature: !importOpts.allowUnauthenticated,
1677
1752
  allowUnauthenticated: importOpts.allowUnauthenticated
1678
- }).catch(() => null);
1753
+ }).catch(coldLookupMiss);
1679
1754
  if (seg && seg.chainId === this.chainId) targetCp = seg.checkpoint;
1680
1755
  }
1681
1756
  if (!targetCp) return markUnauthenticatedPeerError(new CustomError(cpRes && cpRes.status === 200 ? "UPSTREAM_BAD_RESPONSE" : "UPSTREAM_UNAVAILABLE", `Upstream checkpoint #${nextHeight} unavailable or failed hash-chain verification before buffered commit`));
@@ -1729,7 +1804,7 @@ var FollowerSyncService = class {
1729
1804
  for (let i = 0; i < segEntries.length; i++) {
1730
1805
  const entry = segEntries[i];
1731
1806
  const expectedSeq = targetCp.prevSequence + 1 + i;
1732
- if (entry.sequence !== expectedSeq || entry.chainId !== this.chainId || !entry.finalized) return markUnauthenticatedPeerError(new CustomError("LEDGER_DIVERGENCE", `Buffered pre-commit checkpoint #${nextHeight} invalid entry at seq=${entry.sequence}`));
1807
+ if (entry.sequence !== expectedSeq || !isReplayEntryChainIdAcceptable(entry, this.chainId) || !entry.finalized) return markUnauthenticatedPeerError(new CustomError("LEDGER_DIVERGENCE", `Buffered pre-commit checkpoint #${nextHeight} invalid entry at seq=${entry.sequence}`));
1733
1808
  if (!hashRun.check(entry).ok) return markUnauthenticatedPeerError(new CustomError("LEDGER_DIVERGENCE", `Buffered pre-commit checkpoint #${nextHeight} entryHash mismatch at seq=${entry.sequence}`));
1734
1809
  tree.append(entry.entryHash);
1735
1810
  }
@@ -1787,7 +1862,7 @@ var FollowerSyncService = class {
1787
1862
  const pageLimit = Math.min(MAX_HOT_TAIL_LIMIT, targetCp.sequence - cursor + 1);
1788
1863
  const entriesRes = await this.fetchAllowlistedJson(targetBaseUrl, `/api/ledger/entries?from=${cursor}&limit=${pageLimit}`, ENTRIES_MAX_RESPONSE_BYTES);
1789
1864
  if (entriesRes.status === 410 && this.coldArchiveStore) {
1790
- if (await this.catchUpFromColdSegments(nextHeight) > 0) {
1865
+ if (await this.coldCatchUpAfterPrune(nextHeight) > 0) {
1791
1866
  localCp = await this.resolver.ledger.getCheckpoint();
1792
1867
  localHeight = localCp?.height ?? 0;
1793
1868
  localSeq = await this.resolver.ledger.getLatestSequence();
@@ -1801,6 +1876,7 @@ var FollowerSyncService = class {
1801
1876
  if (item.sequence > targetCp.sequence) break;
1802
1877
  if (item.sequence !== cursor) throw new CustomError("INVALID_LEDGER_ENTRY", `Non-contiguous entry sequence at height ${nextHeight}: expected ${cursor}, got ${item.sequence}`);
1803
1878
  this.replayer.validateWireEntry(item, { skipFutureTimestampCheck: true });
1879
+ assertReplayEntryChainIdAcceptable(item, this.chainId, "HotStuff QC segment");
1804
1880
  segmentEntries.push(item);
1805
1881
  cursor++;
1806
1882
  }
@@ -2146,8 +2222,10 @@ var FollowerSyncService = class {
2146
2222
  if (await this.catchUpFromColdSegments(upstreamStatus.latestCheckpoint?.height, verifiedHeadCp) > 0) mutatedLocalDbOnPeer = true;
2147
2223
  } catch (coldErr) {
2148
2224
  if (isFatalVerificationFailure(coldErr) || coldErr?.mutatedLocalDbTransientLock === true) throw coldErr;
2225
+ if (coldImportsBefore(coldErr) > 0) mutatedLocalDbOnPeer = true;
2149
2226
  this.resolver.logger.warn("Cold archive segment unavailable or unverified; falling back to hot-tail sync", {
2150
2227
  chainId: this.chainId,
2228
+ ...this.coldArchiveStore?.isDaSegmentReader === true ? { imported: coldImportsBefore(coldErr) } : {},
2151
2229
  error: coldErr instanceof Error ? coldErr.message : String(coldErr)
2152
2230
  });
2153
2231
  }
@@ -2220,7 +2298,7 @@ var FollowerSyncService = class {
2220
2298
  const entriesRes = await this.fetchAllowlistedJson(targetBaseUrl, `/api/ledger/entries?from=${from}&limit=${MAX_HOT_TAIL_LIMIT}`, ENTRIES_MAX_RESPONSE_BYTES);
2221
2299
  if (entriesRes.status === 410) {
2222
2300
  if (this.coldArchiveStore && bufferedTailBatches.length === 0) {
2223
- const imported = await this.catchUpFromColdSegments(upstreamStatus.latestCheckpoint?.height, verifiedHeadCp);
2301
+ const imported = await this.coldCatchUpAfterPrune(upstreamStatus.latestCheckpoint?.height, verifiedHeadCp);
2224
2302
  localSeq = await this.resolver.ledger.getLatestSequence();
2225
2303
  cursorSeq = localSeq;
2226
2304
  if (imported > 0) mutatedLocalDbOnPeer = true;
@@ -2455,4 +2533,4 @@ var FollowerSyncService = class {
2455
2533
  };
2456
2534
 
2457
2535
  //#endregion
2458
- export { DEFAULT_FOLLOWER_HTTP_TIMEOUT_MS, DEFAULT_FOLLOWER_MAX_SYNC_LAG, DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS, DEFAULT_FOLLOWER_POLL_INTERVAL_MS, FollowerSyncService, isTransientSqliteLockError };
2536
+ export { DEFAULT_FOLLOWER_HTTP_TIMEOUT_MS, DEFAULT_FOLLOWER_MAX_SYNC_LAG, DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS, DEFAULT_FOLLOWER_POLL_INTERVAL_MS, FollowerSyncService, catchUpAfterPrune, coldImportsBefore, coldLookupMiss, isTransientSqliteLockError, noteColdImports };
@@ -31,6 +31,24 @@ interface IDryRunVerifyEntriesOptions {
31
31
  /** Entries come from the local ledger (crash reconciliation), not from a peer: skip the future-timestamp guard. */
32
32
  skipFutureTimestampCheck?: boolean;
33
33
  }
34
+ /**
35
+ * Cross-layer chainId rule for executable replay (#2029, #2039):
36
+ * Own-chain entries (`entry.chainId === expectedChainId`) are accepted directly; a self-declared foreign-`chainId`
37
+ * wire entry (`isEntryChainIdAcceptable(entry, expectedChainId)`) can ONLY execute as a force-finalized orphan
38
+ * (`(entry.stateCommitHash ?? '').trim() === ''`), because `VerifyTx` rejects `chainId !== config.chainId` before
39
+ * `PrepareState`/`CommitState` so a foreign-`chainId` entry can never commit state.
40
+ */
41
+ declare function isReplayEntryChainIdAcceptable(entry: {
42
+ chainId?: string | null;
43
+ txRaw: string;
44
+ stateCommitHash?: string | null;
45
+ }, expectedChainId: string): boolean;
46
+ declare function assertReplayEntryChainIdAcceptable(entry: {
47
+ sequence?: unknown;
48
+ chainId?: string | null;
49
+ txRaw: string;
50
+ stateCommitHash?: string | null;
51
+ }, expectedChainId: string, prefix?: string): void;
34
52
  interface IValidateWireEntryOptions {
35
53
  /** Entries come from the local ledger (crash reconciliation), not from a peer: skip the future-timestamp guard. */
36
54
  skipFutureTimestampCheck?: boolean;
@@ -93,6 +111,13 @@ declare class LedgerEntryReplayer {
93
111
  */
94
112
  validateWireEntry(entry: ILedgerEntry, options?: IValidateWireEntryOptions): void;
95
113
  private authenticateAndDecodeEntry;
114
+ /**
115
+ * Synchronously run `pipes.DecodeTx` + `pipes.DecodeItx` on a force-finalized orphan entry (`stateCommitHash === ''`)
116
+ * so any wire byte ceiling, non-canonical `signatures[].data` JSON, undecodable nested Any, or missing `itx` is
117
+ * caught as a peer-disqualifying `INVALID_LEDGER_ENTRY` BEFORE `importSegment` / `appendVerifiedEntryToLedger`
118
+ * mutates `ledger.sqlite` (#2039).
119
+ */
120
+ private decodeOrphanEntryContext;
96
121
  /**
97
122
  * Index a rejected-but-ledgered entry (finalized, no stateCommitHash) with the row the leader wrote for it: the
98
123
  * leader's `sendTx` passes the context of its `DecodeTx` + `DecodeItx` pipes to `_indexRejectedLedgerTx`, so the
@@ -123,4 +148,4 @@ declare class LedgerEntryReplayer {
123
148
  indexExistingOrphanEntries(fromSeq?: number, toSeq?: number): Promise<number>;
124
149
  }
125
150
  //#endregion
126
- export { FUTURE_LEDGER_ENTRY_TIMESTAMP, IDryRunVerifyEntriesOptions, IDryRunVerifyEntriesResult, IFutureTimestampGuardOptions, IFutureTimestampRejection, ILedgerEntryReplayerOptions, IReplayEntryOptions, IReplayEntryResult, IReplayerResolverTarget, IValidateWireEntryOptions, LedgerEntryReplayer };
151
+ export { FUTURE_LEDGER_ENTRY_TIMESTAMP, IDryRunVerifyEntriesOptions, IDryRunVerifyEntriesResult, IFutureTimestampGuardOptions, IFutureTimestampRejection, ILedgerEntryReplayerOptions, IReplayEntryOptions, IReplayEntryResult, IReplayerResolverTarget, IValidateWireEntryOptions, LedgerEntryReplayer, assertReplayEntryChainIdAcceptable, isReplayEntryChainIdAcceptable };
package/esm/replayer.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { authenticateEntryDecodedFields, computeEntryHash } from "@arcblock/ledger-core";
1
+ import { authenticateEntryDecodedFields, computeEntryHash, isEntryChainIdAcceptable } from "@arcblock/ledger-core";
2
2
  import { toTxHash } from "@ocap/mcrypto";
3
3
  import { createExecutor } from "@ocap/tx-protocols";
4
4
  import { fromBase64 } from "@ocap/util";
@@ -24,6 +24,22 @@ import merge from "lodash/merge.js";
24
24
  * - Enforces pre-commit `expectedCommitHash` on `statedb.runAsLambda` so any state divergence rolls back
25
25
  * SQLite atomically BEFORE `COMMIT` and before appending to `ledger.sqlite`.
26
26
  */
27
+ /**
28
+ * Cross-layer chainId rule for executable replay (#2029, #2039):
29
+ * Own-chain entries (`entry.chainId === expectedChainId`) are accepted directly; a self-declared foreign-`chainId`
30
+ * wire entry (`isEntryChainIdAcceptable(entry, expectedChainId)`) can ONLY execute as a force-finalized orphan
31
+ * (`(entry.stateCommitHash ?? '').trim() === ''`), because `VerifyTx` rejects `chainId !== config.chainId` before
32
+ * `PrepareState`/`CommitState` so a foreign-`chainId` entry can never commit state.
33
+ */
34
+ function isReplayEntryChainIdAcceptable(entry, expectedChainId) {
35
+ if (entry.chainId === expectedChainId) return true;
36
+ return isEntryChainIdAcceptable(entry, expectedChainId) && (entry.stateCommitHash ?? "").trim() === "";
37
+ }
38
+ function assertReplayEntryChainIdAcceptable(entry, expectedChainId, prefix = "Ledger entry") {
39
+ if (isReplayEntryChainIdAcceptable(entry, expectedChainId)) return;
40
+ if (entry.chainId !== expectedChainId && typeof entry.txRaw === "string" && isEntryChainIdAcceptable(entry, expectedChainId) && (entry.stateCommitHash ?? "").trim() !== "") throw new CustomError("CHAIN_ID_MISMATCH", `${prefix} foreign-chainId entry at seq=${String(entry.sequence)} (chainId=${String(entry.chainId)}, local=${expectedChainId}) cannot carry a stateCommitHash`);
41
+ throw new CustomError("CHAIN_ID_MISMATCH", `${prefix} chainId mismatch at seq=${String(entry.sequence)}: expected ${expectedChainId}, got ${String(entry.chainId)}`);
42
+ }
27
43
  /** Error code of a replayed entry refused for a timestamp ahead of the local clock (retryable, never halting). */
28
44
  const FUTURE_LEDGER_ENTRY_TIMESTAMP = "FUTURE_LEDGER_ENTRY_TIMESTAMP";
29
45
  function normalizeHexLower(raw) {
@@ -184,6 +200,7 @@ var LedgerEntryReplayer = class {
184
200
  if (!entry || typeof entry !== "object" || !Number.isSafeInteger(entry.sequence) || entry.sequence < 1 || !Number.isSafeInteger(entry.nonce) || entry.nonce < 0 || !Number.isSafeInteger(entry.timestamp) || entry.timestamp < 0 || entry.timestamp > 864e13 || typeof entry.hash !== "string" || typeof entry.from !== "string" || typeof entry.pk !== "string" || typeof entry.signature !== "string" || typeof entry.txRaw !== "string" || typeof entry.txType !== "string" || typeof entry.chainId !== "string" || typeof entry.entryHash !== "string" || typeof entry.finalized !== "boolean" || entry.stateCommitHash !== void 0 && typeof entry.stateCommitHash !== "string" || entry.tx === null || typeof entry.tx !== "object" || Array.isArray(entry.tx)) throw new CustomError("INVALID_LEDGER_ENTRY", `Ledger entry seq=${String(entry?.sequence)} has invalid wire primitive types`);
185
201
  this.verifyRawTxHashMatchesEntry(entry, "INVALID_LEDGER_ENTRY");
186
202
  this.authenticateAndDecodeEntry(entry);
203
+ if (!(entry.stateCommitHash ?? "").trim()) this.decodeOrphanEntryContext(entry);
187
204
  if (!options.skipFutureTimestampCheck) this.assertEntryTimestampNotInFuture(entry);
188
205
  }
189
206
  authenticateAndDecodeEntry(entry) {
@@ -192,31 +209,44 @@ var LedgerEntryReplayer = class {
192
209
  return authRes.decodedTx;
193
210
  }
194
211
  /**
195
- * Index a rejected-but-ledgered entry (finalized, no stateCommitHash) with the row the leader wrote for it: the
196
- * leader's `sendTx` passes the context of its `DecodeTx` + `DecodeItx` pipes to `_indexRejectedLedgerTx`, so the
197
- * follower builds that context from the entry's txRaw with the same pipes and the time pinned to the entry
198
- * (#1875). Only the rejection code differs: it is not in the ledger, so the row says `ORPHAN_LEDGER_ENTRY`.
212
+ * Synchronously run `pipes.DecodeTx` + `pipes.DecodeItx` on a force-finalized orphan entry (`stateCommitHash === ''`)
213
+ * so any wire byte ceiling, non-canonical `signatures[].data` JSON, undecodable nested Any, or missing `itx` is
214
+ * caught as a peer-disqualifying `INVALID_LEDGER_ENTRY` BEFORE `importSegment` / `appendVerifiedEntryToLedger`
215
+ * mutates `ledger.sqlite` (#2039).
199
216
  */
200
- async indexOrphanEntry(entry) {
217
+ decodeOrphanEntryContext(entry) {
201
218
  const ctx = {
202
219
  txBase64: entry.txRaw,
203
220
  config: this.resolver.config,
204
221
  extra: { txTime: entry.timestamp }
205
222
  };
206
- const runPipe = (pipe) => new Promise((resolve, reject) => {
207
- try {
208
- pipe(ctx, (err) => err ? reject(err) : resolve());
209
- } catch (err) {
210
- reject(err);
211
- }
212
- });
223
+ const runPipeSync = (pipe) => {
224
+ let pipeErr;
225
+ let completed = false;
226
+ pipe(ctx, (err) => {
227
+ completed = true;
228
+ pipeErr = err;
229
+ });
230
+ if (!completed) throw new Error("Orphan decode pipe did not complete synchronously");
231
+ if (pipeErr) throw pipeErr;
232
+ };
213
233
  try {
214
- await runPipe(pipes.DecodeTx);
215
- await runPipe(pipes.DecodeItx);
234
+ runPipeSync(pipes.DecodeTx);
235
+ runPipeSync(pipes.DecodeItx);
216
236
  } catch (err) {
217
237
  throw new CustomError("INVALID_LEDGER_ENTRY", `Orphan ledger entry seq=${entry.sequence} hash=${entry.hash} does not decode as the leader decodes it: ${err instanceof Error ? err.message : String(err)}`);
218
238
  }
219
- if (String(ctx.txHash ?? "").toUpperCase() !== String(entry.hash).toUpperCase()) throw new CustomError("TX_HASH_MISMATCH", `Orphan ledger entry seq=${entry.sequence} hash=${entry.hash}: txRaw does not hash to its entry hash`);
239
+ if (String(ctx.txHash ?? "").toUpperCase() !== String(entry.hash).toUpperCase()) throw new CustomError("INVALID_LEDGER_ENTRY", `Orphan ledger entry seq=${entry.sequence} hash=${entry.hash}: txRaw does not hash to its entry hash`);
240
+ return ctx;
241
+ }
242
+ /**
243
+ * Index a rejected-but-ledgered entry (finalized, no stateCommitHash) with the row the leader wrote for it: the
244
+ * leader's `sendTx` passes the context of its `DecodeTx` + `DecodeItx` pipes to `_indexRejectedLedgerTx`, so the
245
+ * follower builds that context from the entry's txRaw with the same pipes and the time pinned to the entry
246
+ * (#1875). Only the rejection code differs: it is not in the ledger, so the row says `ORPHAN_LEDGER_ENTRY`.
247
+ */
248
+ async indexOrphanEntry(entry, preDecodedCtx) {
249
+ const ctx = preDecodedCtx ?? this.decodeOrphanEntryContext(entry);
220
250
  const leaderCtx = merge(cloneDeep(ctx), ctx);
221
251
  leaderCtx.ledgerSequence = entry.sequence;
222
252
  await this.resolver._indexRejectedLedgerTx(leaderCtx, { code: "ORPHAN_LEDGER_ENTRY" });
@@ -230,8 +260,7 @@ var LedgerEntryReplayer = class {
230
260
  if (!entry || typeof entry !== "object") throw new CustomError("INVALID_LEDGER_ENTRY", "Cannot replay null or non-object ledger entry");
231
261
  if (!entry.finalized) throw new CustomError("UNFINALIZED_LEDGER_ENTRY", `Refusing to replay unfinalized entry seq=${entry.sequence}`);
232
262
  if (!Number.isSafeInteger(entry.timestamp) || entry.timestamp < 0 || entry.timestamp > 864e13) throw new CustomError("INVALID_LEDGER_ENTRY", `Refusing to replay entry seq=${entry.sequence} with out-of-range timestamp: ${String(entry.timestamp)}`);
233
- const expectedChainId = this.resolver.config.chainId || this.resolver.ledger.chainId;
234
- if (entry.chainId !== expectedChainId) throw new CustomError("CHAIN_ID_MISMATCH", `Ledger entry chainId mismatch at seq=${entry.sequence}: expected ${expectedChainId}, got ${entry.chainId}`);
263
+ assertReplayEntryChainIdAcceptable(entry, this.resolver.config.chainId || this.resolver.ledger.chainId, "Ledger entry");
235
264
  const appendToLedger = options.appendToLedger !== false;
236
265
  if (options.entryHashV2From !== void 0 && options.entryHashV2From !== "infinity" && (!Number.isSafeInteger(options.entryHashV2From) || options.entryHashV2From < 1)) throw new CustomError("INVALID_LEDGER_ENTRY", `Invalid entryHashV2From replay option: ${String(options.entryHashV2From)}`);
237
266
  if (!Number.isSafeInteger(entry.sequence) || entry.sequence < 1 || !Number.isSafeInteger(entry.nonce) || entry.nonce < 0 || typeof entry.entryHash !== "string" || !entry.entryHash || entry.stateCommitHash !== void 0 && typeof entry.stateCommitHash !== "string") throw new CustomError("INVALID_LEDGER_ENTRY", `Ledger entry seq=${String(entry.sequence)} has invalid sequence, nonce, or entryHash types`);
@@ -260,8 +289,9 @@ var LedgerEntryReplayer = class {
260
289
  if (entry.entryHash !== expectedEntryHash) throw new CustomError("INVALID_LEDGER_ENTRY", `Ledger entryHash mismatch before execution at seq=${entry.sequence}: expected ${expectedEntryHash}, got ${entry.entryHash}`);
261
290
  }
262
291
  if (!expectedStateCommit) {
292
+ const decodedOrphanCtx = this.decodeOrphanEntryContext(entry);
263
293
  if (appendToLedger) await this.appendVerifiedEntryToLedger(entry, options.entryHashV2From);
264
- await this.indexOrphanEntry(entry);
294
+ await this.indexOrphanEntry(entry, decodedOrphanCtx);
265
295
  return {
266
296
  status: "orphan-indexed",
267
297
  sequence: entry.sequence,
@@ -340,7 +370,7 @@ var LedgerEntryReplayer = class {
340
370
  const entry = entries[i];
341
371
  if (!entry || typeof entry !== "object") throw new CustomError("INVALID_LEDGER_ENTRY", `Proposal entry at index ${i} is not an object`);
342
372
  if (entry.finalized !== true) throw new CustomError("UNFINALIZED_LEDGER_ENTRY", `Proposal entry seq=${String(entry.sequence)} must be finalized`);
343
- if (entry.chainId !== expectedChainId) throw new CustomError("CHAIN_ID_MISMATCH", `Proposal entry chainId mismatch at seq=${String(entry.sequence)}: expected ${expectedChainId}, got ${entry.chainId}`);
373
+ assertReplayEntryChainIdAcceptable(entry, expectedChainId, "Proposal entry");
344
374
  if (entry.sequence !== baseSeq + i + 1) throw new CustomError("SEQUENCE_GAP", `Proposal entry sequence mismatch at index ${i}: expected ${baseSeq + i + 1}, got ${entry.sequence}`);
345
375
  this.validateWireEntry(entry, { skipFutureTimestampCheck: options.skipFutureTimestampCheck });
346
376
  const expectedStateCommit = (entry.stateCommitHash ?? "").trim();
@@ -459,4 +489,4 @@ var LedgerEntryReplayer = class {
459
489
  };
460
490
 
461
491
  //#endregion
462
- export { FUTURE_LEDGER_ENTRY_TIMESTAMP, LedgerEntryReplayer };
492
+ export { FUTURE_LEDGER_ENTRY_TIMESTAMP, LedgerEntryReplayer, assertReplayEntryChainIdAcceptable, isReplayEntryChainIdAcceptable };
package/lib/dashboard.cjs CHANGED
@@ -83,6 +83,8 @@ async function collectLedgerHealthSummary(options) {
83
83
  const proposerPublicKey = options.ledger.getProposerPublicKey?.() || null;
84
84
  const checkpointSigningEnabled = typeof options.ledger.isCheckpointSigningEnabled === "function" ? options.ledger.isCheckpointSigningEnabled() : Boolean(proposerPublicKey);
85
85
  const witnessRegistry = extLedger.getWitnessRegistry?.();
86
+ const daPublisher = extLedger.getDaPublisherStatus?.() ?? null;
87
+ const daArchive = options.runtime?.getDaArchiveStatus?.() ?? null;
86
88
  return {
87
89
  healthy,
88
90
  ...halted ? {
@@ -104,6 +106,8 @@ async function collectLedgerHealthSummary(options) {
104
106
  witnessQuorum: witnessRegistry?.getQuorum() ?? 0,
105
107
  witnessCircuitBroken: witnessRegistry?.isCircuitBroken() ?? false,
106
108
  witnessFraudAlertCount: witnessRegistry?.getFraudAlerts().length ?? 0,
109
+ ...daPublisher ? { daPublisher } : {},
110
+ ...daArchive ? { daArchive } : {},
107
111
  entryHashV2From,
108
112
  latestSequence: health.latestSequence,
109
113
  latestCheckpoint: health.latestCheckpoint ? {
@@ -658,6 +662,7 @@ function createNodeDashboardRouter(options) {
658
662
  witnessQuorum: ledgerHealth.witnessQuorum,
659
663
  witnessCircuitBroken: ledgerHealth.witnessCircuitBroken,
660
664
  witnessFraudAlertCount: ledgerHealth.witnessFraudAlertCount,
665
+ ...ledgerHealth.daPublisher ? { publisher: ledgerHealth.daPublisher } : {},
661
666
  latestAnchorReceipt
662
667
  },
663
668
  pipeline,
@@ -84,6 +84,10 @@ interface ILedgerHealthSummary {
84
84
  witnessQuorum: number;
85
85
  witnessCircuitBroken: boolean;
86
86
  witnessFraudAlertCount: number;
87
+ /** Present only when the segment publisher runs in DA mode (#2016); never part of `healthy` */
88
+ daPublisher?: Record<string, unknown>;
89
+ /** Present only on a follower that reads the DA archive (#2017): `{ state: 'ok' }` or `{ state: 'stalled', code: 'DA_GAP', ... }`; never part of `healthy` */
90
+ daArchive?: Record<string, unknown>;
87
91
  entryHashV2From: string | null;
88
92
  latestSequence: number;
89
93
  latestCheckpoint: (Record<string, unknown> & {
package/lib/follower.cjs CHANGED
@@ -216,11 +216,43 @@ function isLocalTrustedStorageHashError(err, depth = 0) {
216
216
  function isFatalVerificationFailure(err) {
217
217
  if (err instanceof _arcblock_ledger_core.ArchivePayloadDecodeError || err?.name === "ArchivePayloadDecodeError") return false;
218
218
  if (isTransientSqliteLockError(err)) return false;
219
+ if (err?.daFatal === true) return true;
219
220
  if (err?.authenticatedLocalFailure === true || err?.localDivergenceFailure === true) return true;
220
221
  const code = err?.code;
221
222
  if (isLocalTrustedStorageHashError(err)) return true;
222
223
  return code === "TRUST_ANCHOR_REQUIRED";
223
224
  }
225
+ /** The cold catch-up after a `410`: see `FollowerSyncService.coldCatchUpAfterPrune` (a pure function so it can be tested). */
226
+ async function catchUpAfterPrune(options) {
227
+ if (!options.isDaReader) return options.run();
228
+ try {
229
+ return await options.run();
230
+ } catch (err) {
231
+ if (isFatalVerificationFailure(err) || err?.mutatedLocalDbTransientLock === true) throw err;
232
+ options.onSwallowed(err, coldImportsBefore(err));
233
+ return coldImportsBefore(err);
234
+ }
235
+ }
236
+ /**
237
+ * A cold catch-up that fails after it already imported segments (a DA stall or a transient error at segment N+k) has
238
+ * changed the local database: the error carries how many it imported, so the callers do not treat the cycle as untouched.
239
+ */
240
+ function noteColdImports(err, imported) {
241
+ if (imported > 0 && err && typeof err === "object") err.coldImportedCount = imported;
242
+ }
243
+ /** How many segments a failed cold catch-up had imported before it failed (0 when it imported none or is not annotated). */
244
+ function coldImportsBefore(err) {
245
+ const n = err?.coldImportedCount;
246
+ return typeof n === "number" && Number.isSafeInteger(n) && n > 0 ? n : 0;
247
+ }
248
+ /**
249
+ * `.catch()` handler for a best-effort cold segment lookup (to find a checkpoint, not to import): a miss or a transient
250
+ * error is "not found here", but a fatal DA reader error (`daFatal`, #2017) is never swallowed: it halts the follower.
251
+ */
252
+ function coldLookupMiss(err) {
253
+ if (err?.daFatal === true) throw err;
254
+ return null;
255
+ }
224
256
  function canonicalizePeerBaseUrl(rawUrl) {
225
257
  const trimmed = rawUrl.trim();
226
258
  if (!trimmed) return "";
@@ -429,6 +461,7 @@ var FollowerSyncService = class {
429
461
  witnessEnabled: Boolean(this.witnessWallet),
430
462
  witnessAddress: this.witnessAddress,
431
463
  coldArchiveConfigured: Boolean(this.coldArchiveStore),
464
+ ...this.daArchiveDiagnostics(),
432
465
  peerCount: this.allowedBaseUrls.size,
433
466
  ...includePrivate ? {
434
467
  upstreamUrl: this.upstreamUrl,
@@ -446,6 +479,15 @@ var FollowerSyncService = class {
446
479
  } : null
447
480
  };
448
481
  }
482
+ /** The DA reader's status for `/api/health/ledger` (`daArchive`), or null for any other cold reader (#2017). */
483
+ getDaArchiveStatus() {
484
+ return this.daArchiveDiagnostics().daArchive ?? null;
485
+ }
486
+ /** DA follower only (#2017): `daArchive: { state: 'ok' | 'stalled', ... }`; nothing is added for any other cold reader. */
487
+ daArchiveDiagnostics() {
488
+ const reader = this.coldArchiveStore;
489
+ return reader?.isDaSegmentReader === true && typeof reader.getStatus === "function" ? { daArchive: reader.getStatus() } : {};
490
+ }
449
491
  async triggerSyncOrProbe() {
450
492
  if (this.halted) throw new _ocap_util_lib_error.CustomError("NODE_HALTED", `Follower node is halted: ${this.haltReason || "verification error"}`);
451
493
  const promoted = this.leaderRouter?.probeAndPromoteLeader ? await this.leaderRouter.probeAndPromoteLeader() : null;
@@ -1069,8 +1111,33 @@ var FollowerSyncService = class {
1069
1111
  * Stage 1B: Catch up sealed `.zst` checkpoint segments from `coldArchiveStore` when available.
1070
1112
  */
1071
1113
  async catchUpFromColdSegments(maxTargetHeight, verifiedHeadCheckpoint) {
1114
+ const progress = { imported: 0 };
1115
+ try {
1116
+ return await this.catchUpFromColdSegmentsInner(maxTargetHeight, verifiedHeadCheckpoint, progress);
1117
+ } catch (err) {
1118
+ if (this.coldArchiveStore?.isDaSegmentReader === true) noteColdImports(err, progress.imported);
1119
+ throw err;
1120
+ }
1121
+ }
1122
+ /**
1123
+ * The cold catch-up of a `410` (the leader pruned what the follower needs). Only a DA reader's non-fatal failure (a stall)
1124
+ * is treated as "no cold source this cycle"; any other cold reader keeps the base behaviour exactly: its error propagates.
1125
+ */
1126
+ async coldCatchUpAfterPrune(maxTargetHeight, verifiedHeadCheckpoint) {
1127
+ return catchUpAfterPrune({
1128
+ isDaReader: this.coldArchiveStore?.isDaSegmentReader === true,
1129
+ run: () => this.catchUpFromColdSegments(maxTargetHeight, verifiedHeadCheckpoint),
1130
+ onSwallowed: (err, imported) => this.resolver.logger.warn("Cold archive segment unavailable after a pruned upstream; not a cold source for this cycle", {
1131
+ chainId: this.chainId,
1132
+ imported,
1133
+ error: err instanceof Error ? err.message : String(err)
1134
+ })
1135
+ });
1136
+ }
1137
+ async catchUpFromColdSegmentsInner(maxTargetHeight, verifiedHeadCheckpoint, progress) {
1072
1138
  if (!this.coldArchiveStore) return 0;
1073
1139
  await this.hydrateDurableTrustRatchet();
1140
+ const isDaCold = this.coldArchiveStore.isDaSegmentReader === true;
1074
1141
  const verifiedColdAncestors = /* @__PURE__ */ new Map();
1075
1142
  if (verifiedHeadCheckpoint && typeof verifiedHeadCheckpoint.hash === "string" && normalizeHexDigest((0, _arcblock_ledger_core.computeCheckpointHash)(verifiedHeadCheckpoint)) === normalizeHexDigest(verifiedHeadCheckpoint.hash)) verifiedColdAncestors.set(verifiedHeadCheckpoint.height, verifiedHeadCheckpoint);
1076
1143
  let importedCount = 0;
@@ -1112,6 +1179,7 @@ var FollowerSyncService = class {
1112
1179
  checkpoint: rawSegment.checkpoint,
1113
1180
  entries: rawSegment.entries
1114
1181
  };
1182
+ if (isDaCold && verifiedHeadCheckpoint && canonicalSegment.checkpoint.height === verifiedHeadCheckpoint.height && (normalizeHexDigest(canonicalSegment.checkpoint.hash) !== normalizeHexDigest(verifiedHeadCheckpoint.hash) || normalizeHexDigest(canonicalSegment.checkpoint.stateRoot ?? "") !== normalizeHexDigest(verifiedHeadCheckpoint.stateRoot ?? ""))) throw Object.assign(new _ocap_util_lib_error.CustomError("DA_LEADER_MISMATCH", `DA segment #${nextHeight} (${canonicalSegment.checkpoint.hash}) is not the leader's signed checkpoint at that height (${verifiedHeadCheckpoint.hash})`), { daFatal: true });
1115
1183
  if ("contentHash" in rawBundle && rawBundle.contentHash !== void 0) {
1116
1184
  if (typeof rawBundle.contentHash !== "string" || rawBundle.contentHash.replace(/^0x/i, "").toLowerCase() !== (0, _arcblock_ledger_core.computeSegmentContentHash)(canonicalSegment).replace(/^0x/i, "").toLowerCase()) throw new _ocap_util_lib_error.CustomError("COLD_BUNDLE_WRAPPER_MISMATCH", `Cold segment #${nextHeight} unsigned contentHash wrapper does not match canonical segment digest`);
1117
1185
  }
@@ -1133,7 +1201,7 @@ var FollowerSyncService = class {
1133
1201
  }
1134
1202
  let stepCp = h === nextHeight ? canonicalSegment.checkpoint : verifiedColdAncestors.get(h) ?? null;
1135
1203
  if (!stepCp) {
1136
- const stepSeg = await this.coldArchiveStore.getSegment(this.chainId, h).catch(() => null);
1204
+ const stepSeg = await this.coldArchiveStore.getSegment(this.chainId, h).catch(coldLookupMiss);
1137
1205
  stepCp = stepSeg && stepSeg.chainId === this.chainId ? stepSeg.checkpoint : null;
1138
1206
  }
1139
1207
  if (!stepCp || typeof stepCp.hash !== "string" || normalizeHexDigest(stepCp.hash) !== normalizeHexDigest(expectedHash) || normalizeHexDigest((0, _arcblock_ledger_core.computeCheckpointHash)(stepCp)) !== normalizeHexDigest(expectedHash)) {
@@ -1199,7 +1267,10 @@ var FollowerSyncService = class {
1199
1267
  }
1200
1268
  throw segVerifyErr;
1201
1269
  }
1202
- for (const entry of canonicalSegment.entries) this.replayer.validateWireEntry(entry);
1270
+ for (const entry of canonicalSegment.entries) {
1271
+ this.replayer.validateWireEntry(entry);
1272
+ require_replayer.assertReplayEntryChainIdAcceptable(entry, this.chainId, "Cold segment");
1273
+ }
1203
1274
  const hadPartialLocalEntries = localSeq > canonicalSegment.checkpoint.prevSequence;
1204
1275
  let mutatedLocalDb = false;
1205
1276
  try {
@@ -1288,6 +1359,7 @@ var FollowerSyncService = class {
1288
1359
  verifiedLocalStateRoot: verifiedColdStateRoot
1289
1360
  });
1290
1361
  importedCount++;
1362
+ progress.imported = importedCount;
1291
1363
  if (importedCount >= MAX_PAGES_PER_SYNC_CYCLE) break;
1292
1364
  }
1293
1365
  if (importedCount > 0 && this.pruneController) await this.pruneController.pruneHotWindow(this.resolver.ledger);
@@ -1370,7 +1442,7 @@ var FollowerSyncService = class {
1370
1442
  publicKeyOrVerifier: coldVerifyAnchor,
1371
1443
  requireSignature: !importOpts.allowUnauthenticated,
1372
1444
  allowUnauthenticated: importOpts.allowUnauthenticated
1373
- }).catch(() => null);
1445
+ }).catch(coldLookupMiss);
1374
1446
  if (seg && seg.chainId === this.chainId) {
1375
1447
  targetCp = seg.checkpoint;
1376
1448
  const coldAuth = await this.isColdSegmentAuthenticatedByProposer(seg);
@@ -1517,7 +1589,10 @@ var FollowerSyncService = class {
1517
1589
  hotstuffClusterConfig: importOpts.hotstuffClusterConfig
1518
1590
  });
1519
1591
  if (importOpts.allowUnauthenticated && !trustAnchor) {
1520
- for (let i = 0; i < entries.length; i++) this.replayer.validateWireEntry(entries[i]);
1592
+ for (let i = 0; i < entries.length; i++) {
1593
+ this.replayer.validateWireEntry(entries[i]);
1594
+ require_replayer.assertReplayEntryChainIdAcceptable(entries[i], this.chainId, "Hot-tail");
1595
+ }
1521
1596
  return batchParsedV2From ?? parsedV2From;
1522
1597
  }
1523
1598
  if (!trustAnchor) {
@@ -1532,7 +1607,7 @@ var FollowerSyncService = class {
1532
1607
  const entry = entries[i];
1533
1608
  const expectedSeq = requestedFrom + i;
1534
1609
  if (!entry || entry.sequence !== expectedSeq) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Hot-tail batch sequence discontinuity at index ${i}: expected ${expectedSeq}, got ${entry?.sequence}`);
1535
- if (entry.chainId !== this.chainId) throw new _ocap_util_lib_error.CustomError("CHAIN_ID_MISMATCH", `Hot-tail entry chainId (${entry.chainId}) !== local chainId (${this.chainId})`);
1610
+ if (!require_replayer.isReplayEntryChainIdAcceptable(entry, this.chainId)) require_replayer.assertReplayEntryChainIdAcceptable(entry, this.chainId, "Hot-tail");
1536
1611
  if (entry.finalized !== true) throw new _ocap_util_lib_error.CustomError("UNFINALIZED_LEDGER_ENTRY", `Hot-tail entry seq=${entry.sequence} is not finalized`);
1537
1612
  if (!Number.isSafeInteger(entry.timestamp) || entry.timestamp < 0 || entry.timestamp > MAX_SAFE_EPOCH_MS) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Hot-tail entry seq=${entry.sequence} has invalid timestamp: ${String(entry.timestamp)}`);
1538
1613
  if (typeof entry.txRaw !== "string" || !entry.txRaw || entry.txRaw !== entry.txRaw.trim()) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Hot-tail entry seq=${entry.sequence} has missing or non-canonical txRaw`);
@@ -1676,7 +1751,7 @@ var FollowerSyncService = class {
1676
1751
  publicKeyOrVerifier: coldVerifyAnchor,
1677
1752
  requireSignature: !importOpts.allowUnauthenticated,
1678
1753
  allowUnauthenticated: importOpts.allowUnauthenticated
1679
- }).catch(() => null);
1754
+ }).catch(coldLookupMiss);
1680
1755
  if (seg && seg.chainId === this.chainId) targetCp = seg.checkpoint;
1681
1756
  }
1682
1757
  if (!targetCp) return markUnauthenticatedPeerError(new _ocap_util_lib_error.CustomError(cpRes && cpRes.status === 200 ? "UPSTREAM_BAD_RESPONSE" : "UPSTREAM_UNAVAILABLE", `Upstream checkpoint #${nextHeight} unavailable or failed hash-chain verification before buffered commit`));
@@ -1730,7 +1805,7 @@ var FollowerSyncService = class {
1730
1805
  for (let i = 0; i < segEntries.length; i++) {
1731
1806
  const entry = segEntries[i];
1732
1807
  const expectedSeq = targetCp.prevSequence + 1 + i;
1733
- if (entry.sequence !== expectedSeq || entry.chainId !== this.chainId || !entry.finalized) return markUnauthenticatedPeerError(new _ocap_util_lib_error.CustomError("LEDGER_DIVERGENCE", `Buffered pre-commit checkpoint #${nextHeight} invalid entry at seq=${entry.sequence}`));
1808
+ if (entry.sequence !== expectedSeq || !require_replayer.isReplayEntryChainIdAcceptable(entry, this.chainId) || !entry.finalized) return markUnauthenticatedPeerError(new _ocap_util_lib_error.CustomError("LEDGER_DIVERGENCE", `Buffered pre-commit checkpoint #${nextHeight} invalid entry at seq=${entry.sequence}`));
1734
1809
  if (!hashRun.check(entry).ok) return markUnauthenticatedPeerError(new _ocap_util_lib_error.CustomError("LEDGER_DIVERGENCE", `Buffered pre-commit checkpoint #${nextHeight} entryHash mismatch at seq=${entry.sequence}`));
1735
1810
  tree.append(entry.entryHash);
1736
1811
  }
@@ -1788,7 +1863,7 @@ var FollowerSyncService = class {
1788
1863
  const pageLimit = Math.min(MAX_HOT_TAIL_LIMIT, targetCp.sequence - cursor + 1);
1789
1864
  const entriesRes = await this.fetchAllowlistedJson(targetBaseUrl, `/api/ledger/entries?from=${cursor}&limit=${pageLimit}`, ENTRIES_MAX_RESPONSE_BYTES);
1790
1865
  if (entriesRes.status === 410 && this.coldArchiveStore) {
1791
- if (await this.catchUpFromColdSegments(nextHeight) > 0) {
1866
+ if (await this.coldCatchUpAfterPrune(nextHeight) > 0) {
1792
1867
  localCp = await this.resolver.ledger.getCheckpoint();
1793
1868
  localHeight = localCp?.height ?? 0;
1794
1869
  localSeq = await this.resolver.ledger.getLatestSequence();
@@ -1802,6 +1877,7 @@ var FollowerSyncService = class {
1802
1877
  if (item.sequence > targetCp.sequence) break;
1803
1878
  if (item.sequence !== cursor) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Non-contiguous entry sequence at height ${nextHeight}: expected ${cursor}, got ${item.sequence}`);
1804
1879
  this.replayer.validateWireEntry(item, { skipFutureTimestampCheck: true });
1880
+ require_replayer.assertReplayEntryChainIdAcceptable(item, this.chainId, "HotStuff QC segment");
1805
1881
  segmentEntries.push(item);
1806
1882
  cursor++;
1807
1883
  }
@@ -2147,8 +2223,10 @@ var FollowerSyncService = class {
2147
2223
  if (await this.catchUpFromColdSegments(upstreamStatus.latestCheckpoint?.height, verifiedHeadCp) > 0) mutatedLocalDbOnPeer = true;
2148
2224
  } catch (coldErr) {
2149
2225
  if (isFatalVerificationFailure(coldErr) || coldErr?.mutatedLocalDbTransientLock === true) throw coldErr;
2226
+ if (coldImportsBefore(coldErr) > 0) mutatedLocalDbOnPeer = true;
2150
2227
  this.resolver.logger.warn("Cold archive segment unavailable or unverified; falling back to hot-tail sync", {
2151
2228
  chainId: this.chainId,
2229
+ ...this.coldArchiveStore?.isDaSegmentReader === true ? { imported: coldImportsBefore(coldErr) } : {},
2152
2230
  error: coldErr instanceof Error ? coldErr.message : String(coldErr)
2153
2231
  });
2154
2232
  }
@@ -2221,7 +2299,7 @@ var FollowerSyncService = class {
2221
2299
  const entriesRes = await this.fetchAllowlistedJson(targetBaseUrl, `/api/ledger/entries?from=${from}&limit=${MAX_HOT_TAIL_LIMIT}`, ENTRIES_MAX_RESPONSE_BYTES);
2222
2300
  if (entriesRes.status === 410) {
2223
2301
  if (this.coldArchiveStore && bufferedTailBatches.length === 0) {
2224
- const imported = await this.catchUpFromColdSegments(upstreamStatus.latestCheckpoint?.height, verifiedHeadCp);
2302
+ const imported = await this.coldCatchUpAfterPrune(upstreamStatus.latestCheckpoint?.height, verifiedHeadCp);
2225
2303
  localSeq = await this.resolver.ledger.getLatestSequence();
2226
2304
  cursorSeq = localSeq;
2227
2305
  if (imported > 0) mutatedLocalDbOnPeer = true;
@@ -2461,4 +2539,8 @@ exports.DEFAULT_FOLLOWER_MAX_SYNC_LAG = DEFAULT_FOLLOWER_MAX_SYNC_LAG;
2461
2539
  exports.DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS = DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS;
2462
2540
  exports.DEFAULT_FOLLOWER_POLL_INTERVAL_MS = DEFAULT_FOLLOWER_POLL_INTERVAL_MS;
2463
2541
  exports.FollowerSyncService = FollowerSyncService;
2464
- exports.isTransientSqliteLockError = isTransientSqliteLockError;
2542
+ exports.catchUpAfterPrune = catchUpAfterPrune;
2543
+ exports.coldImportsBefore = coldImportsBefore;
2544
+ exports.coldLookupMiss = coldLookupMiss;
2545
+ exports.isTransientSqliteLockError = isTransientSqliteLockError;
2546
+ exports.noteColdImports = noteColdImports;
@@ -101,6 +101,24 @@ interface FollowerSyncServiceOptions {
101
101
  };
102
102
  }
103
103
  declare function isTransientSqliteLockError(err: unknown): boolean;
104
+ /** The cold catch-up after a `410`: see `FollowerSyncService.coldCatchUpAfterPrune` (a pure function so it can be tested). */
105
+ declare function catchUpAfterPrune(options: {
106
+ isDaReader: boolean;
107
+ run: () => Promise<number>;
108
+ onSwallowed: (err: unknown, imported: number) => void;
109
+ }): Promise<number>;
110
+ /**
111
+ * A cold catch-up that fails after it already imported segments (a DA stall or a transient error at segment N+k) has
112
+ * changed the local database: the error carries how many it imported, so the callers do not treat the cycle as untouched.
113
+ */
114
+ declare function noteColdImports(err: unknown, imported: number): void;
115
+ /** How many segments a failed cold catch-up had imported before it failed (0 when it imported none or is not annotated). */
116
+ declare function coldImportsBefore(err: unknown): number;
117
+ /**
118
+ * `.catch()` handler for a best-effort cold segment lookup (to find a checkpoint, not to import): a miss or a transient
119
+ * error is "not found here", but a fatal DA reader error (`daFatal`, #2017) is never swallowed: it halts the follower.
120
+ */
121
+ declare function coldLookupMiss(err: unknown): null;
104
122
  declare class FollowerSyncService implements INodeRuntimeAdapter {
105
123
  readonly role: TNodeRole;
106
124
  writePolicy: TNodeWritePolicy;
@@ -170,6 +188,10 @@ declare class FollowerSyncService implements INodeRuntimeAdapter {
170
188
  getRuntimeDiagnostics(options?: {
171
189
  includePrivateTopology?: boolean;
172
190
  }): Record<string, unknown>;
191
+ /** The DA reader's status for `/api/health/ledger` (`daArchive`), or null for any other cold reader (#2017). */
192
+ getDaArchiveStatus(): Record<string, unknown> | null;
193
+ /** DA follower only (#2017): `daArchive: { state: 'ok' | 'stalled', ... }`; nothing is added for any other cold reader. */
194
+ private daArchiveDiagnostics;
173
195
  triggerSyncOrProbe(): Promise<Record<string, unknown>>;
174
196
  private haltFailClosed;
175
197
  private resolveActiveUpstreamUrl;
@@ -242,6 +264,12 @@ declare class FollowerSyncService implements INodeRuntimeAdapter {
242
264
  * Stage 1B: Catch up sealed `.zst` checkpoint segments from `coldArchiveStore` when available.
243
265
  */
244
266
  private catchUpFromColdSegments;
267
+ /**
268
+ * The cold catch-up of a `410` (the leader pruned what the follower needs). Only a DA reader's non-fatal failure (a stall)
269
+ * is treated as "no cold source this cycle"; any other cold reader keeps the base behaviour exactly: its error propagates.
270
+ */
271
+ private coldCatchUpAfterPrune;
272
+ private catchUpFromColdSegmentsInner;
245
273
  private sealCaughtUpCheckpoints;
246
274
  private tryEmitHotTailReplayFraudAlert;
247
275
  private parseStrictEntryHashV2From;
@@ -291,4 +319,4 @@ declare class FollowerSyncService implements INodeRuntimeAdapter {
291
319
  close(): Promise<void>;
292
320
  }
293
321
  //#endregion
294
- export { DEFAULT_FOLLOWER_HTTP_TIMEOUT_MS, DEFAULT_FOLLOWER_MAX_SYNC_LAG, DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS, DEFAULT_FOLLOWER_POLL_INTERVAL_MS, FollowerSyncService, FollowerSyncServiceOptions, IColdSegmentReader, ILeaderRouterLike, TFollowerUpstreamFetchInterceptor, TFollowerUpstreamFetchKind, isTransientSqliteLockError };
322
+ export { DEFAULT_FOLLOWER_HTTP_TIMEOUT_MS, DEFAULT_FOLLOWER_MAX_SYNC_LAG, DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS, DEFAULT_FOLLOWER_POLL_INTERVAL_MS, FollowerSyncService, FollowerSyncServiceOptions, IColdSegmentReader, ILeaderRouterLike, TFollowerUpstreamFetchInterceptor, TFollowerUpstreamFetchKind, catchUpAfterPrune, coldImportsBefore, coldLookupMiss, isTransientSqliteLockError, noteColdImports };
package/lib/replayer.cjs CHANGED
@@ -27,6 +27,22 @@ lodash_merge = require_rolldown_runtime.__toESM(lodash_merge);
27
27
  * - Enforces pre-commit `expectedCommitHash` on `statedb.runAsLambda` so any state divergence rolls back
28
28
  * SQLite atomically BEFORE `COMMIT` and before appending to `ledger.sqlite`.
29
29
  */
30
+ /**
31
+ * Cross-layer chainId rule for executable replay (#2029, #2039):
32
+ * Own-chain entries (`entry.chainId === expectedChainId`) are accepted directly; a self-declared foreign-`chainId`
33
+ * wire entry (`isEntryChainIdAcceptable(entry, expectedChainId)`) can ONLY execute as a force-finalized orphan
34
+ * (`(entry.stateCommitHash ?? '').trim() === ''`), because `VerifyTx` rejects `chainId !== config.chainId` before
35
+ * `PrepareState`/`CommitState` so a foreign-`chainId` entry can never commit state.
36
+ */
37
+ function isReplayEntryChainIdAcceptable(entry, expectedChainId) {
38
+ if (entry.chainId === expectedChainId) return true;
39
+ return (0, _arcblock_ledger_core.isEntryChainIdAcceptable)(entry, expectedChainId) && (entry.stateCommitHash ?? "").trim() === "";
40
+ }
41
+ function assertReplayEntryChainIdAcceptable(entry, expectedChainId, prefix = "Ledger entry") {
42
+ if (isReplayEntryChainIdAcceptable(entry, expectedChainId)) return;
43
+ if (entry.chainId !== expectedChainId && typeof entry.txRaw === "string" && (0, _arcblock_ledger_core.isEntryChainIdAcceptable)(entry, expectedChainId) && (entry.stateCommitHash ?? "").trim() !== "") throw new _ocap_util_lib_error.CustomError("CHAIN_ID_MISMATCH", `${prefix} foreign-chainId entry at seq=${String(entry.sequence)} (chainId=${String(entry.chainId)}, local=${expectedChainId}) cannot carry a stateCommitHash`);
44
+ throw new _ocap_util_lib_error.CustomError("CHAIN_ID_MISMATCH", `${prefix} chainId mismatch at seq=${String(entry.sequence)}: expected ${expectedChainId}, got ${String(entry.chainId)}`);
45
+ }
30
46
  /** Error code of a replayed entry refused for a timestamp ahead of the local clock (retryable, never halting). */
31
47
  const FUTURE_LEDGER_ENTRY_TIMESTAMP = "FUTURE_LEDGER_ENTRY_TIMESTAMP";
32
48
  function normalizeHexLower(raw) {
@@ -187,6 +203,7 @@ var LedgerEntryReplayer = class {
187
203
  if (!entry || typeof entry !== "object" || !Number.isSafeInteger(entry.sequence) || entry.sequence < 1 || !Number.isSafeInteger(entry.nonce) || entry.nonce < 0 || !Number.isSafeInteger(entry.timestamp) || entry.timestamp < 0 || entry.timestamp > 864e13 || typeof entry.hash !== "string" || typeof entry.from !== "string" || typeof entry.pk !== "string" || typeof entry.signature !== "string" || typeof entry.txRaw !== "string" || typeof entry.txType !== "string" || typeof entry.chainId !== "string" || typeof entry.entryHash !== "string" || typeof entry.finalized !== "boolean" || entry.stateCommitHash !== void 0 && typeof entry.stateCommitHash !== "string" || entry.tx === null || typeof entry.tx !== "object" || Array.isArray(entry.tx)) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Ledger entry seq=${String(entry?.sequence)} has invalid wire primitive types`);
188
204
  this.verifyRawTxHashMatchesEntry(entry, "INVALID_LEDGER_ENTRY");
189
205
  this.authenticateAndDecodeEntry(entry);
206
+ if (!(entry.stateCommitHash ?? "").trim()) this.decodeOrphanEntryContext(entry);
190
207
  if (!options.skipFutureTimestampCheck) this.assertEntryTimestampNotInFuture(entry);
191
208
  }
192
209
  authenticateAndDecodeEntry(entry) {
@@ -195,31 +212,44 @@ var LedgerEntryReplayer = class {
195
212
  return authRes.decodedTx;
196
213
  }
197
214
  /**
198
- * Index a rejected-but-ledgered entry (finalized, no stateCommitHash) with the row the leader wrote for it: the
199
- * leader's `sendTx` passes the context of its `DecodeTx` + `DecodeItx` pipes to `_indexRejectedLedgerTx`, so the
200
- * follower builds that context from the entry's txRaw with the same pipes and the time pinned to the entry
201
- * (#1875). Only the rejection code differs: it is not in the ledger, so the row says `ORPHAN_LEDGER_ENTRY`.
215
+ * Synchronously run `pipes.DecodeTx` + `pipes.DecodeItx` on a force-finalized orphan entry (`stateCommitHash === ''`)
216
+ * so any wire byte ceiling, non-canonical `signatures[].data` JSON, undecodable nested Any, or missing `itx` is
217
+ * caught as a peer-disqualifying `INVALID_LEDGER_ENTRY` BEFORE `importSegment` / `appendVerifiedEntryToLedger`
218
+ * mutates `ledger.sqlite` (#2039).
202
219
  */
203
- async indexOrphanEntry(entry) {
220
+ decodeOrphanEntryContext(entry) {
204
221
  const ctx = {
205
222
  txBase64: entry.txRaw,
206
223
  config: this.resolver.config,
207
224
  extra: { txTime: entry.timestamp }
208
225
  };
209
- const runPipe = (pipe) => new Promise((resolve, reject) => {
210
- try {
211
- pipe(ctx, (err) => err ? reject(err) : resolve());
212
- } catch (err) {
213
- reject(err);
214
- }
215
- });
226
+ const runPipeSync = (pipe) => {
227
+ let pipeErr;
228
+ let completed = false;
229
+ pipe(ctx, (err) => {
230
+ completed = true;
231
+ pipeErr = err;
232
+ });
233
+ if (!completed) throw new Error("Orphan decode pipe did not complete synchronously");
234
+ if (pipeErr) throw pipeErr;
235
+ };
216
236
  try {
217
- await runPipe(_ocap_tx_pipeline.pipes.DecodeTx);
218
- await runPipe(_ocap_tx_pipeline.pipes.DecodeItx);
237
+ runPipeSync(_ocap_tx_pipeline.pipes.DecodeTx);
238
+ runPipeSync(_ocap_tx_pipeline.pipes.DecodeItx);
219
239
  } catch (err) {
220
240
  throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Orphan ledger entry seq=${entry.sequence} hash=${entry.hash} does not decode as the leader decodes it: ${err instanceof Error ? err.message : String(err)}`);
221
241
  }
222
- if (String(ctx.txHash ?? "").toUpperCase() !== String(entry.hash).toUpperCase()) throw new _ocap_util_lib_error.CustomError("TX_HASH_MISMATCH", `Orphan ledger entry seq=${entry.sequence} hash=${entry.hash}: txRaw does not hash to its entry hash`);
242
+ if (String(ctx.txHash ?? "").toUpperCase() !== String(entry.hash).toUpperCase()) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Orphan ledger entry seq=${entry.sequence} hash=${entry.hash}: txRaw does not hash to its entry hash`);
243
+ return ctx;
244
+ }
245
+ /**
246
+ * Index a rejected-but-ledgered entry (finalized, no stateCommitHash) with the row the leader wrote for it: the
247
+ * leader's `sendTx` passes the context of its `DecodeTx` + `DecodeItx` pipes to `_indexRejectedLedgerTx`, so the
248
+ * follower builds that context from the entry's txRaw with the same pipes and the time pinned to the entry
249
+ * (#1875). Only the rejection code differs: it is not in the ledger, so the row says `ORPHAN_LEDGER_ENTRY`.
250
+ */
251
+ async indexOrphanEntry(entry, preDecodedCtx) {
252
+ const ctx = preDecodedCtx ?? this.decodeOrphanEntryContext(entry);
223
253
  const leaderCtx = (0, lodash_merge.default)((0, lodash_cloneDeep.default)(ctx), ctx);
224
254
  leaderCtx.ledgerSequence = entry.sequence;
225
255
  await this.resolver._indexRejectedLedgerTx(leaderCtx, { code: "ORPHAN_LEDGER_ENTRY" });
@@ -233,8 +263,7 @@ var LedgerEntryReplayer = class {
233
263
  if (!entry || typeof entry !== "object") throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", "Cannot replay null or non-object ledger entry");
234
264
  if (!entry.finalized) throw new _ocap_util_lib_error.CustomError("UNFINALIZED_LEDGER_ENTRY", `Refusing to replay unfinalized entry seq=${entry.sequence}`);
235
265
  if (!Number.isSafeInteger(entry.timestamp) || entry.timestamp < 0 || entry.timestamp > 864e13) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Refusing to replay entry seq=${entry.sequence} with out-of-range timestamp: ${String(entry.timestamp)}`);
236
- const expectedChainId = this.resolver.config.chainId || this.resolver.ledger.chainId;
237
- if (entry.chainId !== expectedChainId) throw new _ocap_util_lib_error.CustomError("CHAIN_ID_MISMATCH", `Ledger entry chainId mismatch at seq=${entry.sequence}: expected ${expectedChainId}, got ${entry.chainId}`);
266
+ assertReplayEntryChainIdAcceptable(entry, this.resolver.config.chainId || this.resolver.ledger.chainId, "Ledger entry");
238
267
  const appendToLedger = options.appendToLedger !== false;
239
268
  if (options.entryHashV2From !== void 0 && options.entryHashV2From !== "infinity" && (!Number.isSafeInteger(options.entryHashV2From) || options.entryHashV2From < 1)) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Invalid entryHashV2From replay option: ${String(options.entryHashV2From)}`);
240
269
  if (!Number.isSafeInteger(entry.sequence) || entry.sequence < 1 || !Number.isSafeInteger(entry.nonce) || entry.nonce < 0 || typeof entry.entryHash !== "string" || !entry.entryHash || entry.stateCommitHash !== void 0 && typeof entry.stateCommitHash !== "string") throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Ledger entry seq=${String(entry.sequence)} has invalid sequence, nonce, or entryHash types`);
@@ -263,8 +292,9 @@ var LedgerEntryReplayer = class {
263
292
  if (entry.entryHash !== expectedEntryHash) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Ledger entryHash mismatch before execution at seq=${entry.sequence}: expected ${expectedEntryHash}, got ${entry.entryHash}`);
264
293
  }
265
294
  if (!expectedStateCommit) {
295
+ const decodedOrphanCtx = this.decodeOrphanEntryContext(entry);
266
296
  if (appendToLedger) await this.appendVerifiedEntryToLedger(entry, options.entryHashV2From);
267
- await this.indexOrphanEntry(entry);
297
+ await this.indexOrphanEntry(entry, decodedOrphanCtx);
268
298
  return {
269
299
  status: "orphan-indexed",
270
300
  sequence: entry.sequence,
@@ -343,7 +373,7 @@ var LedgerEntryReplayer = class {
343
373
  const entry = entries[i];
344
374
  if (!entry || typeof entry !== "object") throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Proposal entry at index ${i} is not an object`);
345
375
  if (entry.finalized !== true) throw new _ocap_util_lib_error.CustomError("UNFINALIZED_LEDGER_ENTRY", `Proposal entry seq=${String(entry.sequence)} must be finalized`);
346
- if (entry.chainId !== expectedChainId) throw new _ocap_util_lib_error.CustomError("CHAIN_ID_MISMATCH", `Proposal entry chainId mismatch at seq=${String(entry.sequence)}: expected ${expectedChainId}, got ${entry.chainId}`);
376
+ assertReplayEntryChainIdAcceptable(entry, expectedChainId, "Proposal entry");
347
377
  if (entry.sequence !== baseSeq + i + 1) throw new _ocap_util_lib_error.CustomError("SEQUENCE_GAP", `Proposal entry sequence mismatch at index ${i}: expected ${baseSeq + i + 1}, got ${entry.sequence}`);
348
378
  this.validateWireEntry(entry, { skipFutureTimestampCheck: options.skipFutureTimestampCheck });
349
379
  const expectedStateCommit = (entry.stateCommitHash ?? "").trim();
@@ -463,4 +493,6 @@ var LedgerEntryReplayer = class {
463
493
 
464
494
  //#endregion
465
495
  exports.FUTURE_LEDGER_ENTRY_TIMESTAMP = FUTURE_LEDGER_ENTRY_TIMESTAMP;
466
- exports.LedgerEntryReplayer = LedgerEntryReplayer;
496
+ exports.LedgerEntryReplayer = LedgerEntryReplayer;
497
+ exports.assertReplayEntryChainIdAcceptable = assertReplayEntryChainIdAcceptable;
498
+ exports.isReplayEntryChainIdAcceptable = isReplayEntryChainIdAcceptable;
@@ -31,6 +31,24 @@ interface IDryRunVerifyEntriesOptions {
31
31
  /** Entries come from the local ledger (crash reconciliation), not from a peer: skip the future-timestamp guard. */
32
32
  skipFutureTimestampCheck?: boolean;
33
33
  }
34
+ /**
35
+ * Cross-layer chainId rule for executable replay (#2029, #2039):
36
+ * Own-chain entries (`entry.chainId === expectedChainId`) are accepted directly; a self-declared foreign-`chainId`
37
+ * wire entry (`isEntryChainIdAcceptable(entry, expectedChainId)`) can ONLY execute as a force-finalized orphan
38
+ * (`(entry.stateCommitHash ?? '').trim() === ''`), because `VerifyTx` rejects `chainId !== config.chainId` before
39
+ * `PrepareState`/`CommitState` so a foreign-`chainId` entry can never commit state.
40
+ */
41
+ declare function isReplayEntryChainIdAcceptable(entry: {
42
+ chainId?: string | null;
43
+ txRaw: string;
44
+ stateCommitHash?: string | null;
45
+ }, expectedChainId: string): boolean;
46
+ declare function assertReplayEntryChainIdAcceptable(entry: {
47
+ sequence?: unknown;
48
+ chainId?: string | null;
49
+ txRaw: string;
50
+ stateCommitHash?: string | null;
51
+ }, expectedChainId: string, prefix?: string): void;
34
52
  interface IValidateWireEntryOptions {
35
53
  /** Entries come from the local ledger (crash reconciliation), not from a peer: skip the future-timestamp guard. */
36
54
  skipFutureTimestampCheck?: boolean;
@@ -93,6 +111,13 @@ declare class LedgerEntryReplayer {
93
111
  */
94
112
  validateWireEntry(entry: ILedgerEntry, options?: IValidateWireEntryOptions): void;
95
113
  private authenticateAndDecodeEntry;
114
+ /**
115
+ * Synchronously run `pipes.DecodeTx` + `pipes.DecodeItx` on a force-finalized orphan entry (`stateCommitHash === ''`)
116
+ * so any wire byte ceiling, non-canonical `signatures[].data` JSON, undecodable nested Any, or missing `itx` is
117
+ * caught as a peer-disqualifying `INVALID_LEDGER_ENTRY` BEFORE `importSegment` / `appendVerifiedEntryToLedger`
118
+ * mutates `ledger.sqlite` (#2039).
119
+ */
120
+ private decodeOrphanEntryContext;
96
121
  /**
97
122
  * Index a rejected-but-ledgered entry (finalized, no stateCommitHash) with the row the leader wrote for it: the
98
123
  * leader's `sendTx` passes the context of its `DecodeTx` + `DecodeItx` pipes to `_indexRejectedLedgerTx`, so the
@@ -123,4 +148,4 @@ declare class LedgerEntryReplayer {
123
148
  indexExistingOrphanEntries(fromSeq?: number, toSeq?: number): Promise<number>;
124
149
  }
125
150
  //#endregion
126
- export { FUTURE_LEDGER_ENTRY_TIMESTAMP, IDryRunVerifyEntriesOptions, IDryRunVerifyEntriesResult, IFutureTimestampGuardOptions, IFutureTimestampRejection, ILedgerEntryReplayerOptions, IReplayEntryOptions, IReplayEntryResult, IReplayerResolverTarget, IValidateWireEntryOptions, LedgerEntryReplayer };
151
+ export { FUTURE_LEDGER_ENTRY_TIMESTAMP, IDryRunVerifyEntriesOptions, IDryRunVerifyEntriesResult, IFutureTimestampGuardOptions, IFutureTimestampRejection, ILedgerEntryReplayerOptions, IReplayEntryOptions, IReplayEntryResult, IReplayerResolverTarget, IValidateWireEntryOptions, LedgerEntryReplayer, assertReplayEntryChainIdAcceptable, isReplayEntryChainIdAcceptable };
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.32.2",
6
+ "version": "1.32.3",
7
7
  "description": "GraphQL resolver built upon ocap statedb and GQL layer",
8
8
  "type": "module",
9
9
  "main": "./lib/index.cjs",
@@ -54,22 +54,22 @@
54
54
  "tsdown": "^0.18.4"
55
55
  },
56
56
  "dependencies": {
57
- "@arcblock/did": "1.32.2",
58
- "@arcblock/did-ext": "1.32.2",
59
- "@arcblock/did-util": "1.32.2",
60
- "@arcblock/ledger-core": "1.32.2",
57
+ "@arcblock/did": "1.32.3",
58
+ "@arcblock/did-ext": "1.32.3",
59
+ "@arcblock/did-util": "1.32.3",
60
+ "@arcblock/ledger-core": "1.32.3",
61
61
  "@arcblock/nft-display": "^3.2.3",
62
- "@arcblock/validator": "1.32.2",
63
- "@ocap/config": "1.32.2",
64
- "@ocap/indexdb": "1.32.2",
65
- "@ocap/mcrypto": "1.32.2",
66
- "@ocap/message": "1.32.2",
67
- "@ocap/state": "1.32.2",
68
- "@ocap/tx-pipeline": "1.32.2",
69
- "@ocap/tx-protocols": "1.32.2",
70
- "@ocap/types": "1.32.2",
71
- "@ocap/util": "1.32.2",
72
- "@ocap/wallet": "1.32.2",
62
+ "@arcblock/validator": "1.32.3",
63
+ "@ocap/config": "1.32.3",
64
+ "@ocap/indexdb": "1.32.3",
65
+ "@ocap/mcrypto": "1.32.3",
66
+ "@ocap/message": "1.32.3",
67
+ "@ocap/state": "1.32.3",
68
+ "@ocap/tx-pipeline": "1.32.3",
69
+ "@ocap/tx-protocols": "1.32.3",
70
+ "@ocap/types": "1.32.3",
71
+ "@ocap/util": "1.32.3",
72
+ "@ocap/wallet": "1.32.3",
73
73
  "debug": "^4.4.3",
74
74
  "express": "^4.22.1",
75
75
  "lodash": "^4.17.23",