@ocap/resolver 1.31.9 → 1.32.1

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.
Files changed (42) hide show
  1. package/esm/_virtual/rolldown_runtime.mjs +7 -0
  2. package/esm/api.d.mts +33 -5
  3. package/esm/api.mjs +939 -53
  4. package/esm/dashboard.d.mts +199 -0
  5. package/esm/dashboard.mjs +2481 -0
  6. package/esm/explorer.d.mts +29 -0
  7. package/esm/explorer.mjs +227 -0
  8. package/esm/follower.d.mts +294 -0
  9. package/esm/follower.mjs +2452 -0
  10. package/esm/hooks.mjs +1 -1
  11. package/esm/hotstuff-runtime.d.mts +271 -0
  12. package/esm/hotstuff-runtime.mjs +2668 -0
  13. package/esm/index.d.mts +79 -4
  14. package/esm/index.mjs +911 -174
  15. package/esm/node-preferences.d.mts +203 -0
  16. package/esm/node-preferences.mjs +1021 -0
  17. package/esm/replayer.d.mts +114 -0
  18. package/esm/replayer.mjs +430 -0
  19. package/esm/token-distribution.mjs +2 -2
  20. package/esm/token-flow.mjs +1 -1
  21. package/esm/types.d.mts +25 -2
  22. package/lib/api.cjs +941 -52
  23. package/lib/api.d.cts +33 -5
  24. package/lib/dashboard.cjs +2491 -0
  25. package/lib/dashboard.d.cts +199 -0
  26. package/lib/explorer.cjs +227 -0
  27. package/lib/explorer.d.cts +29 -0
  28. package/lib/follower.cjs +2458 -0
  29. package/lib/follower.d.cts +294 -0
  30. package/lib/hooks.cjs +1 -1
  31. package/lib/hotstuff-runtime.cjs +2671 -0
  32. package/lib/hotstuff-runtime.d.cts +271 -0
  33. package/lib/index.cjs +946 -174
  34. package/lib/index.d.cts +79 -4
  35. package/lib/node-preferences.cjs +1043 -0
  36. package/lib/node-preferences.d.cts +203 -0
  37. package/lib/replayer.cjs +432 -0
  38. package/lib/replayer.d.cts +114 -0
  39. package/lib/token-distribution.cjs +2 -2
  40. package/lib/token-flow.cjs +1 -1
  41. package/lib/types.d.cts +25 -2
  42. package/package.json +20 -14
@@ -0,0 +1,203 @@
1
+ import { TNodeRole, TNodeWritePolicy } from "@ocap/types";
2
+ import { Request, RequestHandler, Response } from "express";
3
+
4
+ //#region src/node-preferences.d.ts
5
+
6
+ declare const MAX_BLOCKED_ACCOUNTS = 5000;
7
+ declare const MAX_TRUSTED_ACCOUNTS = 1000;
8
+ declare const MAX_RESERVED_SYMBOLS = 500;
9
+ declare const MAX_PEER_URLS = 32;
10
+ declare const MAX_MEMO_LENGTH = 256;
11
+ declare const MAX_CONFIG_BODY_BYTES: number;
12
+ type TPreferenceSource = 'env' | 'static' | 'preferences';
13
+ interface IBlockedAccountEntry {
14
+ address: string;
15
+ memo?: string;
16
+ }
17
+ interface ITrustedAccountEntry {
18
+ address: string;
19
+ tolerance?: number;
20
+ memo?: string;
21
+ }
22
+ interface IReservedSymbolEntry {
23
+ symbol: string;
24
+ memo?: string;
25
+ }
26
+ interface ILedgerHealthThresholds {
27
+ checkpointLag: number;
28
+ checkpointAgeMs: number;
29
+ unfinalizedAgeMs: number;
30
+ }
31
+ interface INodeRuntimePreferences {
32
+ writePolicy?: TNodeWritePolicy;
33
+ txMaxRequest?: number;
34
+ pollIntervalMs?: number;
35
+ maxSyncLag?: number;
36
+ peerUrls?: string[];
37
+ healthThresholds?: Partial<ILedgerHealthThresholds>;
38
+ }
39
+ interface INodePreferencesFileSchema {
40
+ version?: number;
41
+ updatedAt?: string;
42
+ blockedAccounts?: Array<string | IBlockedAccountEntry>;
43
+ trustedAccounts?: Array<string | ITrustedAccountEntry>;
44
+ reservedSymbols?: Array<string | IReservedSymbolEntry>;
45
+ runtime?: INodeRuntimePreferences;
46
+ }
47
+ interface IAttributedBlockedAccount extends IBlockedAccountEntry {
48
+ source: TPreferenceSource;
49
+ mutable: boolean;
50
+ }
51
+ interface IAttributedTrustedAccount extends ITrustedAccountEntry {
52
+ source: TPreferenceSource;
53
+ mutable: boolean;
54
+ }
55
+ interface IAttributedReservedSymbol extends IReservedSymbolEntry {
56
+ source: TPreferenceSource;
57
+ mutable: boolean;
58
+ }
59
+ interface INodePreferencesSnapshot {
60
+ preferencesPath: string | null;
61
+ updatedAt: string | null;
62
+ blockedAccounts: IAttributedBlockedAccount[];
63
+ trustedAccounts: IAttributedTrustedAccount[];
64
+ reservedSymbols: IAttributedReservedSymbol[];
65
+ runtime: INodeRuntimePreferences;
66
+ }
67
+ interface ILegacyPreferencesResult {
68
+ reservedSymbols: IReservedSymbolEntry[];
69
+ trustedAccounts: ITrustedAccountEntry[];
70
+ blockedAccounts: IBlockedAccountEntry[];
71
+ }
72
+ declare class NodePreferencesError extends Error {
73
+ readonly code: string;
74
+ readonly status: number;
75
+ constructor(code: string, message: string, status?: number);
76
+ }
77
+ /**
78
+ * Constant-time token comparison over fixed-width SHA-256 digests so secret length is never leaked.
79
+ */
80
+ declare function timingSafeTokenEqual(expected: unknown, provided: unknown): boolean;
81
+ /**
82
+ * Normalize DID / 0x / did:name address keys identically to HTTP `/blocked` lookup.
83
+ */
84
+ declare function normalizeBlockedAccountKey(raw: unknown): string;
85
+ declare function isValidAccountAddressCandidate(raw: unknown): raw is string;
86
+ declare function isPrivateOrReservedIpAddress(rawIp: string): boolean;
87
+ type DnsLookupAllFn = (hostname: string) => Promise<Array<{
88
+ address: string;
89
+ family: number;
90
+ }>>;
91
+ /**
92
+ * Validate Follower `peerUrls` for strict HTTP(S) base URL hygiene and SSRF / DNS-rebinding safety.
93
+ */
94
+ declare function validateFollowerPeerUrls(rawUrls: unknown, env?: Record<string, string | undefined>, dnsLookup?: DnsLookupAllFn): Promise<string[]>;
95
+ /**
96
+ * Connect-time SSRF & DNS-rebinding guard for Follower / LeaderRouter outbound `fetch()` calls.
97
+ * Static operator-configured origins (`UPSTREAM_CHAIN_URL` / `CLUSTER_PEER_URLS` / `HOTSTUFF_VALIDATORS` from boot env)
98
+ * are explicitly allowlisted; any dynamically configured `peerUrl` is re-verified on every request (defeating `TTL=0`
99
+ * DNS rebinding) and, for `http:` DNS hosts, connected directly to the verified public IP with an explicit `Host` header
100
+ * so no second DNS resolution occurs.
101
+ */
102
+ declare function createFollowerPeerFetchGuard(options: {
103
+ env?: Record<string, string | undefined>;
104
+ dnsLookup?: DnsLookupAllFn;
105
+ trustedStaticUrls?: Array<string | undefined | null>;
106
+ baseFetch?: typeof fetch;
107
+ }): typeof fetch;
108
+ /**
109
+ * Safely apply persisted `preferences.json` runtime overrides at node startup without crashing
110
+ * when `updateRuntimeConfig` is synchronous (`void`), while filtering role-inapplicable keys
111
+ * and validating Follower `peerUrls` against SSRF / DNS-rebinding rules.
112
+ */
113
+ declare function applyBootRuntimePreferences(params: {
114
+ runtime?: {
115
+ role?: TNodeRole;
116
+ updateRuntimeConfig?: (patch: INodeRuntimePreferences) => Promise<void> | void;
117
+ } | null;
118
+ preferencesManager: NodePreferencesManager;
119
+ env?: Record<string, string | undefined>;
120
+ dnsLookup?: DnsLookupAllFn;
121
+ logger?: {
122
+ warn?: (...args: unknown[]) => void;
123
+ };
124
+ }): Promise<void>;
125
+ /**
126
+ * Backward-compatible helper used by standalone chain startup (`loadPreferences(dataDir?)`).
127
+ * Unions immutable `CHAIN_*` env baseline with `<dataDir>/preferences.json` (when `dataDir` is passed)
128
+ * or `CHAIN_PREFERENCES_PATH` so an empty `preferences.json` array never wipes out env rules.
129
+ */
130
+ declare function loadNodePreferences(dataDir?: string, env?: Record<string, string | undefined>): ILegacyPreferencesResult;
131
+ interface NodePreferencesManagerOptions {
132
+ dataDir?: string;
133
+ preferencesPath?: string;
134
+ env?: Record<string, string | undefined>;
135
+ staticBlockedAddresses?: string[];
136
+ baseReservedSymbols?: string[];
137
+ getNodeRole?: () => TNodeRole;
138
+ getConsensusMode?: () => 'single' | 'hotstuff';
139
+ dnsLookup?: DnsLookupAllFn;
140
+ onApply?: (snapshot: INodePreferencesSnapshot, meta: {
141
+ changedRuntimeKeys: string[];
142
+ requiresRestart: boolean;
143
+ }) => Promise<void> | void;
144
+ }
145
+ interface IUpdateNodePreferencesInput {
146
+ blockedAccounts?: Array<string | IBlockedAccountEntry>;
147
+ trustedAccounts?: Array<string | ITrustedAccountEntry>;
148
+ reservedSymbols?: Array<string | IReservedSymbolEntry>;
149
+ runtime?: INodeRuntimePreferences;
150
+ }
151
+ interface IUpdateNodePreferencesResult {
152
+ snapshot: INodePreferencesSnapshot;
153
+ requiresRestart: boolean;
154
+ changedRuntimeKeys: string[];
155
+ }
156
+ declare class NodePreferencesManager {
157
+ private readonly env;
158
+ private readonly preferencesPath;
159
+ private readonly staticBlockedAddresses;
160
+ private readonly baseReservedSymbols;
161
+ private readonly getNodeRoleFn;
162
+ private readonly getConsensusModeFn;
163
+ private readonly dnsLookup;
164
+ private onApplyFn?;
165
+ private fileState;
166
+ private snapshotCache;
167
+ private normalizedBlockedKeySet;
168
+ private normalizedReservedSymbolSet;
169
+ private writeChain;
170
+ constructor(options?: NodePreferencesManagerOptions);
171
+ setOnApply(fn: NodePreferencesManagerOptions['onApply']): void;
172
+ getPreferencesPath(): string | null;
173
+ reloadFromDiskSync(): INodePreferencesSnapshot;
174
+ reload(): Promise<INodePreferencesSnapshot>;
175
+ getSnapshot(): INodePreferencesSnapshot;
176
+ getBlockedAddresses(): string[];
177
+ getTrustedAccounts(): ITrustedAccountEntry[];
178
+ getEffectiveHealthThresholds(): ILedgerHealthThresholds;
179
+ isBlocked(address: string): boolean;
180
+ isReservedSymbol(symbol: string): boolean;
181
+ update(input: IUpdateNodePreferencesInput): Promise<IUpdateNodePreferencesResult>;
182
+ private atomicWritePreferencesFile;
183
+ private rebuildEffectiveSnapshot;
184
+ }
185
+ interface AdminAuthGuardOptions {
186
+ env?: Record<string, string | undefined>;
187
+ windowMs?: number;
188
+ maxFailedAttemptsPerIp?: number;
189
+ maxTrackedIps?: number;
190
+ }
191
+ interface IAdminAuthGuard {
192
+ isConfigured: () => boolean;
193
+ isAuthenticatedRequest: (req: Request) => boolean;
194
+ checkOptionalAdmin?: (req: Request, res: Response) => 'admin' | 'anonymous' | 'rate_limited';
195
+ requireAdmin: RequestHandler;
196
+ }
197
+ /**
198
+ * Constant-time SHA-256 admin auth guard with bounded per-IP failed-attempt rate limiting
199
+ * and CSRF Content-Type / custom-header enforcement on state-mutating methods.
200
+ */
201
+ declare function createAdminAuthGuard(options?: AdminAuthGuardOptions): IAdminAuthGuard;
202
+ //#endregion
203
+ export { AdminAuthGuardOptions, DnsLookupAllFn, IAdminAuthGuard, IAttributedBlockedAccount, IAttributedReservedSymbol, IAttributedTrustedAccount, IBlockedAccountEntry, ILedgerHealthThresholds, ILegacyPreferencesResult, INodePreferencesFileSchema, INodePreferencesSnapshot, INodeRuntimePreferences, IReservedSymbolEntry, ITrustedAccountEntry, IUpdateNodePreferencesInput, IUpdateNodePreferencesResult, MAX_BLOCKED_ACCOUNTS, MAX_CONFIG_BODY_BYTES, MAX_MEMO_LENGTH, MAX_PEER_URLS, MAX_RESERVED_SYMBOLS, MAX_TRUSTED_ACCOUNTS, NodePreferencesError, NodePreferencesManager, NodePreferencesManagerOptions, TPreferenceSource, applyBootRuntimePreferences, createAdminAuthGuard, createFollowerPeerFetchGuard, isPrivateOrReservedIpAddress, isValidAccountAddressCandidate, loadNodePreferences, normalizeBlockedAccountKey, timingSafeTokenEqual, validateFollowerPeerUrls };
@@ -0,0 +1,432 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let _arcblock_ledger_core = require("@arcblock/ledger-core");
3
+ let _ocap_mcrypto = require("@ocap/mcrypto");
4
+ let _ocap_tx_protocols = require("@ocap/tx-protocols");
5
+ let _ocap_util = require("@ocap/util");
6
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
7
+ let _ocap_state = require("@ocap/state");
8
+
9
+ //#region src/replayer.ts
10
+ /**
11
+ * Sequential Deterministic Ledger Entry Replayer (`concurrency = 1`, #1710)
12
+ *
13
+ * Replays finalized `ILedgerEntry` items from cold segments or hot-tail polling onto a Follower's
14
+ * local `statedb` + `indexdb` + `ledger`:
15
+ * - Always uses an isolated, empty `Blacklist` (never the follower's local `blocked.json`).
16
+ * - Pins `extra.txTime` to `entry.timestamp` and unpacks `entry.txExtra` (`{ txExtra, gasStakeHeaders }`).
17
+ * - Handles all 3 ledger entry classes:
18
+ * 1. `OK` committed transaction (`entry.stateCommitHash` non-empty)
19
+ * 2. `PERSISTED_FAILED` gas-charged transaction (`entry.stateCommitHash` non-empty)
20
+ * 3. Force-finalized orphan entry (`!entry.stateCommitHash`) — skips `runAsLambda` so `_state_commit`
21
+ * does NOT advance, verifies `toTxHash(txRaw) === entry.hash`, and indexes the rejected tx in `indexdb`.
22
+ * - Enforces pre-commit `expectedCommitHash` on `statedb.runAsLambda` so any state divergence rolls back
23
+ * SQLite atomically BEFORE `COMMIT` and before appending to `ledger.sqlite`.
24
+ */
25
+ /** Error code of a replayed entry refused for a timestamp ahead of the local clock (retryable, never halting). */
26
+ const FUTURE_LEDGER_ENTRY_TIMESTAMP = "FUTURE_LEDGER_ENTRY_TIMESTAMP";
27
+ function normalizeHexLower(raw) {
28
+ return String(raw ?? "").trim().replace(/^0x/i, "").toLowerCase();
29
+ }
30
+ function isLocalStorageEngineError(err, depth = 0) {
31
+ if (!err || typeof err !== "object" || depth > 3) return false;
32
+ if (err.upstreamTransportFailure === true) return false;
33
+ if (err.localStorageFailure === true) return true;
34
+ const rawCode = err.code;
35
+ const rawErrcode = err.errcode;
36
+ if (rawCode === 5 || rawCode === 6 || rawErrcode === 5 || rawErrcode === 6) return true;
37
+ if (typeof rawErrcode === "number" && Number.isFinite(rawErrcode)) {
38
+ const primaryErr = rawErrcode & 255;
39
+ if (primaryErr === 5 || primaryErr === 6 || primaryErr === 8 || primaryErr === 10 || primaryErr === 11 || primaryErr === 13 || primaryErr === 14 || primaryErr === 26) return true;
40
+ }
41
+ const code = String(rawCode ?? "");
42
+ const name = String(err.name ?? "");
43
+ const message = err instanceof Error ? err.message : String(err.message ?? "");
44
+ if (code === "INVALID_HASH" && /^Trusted hash verification failed\b/i.test(message) || /^SQLITE_/i.test(code) || code === "ERR_SQLITE_ERROR" || name === "SqliteError" || name === "SQLiteError" || !code && /^(?:Failed to verify signature of hash:|Failed to update hash, hash mismatch|database (?:table )?is locked\b)/i.test(message) || /^LEDGER_/i.test(code) && /(?:\bSQLITE_(?:CORRUPT|FULL|IOERR|BUSY|LOCKED|READONLY|CANTOPEN|NOTADB)\b|database disk image is malformed|file is not a database|database (?:table )?is locked)/i.test(message)) return true;
45
+ const cause = err.cause;
46
+ return cause !== void 0 && cause !== err ? isLocalStorageEngineError(cause, depth + 1) : false;
47
+ }
48
+ var LedgerEntryReplayer = class {
49
+ constructor(resolver, options = {}) {
50
+ this.activeSubLambdaOverride = null;
51
+ this.lastCommittedHash = null;
52
+ this.lastCommitMismatchError = null;
53
+ this.lastStorageError = null;
54
+ this.mutex = Promise.resolve();
55
+ this.resolver = resolver;
56
+ this.emptyFilter = new _ocap_state.Blacklist();
57
+ const guard = options.futureTimestampGuard;
58
+ if (guard) {
59
+ if (!Number.isSafeInteger(guard.activationSequence) || guard.activationSequence < 1) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `futureTimestampGuard.activationSequence must be a positive integer, got ${String(guard.activationSequence)}`);
60
+ if (!Number.isSafeInteger(guard.maxSkewMs) || guard.maxSkewMs < 0) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", `futureTimestampGuard.maxSkewMs must be a non-negative integer, got ${String(guard.maxSkewMs)}`);
61
+ }
62
+ this.futureTimestampGuard = guard ? { ...guard } : null;
63
+ const statedb = resolver.statedb;
64
+ const runAsLambda = typeof statedb.runAsLambda === "function" ? async (fn, opts = {}) => {
65
+ const expectedCommitHash = this.activeExpectedCommitHash;
66
+ const targetLambda = this.activeSubLambdaOverride ?? statedb.runAsLambda.bind(statedb);
67
+ let fnThrew = false;
68
+ let fnErrRef;
69
+ const wrappedFn = async (txn) => {
70
+ fnThrew = false;
71
+ fnErrRef = void 0;
72
+ try {
73
+ return await fn(txn);
74
+ } catch (innerErr) {
75
+ fnThrew = true;
76
+ fnErrRef = innerErr;
77
+ if (isLocalStorageEngineError(innerErr)) innerErr.localStorageFailure = true;
78
+ throw innerErr;
79
+ }
80
+ };
81
+ try {
82
+ return await targetLambda(wrappedFn, {
83
+ ...opts,
84
+ ...expectedCommitHash !== void 0 ? { expectedCommitHash } : {},
85
+ onCommit: async (commitHash) => {
86
+ this.lastCommittedHash = commitHash ?? null;
87
+ this.lastStorageError = null;
88
+ this.lastCommitMismatchError = null;
89
+ const origOnCommit = opts.onCommit;
90
+ if (typeof origOnCommit === "function") await origOnCommit(commitHash);
91
+ }
92
+ });
93
+ } catch (err) {
94
+ if (err?.code === "STATE_COMMIT_MISMATCH") this.lastCommitMismatchError = err;
95
+ else if (!fnThrew || err !== fnErrRef || isLocalStorageEngineError(err)) {
96
+ if (err && typeof err === "object") {
97
+ err.localStorageFailure = true;
98
+ if (!this.lastStorageError) this.lastStorageError = err;
99
+ }
100
+ }
101
+ throw err;
102
+ }
103
+ } : void 0;
104
+ this.executor = (0, _ocap_tx_protocols.createExecutor)({
105
+ filter: this.emptyFilter,
106
+ runAsLambda
107
+ });
108
+ }
109
+ async runExclusive(fn) {
110
+ const prev = this.mutex;
111
+ let release;
112
+ this.mutex = new Promise((resolve) => {
113
+ release = resolve;
114
+ });
115
+ await prev;
116
+ try {
117
+ return await fn();
118
+ } finally {
119
+ release();
120
+ }
121
+ }
122
+ async appendVerifiedEntryToLedger(entry, entryHashV2From) {
123
+ if (typeof this.resolver.ledger.appendVerifiedEntries === "function") {
124
+ await this.resolver.ledger.appendVerifiedEntries([entry], {
125
+ ...entryHashV2From !== void 0 ? { entryHashV2From } : {},
126
+ verifyTxRawHash: true,
127
+ strictDecode: true,
128
+ requireWireOnly: true
129
+ });
130
+ return;
131
+ }
132
+ const storage = this.resolver.ledger.getStorage?.();
133
+ if (storage && typeof storage.appendEntries === "function") {
134
+ await storage.appendEntries([entry]);
135
+ return;
136
+ }
137
+ throw new _ocap_util_lib_error.CustomError("LEDGER_UNSUPPORTED", "Follower ledger does not support appendVerifiedEntries");
138
+ }
139
+ verifyRawTxHashMatchesEntry(entry, throwCodeOnMismatch = "TX_HASH_MISMATCH") {
140
+ if (typeof entry.txRaw !== "string" || !entry.txRaw) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Ledger entry seq=${entry.sequence} is missing txRaw`);
141
+ if (typeof entry.hash !== "string" || !entry.hash) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Ledger entry seq=${entry.sequence} is missing string hash`);
142
+ if (entry.txRaw !== entry.txRaw.trim() || entry.txRaw.startsWith("{")) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Ledger entry seq=${entry.sequence} has non-canonical or non-wire txRaw`);
143
+ let computedTxHash;
144
+ try {
145
+ computedTxHash = (0, _ocap_mcrypto.toTxHash)((0, _ocap_util.fromBase64)(entry.txRaw));
146
+ } catch (err) {
147
+ throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Failed to hash txRaw at seq=${entry.sequence}: ${err instanceof Error ? err.message : String(err)}`);
148
+ }
149
+ if (computedTxHash.toUpperCase() !== entry.hash.toUpperCase()) throw new _ocap_util_lib_error.CustomError(throwCodeOnMismatch, `Ledger entry txRaw hash mismatch at seq=${entry.sequence}: computed ${computedTxHash}, entry has ${entry.hash}`);
150
+ }
151
+ /**
152
+ * #1961 future-timestamp guard (no-op unless `futureTimestampGuard` is configured). Throws a retryable
153
+ * `FUTURE_LEDGER_ENTRY_TIMESTAMP` that is neither a local divergence nor a peer authentication failure, so the
154
+ * follower logs it, keeps its state and retries on the next sync cycle.
155
+ */
156
+ assertEntryTimestampNotInFuture(entry) {
157
+ const guard = this.futureTimestampGuard;
158
+ if (!guard || !Number.isSafeInteger(entry?.sequence) || entry.sequence < guard.activationSequence) return;
159
+ const nowMs = guard.now ? guard.now() : Date.now();
160
+ if (!Number.isFinite(nowMs) || entry.timestamp <= nowMs + guard.maxSkewMs) return;
161
+ const info = {
162
+ sequence: entry.sequence,
163
+ hash: String(entry.hash ?? ""),
164
+ timestamp: entry.timestamp,
165
+ nowMs,
166
+ maxSkewMs: guard.maxSkewMs,
167
+ activationSequence: guard.activationSequence
168
+ };
169
+ try {
170
+ guard.onReject?.(info);
171
+ } catch {}
172
+ const err = new _ocap_util_lib_error.CustomError(FUTURE_LEDGER_ENTRY_TIMESTAMP, `Ledger entry seq=${entry.sequence} timestamp ${entry.timestamp} is ${entry.timestamp - nowMs} ms ahead of the local clock (max skew ${guard.maxSkewMs} ms, guard active from seq=${guard.activationSequence}); will retry`);
173
+ err.retryable = true;
174
+ throw err;
175
+ }
176
+ /**
177
+ * Pre-replay wire & primitive validation for untrusted network hot-tail / cold-segment payloads (#1710).
178
+ * Throws `INVALID_LEDGER_ENTRY` (peer-disqualifying, non-halting) on any malformed wire field or lossy JSON coercion,
179
+ * and the retryable `FUTURE_LEDGER_ENTRY_TIMESTAMP` when the #1961 guard is on (unless the entry is local).
180
+ */
181
+ validateWireEntry(entry, options = {}) {
182
+ 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`);
183
+ this.verifyRawTxHashMatchesEntry(entry, "INVALID_LEDGER_ENTRY");
184
+ this.authenticateAndDecodeEntry(entry);
185
+ if (!options.skipFutureTimestampCheck) this.assertEntryTimestampNotInFuture(entry);
186
+ }
187
+ authenticateAndDecodeEntry(entry) {
188
+ const authRes = (0, _arcblock_ledger_core.authenticateEntryDecodedFields)(entry, true, { requireFullWireEntry: true });
189
+ if (!authRes.ok) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Ledger entry seq=${entry.sequence} failed field authentication: ${authRes.reason}`);
190
+ return authRes.decodedTx;
191
+ }
192
+ async indexOrphanEntry(entry, decodedTx) {
193
+ const safeTx = decodedTx && typeof decodedTx === "object" ? decodedTx : {};
194
+ const rawItx = safeTx.itx && typeof safeTx.itx === "object" ? safeTx.itx : void 0;
195
+ const derivedTxType = rawItx && typeof rawItx.typeUrl === "string" && rawItx.typeUrl ? rawItx.typeUrl : rawItx && typeof rawItx.type === "string" && rawItx.type ? rawItx.type : typeof safeTx.txType === "string" && safeTx.txType ? safeTx.txType : entry.txType;
196
+ const txTimeIso = Number.isSafeInteger(entry.timestamp) && entry.timestamp >= 0 && entry.timestamp <= 864e13 ? new Date(entry.timestamp).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
197
+ await this.resolver._indexRejectedLedgerTx({
198
+ ledgerSequence: entry.sequence,
199
+ txHash: entry.hash,
200
+ txType: derivedTxType,
201
+ txTime: txTimeIso,
202
+ tx: {
203
+ ...safeTx,
204
+ from: String(safeTx.from ?? safeTx.spenderDid ?? ""),
205
+ nonce: safeTx.nonce ?? 0,
206
+ pk: String(safeTx.pk ?? safeTx.spenderPublicKey ?? ""),
207
+ signature: String(safeTx.signature ?? safeTx.spenderSignature ?? ""),
208
+ chainId: String(safeTx.chainId ?? this.resolver.config.chainId ?? "")
209
+ },
210
+ ...rawItx ? { itxJson: rawItx } : {}
211
+ }, { code: "ORPHAN_LEDGER_ENTRY" });
212
+ await this.resolver.flushIndexWrites();
213
+ }
214
+ /**
215
+ * Replay a single finalized `ILedgerEntry` sequentially (`concurrency = 1`).
216
+ */
217
+ async replayEntry(entry, options = {}) {
218
+ return this.runExclusive(async () => {
219
+ if (!entry || typeof entry !== "object") throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", "Cannot replay null or non-object ledger entry");
220
+ if (!entry.finalized) throw new _ocap_util_lib_error.CustomError("UNFINALIZED_LEDGER_ENTRY", `Refusing to replay unfinalized entry seq=${entry.sequence}`);
221
+ 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)}`);
222
+ const expectedChainId = this.resolver.config.chainId || this.resolver.ledger.chainId;
223
+ 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}`);
224
+ const appendToLedger = options.appendToLedger !== false;
225
+ 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)}`);
226
+ 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`);
227
+ const localLatestSeq = await this.resolver.ledger.getLatestSequence();
228
+ if (appendToLedger) {
229
+ if (entry.sequence <= localLatestSeq) {
230
+ const existing = await this.resolver.ledger.getBySequence(entry.sequence);
231
+ if (existing && existing.entryHash === entry.entryHash && existing.hash === entry.hash) return {
232
+ status: "already-applied",
233
+ sequence: entry.sequence,
234
+ hash: entry.hash,
235
+ code: "ALREADY_APPLIED",
236
+ stateCommitHash: existing.stateCommitHash || null
237
+ };
238
+ throw new _ocap_util_lib_error.CustomError("LEDGER_DIVERGENCE", `Ledger divergence at seq=${entry.sequence}: local entryHash=${existing?.entryHash ?? "missing"} !== upstream ${entry.entryHash}`);
239
+ }
240
+ if (entry.sequence !== localLatestSeq + 1) throw new _ocap_util_lib_error.CustomError("SEQUENCE_GAP", `Non-contiguous replay sequence: localLatest=${localLatestSeq}, got seq=${entry.sequence}`);
241
+ }
242
+ if (appendToLedger) this.assertEntryTimestampNotInFuture(entry);
243
+ this.verifyRawTxHashMatchesEntry(entry);
244
+ const decodedTx = this.authenticateAndDecodeEntry(entry);
245
+ const expectedStateCommit = (entry.stateCommitHash ?? "").trim();
246
+ if (appendToLedger) {
247
+ const v2Cutoff = options.entryHashV2From === "infinity" ? Number.POSITIVE_INFINITY : typeof options.entryHashV2From === "number" ? options.entryHashV2From : this.resolver.ledger.getEntryHashV2From?.() ?? 1;
248
+ const expectedEntryHash = (0, _arcblock_ledger_core.computeEntryHash)(entry.sequence, entry.txRaw, expectedStateCommit, entry.sequence >= v2Cutoff ? 2 : 1);
249
+ 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}`);
250
+ }
251
+ if (!expectedStateCommit) {
252
+ if (appendToLedger) await this.appendVerifiedEntryToLedger(entry, options.entryHashV2From);
253
+ await this.indexOrphanEntry(entry, decodedTx);
254
+ return {
255
+ status: "orphan-indexed",
256
+ sequence: entry.sequence,
257
+ hash: entry.hash,
258
+ code: "ORPHAN_LEDGER_ENTRY",
259
+ stateCommitHash: null
260
+ };
261
+ }
262
+ const unpackedExtra = entry.txExtra && typeof entry.txExtra === "object" ? { ...entry.txExtra } : {};
263
+ const execContext = {
264
+ txBase64: entry.txRaw,
265
+ statedb: this.resolver.statedb,
266
+ indexdb: this.resolver.indexdb,
267
+ ledger: void 0,
268
+ ledgerSequence: entry.sequence,
269
+ config: this.resolver.config,
270
+ filter: this.emptyFilter,
271
+ logger: this.resolver.logger,
272
+ extra: {
273
+ ...unpackedExtra,
274
+ txTime: entry.timestamp,
275
+ _isReplay: true
276
+ }
277
+ };
278
+ this.activeExpectedCommitHash = expectedStateCommit;
279
+ this.lastCommittedHash = null;
280
+ this.lastCommitMismatchError = null;
281
+ this.lastStorageError = null;
282
+ let execError = null;
283
+ try {
284
+ await this.executor.execute(execContext);
285
+ } catch (err) {
286
+ execError = err;
287
+ } finally {
288
+ this.activeExpectedCommitHash = void 0;
289
+ }
290
+ if (!this.lastCommittedHash && this.lastStorageError) throw this.lastStorageError;
291
+ if (this.lastCommitMismatchError) throw this.lastCommitMismatchError;
292
+ if (this.lastStorageError) throw this.lastStorageError;
293
+ if (execError?.code === "STATE_COMMIT_MISMATCH") throw execError;
294
+ if (execError && isLocalStorageEngineError(execError)) {
295
+ execError.localStorageFailure = true;
296
+ throw execError;
297
+ }
298
+ if (typeof this.resolver.statedb.runAsLambda === "function") {
299
+ if (!this.lastCommittedHash) throw new _ocap_util_lib_error.CustomError("STATE_COMMIT_MISMATCH", `Replay of seq=${entry.sequence} (${entry.hash}) did not commit state (expected ${expectedStateCommit}; error=${execError?.code || execError?.message || "none"})`);
300
+ if (normalizeHexLower(this.lastCommittedHash) !== normalizeHexLower(expectedStateCommit)) throw new _ocap_util_lib_error.CustomError("STATE_COMMIT_MISMATCH", `State commit mismatch at seq=${entry.sequence}: expected ${expectedStateCommit}, got ${this.lastCommittedHash}`);
301
+ }
302
+ const replayedHash = typeof execContext.txHash === "string" ? execContext.txHash : "";
303
+ if (replayedHash && replayedHash.toUpperCase() !== entry.hash.toUpperCase()) throw new _ocap_util_lib_error.CustomError("TX_HASH_MISMATCH", `Replayed txHash (${replayedHash}) !== ledger entry hash (${entry.hash}) at seq=${entry.sequence}`);
304
+ if (appendToLedger) await this.appendVerifiedEntryToLedger(entry, options.entryHashV2From);
305
+ await this.resolver.flushIndexWrites();
306
+ return {
307
+ status: execError ? "persisted-failed" : "applied",
308
+ sequence: entry.sequence,
309
+ hash: entry.hash,
310
+ code: execError ? execError.code || "FAILED" : "OK",
311
+ stateCommitHash: this.lastCommittedHash ?? expectedStateCommit
312
+ };
313
+ });
314
+ }
315
+ /**
316
+ * Dry-run verify a proposed batch of `1..N` finalized entries inside a single rolled-back SQLite
317
+ * transaction (#1712 HotStuff-Lite replica voting), verifying every entry's wire format, `entryHash`,
318
+ * and post-execution `_state_commit` hash with zero mutations to `statedb`, `trusted`, `indexdb`, or `ledger`.
319
+ */
320
+ async dryRunVerifyEntries(entries, options = {}) {
321
+ return this.runExclusive(async () => {
322
+ if (!Array.isArray(entries) || entries.length === 0) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", "Cannot dry-run an empty proposal entry batch");
323
+ if (typeof this.resolver.statedb.runWithinDryRunSession !== "function") throw new _ocap_util_lib_error.CustomError("DRY_RUN_UNSUPPORTED", "StateDB adapter does not support runWithinDryRunSession for BFT replica dry-run verification");
324
+ const expectedChainId = this.resolver.config.chainId || this.resolver.ledger.chainId;
325
+ const baseSeq = options.expectedPrevSequence !== void 0 ? options.expectedPrevSequence : await this.resolver.ledger.getLatestSequence();
326
+ const v2Cutoff = options.entryHashV2From === "infinity" ? Number.POSITIVE_INFINITY : typeof options.entryHashV2From === "number" ? options.entryHashV2From : this.resolver.ledger.getEntryHashV2From?.() ?? 1;
327
+ const entryHashes = [];
328
+ for (let i = 0; i < entries.length; i++) {
329
+ const entry = entries[i];
330
+ if (!entry || typeof entry !== "object") throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Proposal entry at index ${i} is not an object`);
331
+ if (entry.finalized !== true) throw new _ocap_util_lib_error.CustomError("UNFINALIZED_LEDGER_ENTRY", `Proposal entry seq=${String(entry.sequence)} must be finalized`);
332
+ 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}`);
333
+ 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}`);
334
+ this.validateWireEntry(entry, { skipFutureTimestampCheck: options.skipFutureTimestampCheck });
335
+ const expectedStateCommit = (entry.stateCommitHash ?? "").trim();
336
+ const expectedEntryHash = (0, _arcblock_ledger_core.computeEntryHash)(entry.sequence, entry.txRaw, expectedStateCommit, entry.sequence >= v2Cutoff ? 2 : 1);
337
+ if (entry.entryHash !== expectedEntryHash) throw new _ocap_util_lib_error.CustomError("INVALID_LEDGER_ENTRY", `Proposal entryHash mismatch at seq=${entry.sequence}: expected ${expectedEntryHash}, got ${entry.entryHash}`);
338
+ entryHashes.push(entry.entryHash);
339
+ }
340
+ let derivedStateRoot = (options.prevStateRoot ?? "").trim();
341
+ const dryRunFilter = new _ocap_state.Blacklist();
342
+ try {
343
+ await this.resolver.statedb.runWithinDryRunSession(async (runSubLambda) => {
344
+ this.activeSubLambdaOverride = runSubLambda;
345
+ try {
346
+ for (const entry of entries) {
347
+ const expectedStateCommit = (entry.stateCommitHash ?? "").trim();
348
+ if (!expectedStateCommit) continue;
349
+ const unpackedExtra = entry.txExtra && typeof entry.txExtra === "object" ? { ...entry.txExtra } : {};
350
+ const execContext = {
351
+ txBase64: entry.txRaw,
352
+ statedb: this.resolver.statedb,
353
+ indexdb: this.resolver.indexdb,
354
+ ledger: void 0,
355
+ ledgerSequence: entry.sequence,
356
+ config: this.resolver.config,
357
+ filter: dryRunFilter,
358
+ logger: this.resolver.logger,
359
+ extra: {
360
+ ...unpackedExtra,
361
+ txTime: entry.timestamp,
362
+ _isReplay: true,
363
+ _dryRun: true
364
+ }
365
+ };
366
+ this.activeExpectedCommitHash = expectedStateCommit;
367
+ this.lastCommittedHash = null;
368
+ this.lastCommitMismatchError = null;
369
+ this.lastStorageError = null;
370
+ let execError = null;
371
+ try {
372
+ await this.executor.execute(execContext);
373
+ } catch (err) {
374
+ execError = err;
375
+ } finally {
376
+ this.activeExpectedCommitHash = void 0;
377
+ }
378
+ if (!this.lastCommittedHash && this.lastStorageError) throw this.lastStorageError;
379
+ if (this.lastCommitMismatchError) throw this.lastCommitMismatchError;
380
+ if (this.lastStorageError) throw this.lastStorageError;
381
+ if (execError?.code === "STATE_COMMIT_MISMATCH") throw execError;
382
+ if (execError && isLocalStorageEngineError(execError)) {
383
+ execError.localStorageFailure = true;
384
+ throw execError;
385
+ }
386
+ if (!this.lastCommittedHash) throw new _ocap_util_lib_error.CustomError("STATE_COMMIT_MISMATCH", `Dry-run of seq=${entry.sequence} (${entry.hash}) did not commit state (expected ${expectedStateCommit}; error=${execError?.code || execError?.message || "none"})`);
387
+ if (normalizeHexLower(this.lastCommittedHash) !== normalizeHexLower(expectedStateCommit)) throw new _ocap_util_lib_error.CustomError("STATE_COMMIT_MISMATCH", `Dry-run state commit mismatch at seq=${entry.sequence}: expected ${expectedStateCommit}, got ${this.lastCommittedHash}`);
388
+ const replayedHash = typeof execContext.txHash === "string" ? execContext.txHash : "";
389
+ if (replayedHash && replayedHash.toUpperCase() !== entry.hash.toUpperCase()) throw new _ocap_util_lib_error.CustomError("TX_HASH_MISMATCH", `Dry-run txHash (${replayedHash}) !== proposal entry hash (${entry.hash}) at seq=${entry.sequence}`);
390
+ derivedStateRoot = this.lastCommittedHash;
391
+ }
392
+ } finally {
393
+ this.activeSubLambdaOverride = null;
394
+ this.activeExpectedCommitHash = void 0;
395
+ }
396
+ });
397
+ } catch (dryRunErr) {
398
+ if (dryRunErr && typeof dryRunErr === "object" && isLocalStorageEngineError(dryRunErr)) dryRunErr.localStorageFailure = true;
399
+ throw dryRunErr;
400
+ }
401
+ return {
402
+ derivedStateRoot,
403
+ entryHashes
404
+ };
405
+ });
406
+ }
407
+ /**
408
+ * Scan existing local ledger entries in `[fromSeq, toSeq]` and ensure any force-finalized
409
+ * orphan entries (`stateCommitHash === ''`) are indexed into `indexdb.tx` after `rebuildIndex()`.
410
+ */
411
+ async indexExistingOrphanEntries(fromSeq = 1, toSeq) {
412
+ const latestSeq = toSeq ?? await this.resolver.ledger.getLatestSequence();
413
+ if (latestSeq < fromSeq) return 0;
414
+ let indexedCount = 0;
415
+ const pageSize = 200;
416
+ for (let cursor = Math.max(1, fromSeq); cursor <= latestSeq; cursor += pageSize) {
417
+ const end = Math.min(latestSeq, cursor + pageSize - 1);
418
+ const entries = await this.resolver.ledger.getRange(cursor, end);
419
+ for (const entry of entries) if (!entry.stateCommitHash || !entry.stateCommitHash.trim()) {
420
+ this.verifyRawTxHashMatchesEntry(entry);
421
+ const decodedTx = this.authenticateAndDecodeEntry(entry);
422
+ await this.indexOrphanEntry(entry, decodedTx);
423
+ indexedCount++;
424
+ }
425
+ }
426
+ return indexedCount;
427
+ }
428
+ };
429
+
430
+ //#endregion
431
+ exports.FUTURE_LEDGER_ENTRY_TIMESTAMP = FUTURE_LEDGER_ENTRY_TIMESTAMP;
432
+ exports.LedgerEntryReplayer = LedgerEntryReplayer;