@ocap/resolver 1.31.8 → 1.32.0

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 +277 -0
  9. package/esm/follower.mjs +2428 -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 +87 -4
  14. package/esm/index.mjs +937 -177
  15. package/esm/node-preferences.d.mts +203 -0
  16. package/esm/node-preferences.mjs +1021 -0
  17. package/esm/replayer.d.mts +74 -0
  18. package/esm/replayer.mjs +394 -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 +2434 -0
  29. package/lib/follower.d.cts +277 -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 +972 -177
  34. package/lib/index.d.cts +87 -4
  35. package/lib/node-preferences.cjs +1043 -0
  36. package/lib/node-preferences.d.cts +203 -0
  37. package/lib/replayer.cjs +395 -0
  38. package/lib/replayer.d.cts +74 -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,2668 @@
1
+ import { LedgerEntryReplayer } from "./replayer.mjs";
2
+ import { IncrementalMerkleTree, LeaderRouter, aggregatePrepareQuorumCertificate, aggregateQuorumCertificate, aggregateTimeoutCertificate, assertValidConsensusBindHost, assertValidConsensusPeerUrl, canVoterPrepareProposal, computeCheckpointHash, computeEntryHash, computeSegmentCommitmentDigest, computeSegmentContentHash, createCheckpointSigner, createHotStuffProposal, createHotStuffTimeoutMessage, createHotStuffTrustAnchor, getLeaderForView, normalizeHttpBaseUrl, selectHighestQC, toHotStuffClusterConfig, verifyCheckpointQuorumCertificate, verifyHotStuffPrepareVote, verifyHotStuffTimeoutMessage, verifyHotStuffVote, verifyPrepareQCAndCreateCommitVote, verifyPrepareQuorumCertificate, verifyProposalAndCreatePrepareVote, verifyQuorumCertificate, verifySegmentCommitmentSignature, verifyTimeoutCertificate } from "@arcblock/ledger-core";
3
+ import { createHash, randomBytes } from "node:crypto";
4
+ import { CustomError } from "@ocap/util/lib/error";
5
+ import http from "node:http";
6
+
7
+ //#region src/hotstuff-runtime.ts
8
+ /**
9
+ * Split-Plane WireGuard Consensus Listener & HotStuff-Lite 3f+1 BFT HA Runtime (#1712)
10
+ *
11
+ * Implements:
12
+ * 1. Dedicated private consensus `node:http` server bound STRICTLY to `CONSENSUS_BIND_HOST`
13
+ * (loopback or private WireGuard IP — never `0.0.0.0` / `::` / public IP, and never mounted on
14
+ * the public Express RPC server).
15
+ * 2. Mutual Ed25519 request + response authentication (`X-Ocap-Consensus-*` headers) against the
16
+ * `HOTSTUFF_VALIDATORS` roster with `±60s` clock-skew bounds, bounded nonce replay cache,
17
+ * `redirect: 'error'`, and strict pre-`JSON.parse` byte caps (`2 MiB` data / `256 KiB` control).
18
+ * 3. 1-RTT `Instant Settle` HotStuff-Lite execution (`executeWithConsensusLock` + `IConsensusCommitter`)
19
+ * across rotating views (`validators[view % N]`), replica SQLite `SAVEPOINT` dry-run voting
20
+ * (`LedgerEntryReplayer.dryRunVerifyEntries`), Pacemaker heartbeats + `TimeoutCertificate` failover,
21
+ * uncommitted `tc.lockedCheckpoint` recovery, quorum-lease isolation (`1-vs-3` partition), and
22
+ * stale-leader automatic demotion + `LeaderRouter` write forwarding.
23
+ */
24
+ const MAX_DATA_ROUTE_BYTES = 2 * 1024 * 1024;
25
+ const MAX_CONTROL_ROUTE_BYTES = 256 * 1024;
26
+ const MAX_CLOCK_SKEW_MS = 6e4;
27
+ const REPLAY_TTL_MS = 12e4;
28
+ const MAX_REPLAY_CACHE_ENTRIES = 8192;
29
+ const DEFAULT_PROPOSAL_TIMEOUT_MS = 2500;
30
+ const DEFAULT_HTTP_TIMEOUT_MS = 3e3;
31
+ const DEFAULT_HEARTBEAT_INTERVAL_MS = 400;
32
+ const DEFAULT_VIEW_TIMEOUT_MS = 1500;
33
+ const MAX_VIEW_TIMEOUT_BACKOFF_MULTIPLIER = 8;
34
+ const DEFAULT_STARTUP_QUORUM_GRACE_MS = 2e3;
35
+ const NEXT_LEADER_COMMIT_WAIT_MS = 300;
36
+ const MAX_CATCHUP_SEGMENTS_PER_REQUEST = 50;
37
+ const MAX_IN_MEMORY_UNCOMMITTED_PROPOSALS = 8;
38
+ const DEFAULT_MAX_EMPTY_VIEW_MS = 12e3;
39
+ var ConsensusAbortError = class extends CustomError {
40
+ constructor(code, message) {
41
+ super(code, message);
42
+ this.isConsensusAbort = true;
43
+ this.code = code;
44
+ this.name = "ConsensusAbortError";
45
+ }
46
+ };
47
+ function sha256HexBytes(bytes) {
48
+ return `0x${createHash("sha256").update(bytes).digest("hex")}`;
49
+ }
50
+ function sha256Utf8Bytes(input) {
51
+ return new Uint8Array(createHash("sha256").update(input, "utf8").digest());
52
+ }
53
+ function normalizeHexCompare(hex) {
54
+ return String(hex ?? "").trim().replace(/^0x/i, "").toLowerCase();
55
+ }
56
+ function buildCanonicalHttpAuthDigest(params) {
57
+ const bodyHash = sha256HexBytes(params.bodyBytes);
58
+ return sha256Utf8Bytes(JSON.stringify([
59
+ "arcblock:consensus-http:v1",
60
+ params.kind,
61
+ params.chainId,
62
+ params.methodOrStatus.toUpperCase(),
63
+ params.pathWithQuery,
64
+ params.senderDid,
65
+ String(params.timestampMs),
66
+ params.nonce,
67
+ bodyHash
68
+ ]));
69
+ }
70
+ async function readIncomingBytesBounded(req, maxBytes) {
71
+ const rawLen = req.headers["content-length"];
72
+ if (typeof rawLen === "string" && rawLen.trim().length > 0) {
73
+ const declared = Number(rawLen);
74
+ if (Number.isFinite(declared) && declared > maxBytes) return {
75
+ ok: false,
76
+ status: 413,
77
+ code: "PAYLOAD_TOO_LARGE",
78
+ error: `Consensus request Content-Length (${declared}) exceeds ${maxBytes} bytes`
79
+ };
80
+ }
81
+ return new Promise((resolve) => {
82
+ const chunks = [];
83
+ let total = 0;
84
+ let settled = false;
85
+ const finish = (res) => {
86
+ if (settled) return;
87
+ settled = true;
88
+ resolve(res);
89
+ };
90
+ req.on("data", (chunk) => {
91
+ if (settled) return;
92
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf8");
93
+ total += buf.byteLength;
94
+ if (total > maxBytes) {
95
+ req.pause();
96
+ finish({
97
+ ok: false,
98
+ status: 413,
99
+ code: "PAYLOAD_TOO_LARGE",
100
+ error: `Consensus request body exceeds ${maxBytes}-byte limit`
101
+ });
102
+ return;
103
+ }
104
+ chunks.push(buf);
105
+ });
106
+ req.on("end", () => {
107
+ if (settled) return;
108
+ finish({
109
+ ok: true,
110
+ bytes: new Uint8Array(Buffer.concat(chunks, total))
111
+ });
112
+ });
113
+ req.on("error", () => {
114
+ finish({
115
+ ok: false,
116
+ status: 400,
117
+ code: "STREAM_ERROR",
118
+ error: "Failed to read consensus request body"
119
+ });
120
+ });
121
+ });
122
+ }
123
+ async function readFetchResponseBytesBounded(response, maxBytes) {
124
+ const contentLength = response.headers?.get?.("content-length");
125
+ if (contentLength) {
126
+ const declared = Number(contentLength);
127
+ if (Number.isFinite(declared) && declared > maxBytes) {
128
+ await response.body?.cancel().catch(() => void 0);
129
+ throw new CustomError("RESPONSE_TOO_LARGE", `Consensus response (${declared}) exceeds ${maxBytes} bytes`);
130
+ }
131
+ }
132
+ if (!response.body || typeof response.body.getReader !== "function") {
133
+ const buf = new Uint8Array(await response.arrayBuffer());
134
+ if (buf.byteLength > maxBytes) throw new CustomError("RESPONSE_TOO_LARGE", `Consensus response (${buf.byteLength}) exceeds ${maxBytes} bytes`);
135
+ return buf;
136
+ }
137
+ const reader = response.body.getReader();
138
+ const chunks = [];
139
+ let total = 0;
140
+ try {
141
+ while (true) {
142
+ const { done, value } = await reader.read();
143
+ if (done) break;
144
+ if (!value || value.byteLength === 0) continue;
145
+ total += value.byteLength;
146
+ if (total > maxBytes) {
147
+ await reader.cancel().catch(() => void 0);
148
+ throw new CustomError("RESPONSE_TOO_LARGE", `Consensus streaming response exceeded ${maxBytes} bytes`);
149
+ }
150
+ chunks.push(value);
151
+ }
152
+ } finally {
153
+ try {
154
+ reader.releaseLock();
155
+ } catch {}
156
+ }
157
+ const out = new Uint8Array(total);
158
+ let offset = 0;
159
+ for (const c of chunks) {
160
+ out.set(c, offset);
161
+ offset += c.byteLength;
162
+ }
163
+ return out;
164
+ }
165
+ var InMemoryHotStuffStateStore = class {
166
+ constructor() {
167
+ this.lock = null;
168
+ this.currentView = 0;
169
+ this.lockedQC = null;
170
+ this.highQC = null;
171
+ this.lastTC = null;
172
+ this.uncommitted = /* @__PURE__ */ new Map();
173
+ }
174
+ async getLock() {
175
+ return this.lock;
176
+ }
177
+ async setLock(record) {
178
+ this.lock = { ...record };
179
+ this.currentView = Math.max(this.currentView, record.lastVotedView, record.lastPreparedView ?? 0, record.lastCommitVotedView ?? 0, record.lastTimedOutView ?? 0);
180
+ }
181
+ async loadRuntimeState(chainId, voterDid) {
182
+ return {
183
+ chainId,
184
+ voterDid,
185
+ currentView: this.currentView,
186
+ lockRecord: this.lock,
187
+ lockedQC: this.lockedQC,
188
+ highQC: this.highQC,
189
+ lastTC: this.lastTC
190
+ };
191
+ }
192
+ async saveRuntimeState(params) {
193
+ if (params.lockedQC !== void 0) this.lockedQC = selectHighestQC([this.lockedQC, params.lockedQC]);
194
+ if (params.highQC !== void 0) this.highQC = selectHighestQC([this.highQC, params.highQC]);
195
+ if (params.lastTC && (!this.lastTC || params.lastTC.viewNumber > this.lastTC.viewNumber || params.lastTC.viewNumber === this.lastTC.viewNumber && params.lastTC.signatures.length > this.lastTC.signatures.length)) this.lastTC = params.lastTC;
196
+ this.currentView = Math.max(this.currentView, params.currentView ?? 0, this.highQC ? this.highQC.viewNumber + 1 : 0, this.lastTC ? this.lastTC.viewNumber + 1 : 0);
197
+ const pruneUpTo = params.pruneUncommittedUpToHeight ?? this.highQC?.height ?? 0;
198
+ if (pruneUpTo > 0) {
199
+ for (const [k, v] of this.uncommitted.entries()) if (v.height <= pruneUpTo) this.uncommitted.delete(k);
200
+ if (this.lock?.lockedPrepareQC && this.lock.lockedPrepareQC.height <= pruneUpTo) {
201
+ const pruned = { ...this.lock };
202
+ delete pruned.lockedPrepareQC;
203
+ delete pruned.lockedPrepareCheckpoint;
204
+ this.lock = pruned;
205
+ }
206
+ }
207
+ }
208
+ async saveUncommittedProposalEntries(params) {
209
+ if (this.highQC && params.height <= this.highQC.height) return;
210
+ const cleanKey = normalizeHexCompare(params.checkpointHash);
211
+ if (!cleanKey) return;
212
+ this.uncommitted.set(cleanKey, {
213
+ height: params.height,
214
+ entries: params.entries,
215
+ ...params.checkpoint ? { checkpoint: params.checkpoint } : {},
216
+ updatedAt: params.updatedAt ?? Date.now()
217
+ });
218
+ if (this.uncommitted.size > MAX_IN_MEMORY_UNCOMMITTED_PROPOSALS) {
219
+ const pinned = /* @__PURE__ */ new Set();
220
+ for (const raw of [
221
+ this.lock?.lockedPrepareQC?.checkpointHash,
222
+ this.lock?.lockedPrepareCheckpoint?.hash,
223
+ this.lock?.lastPreparedCheckpointHash,
224
+ this.lock?.lastCommitVotedCheckpointHash,
225
+ this.lock?.lastVotedCheckpointHash,
226
+ this.lastTC?.lockedCheckpoint?.hash,
227
+ this.lastTC?.highestPrepareCheckpoint?.hash,
228
+ this.lastTC?.highestPrepareQC?.checkpointHash
229
+ ]) {
230
+ const norm = normalizeHexCompare(raw);
231
+ if (norm) pinned.add(norm);
232
+ }
233
+ const evictable = Array.from(this.uncommitted.entries()).filter(([k]) => !pinned.has(k)).sort((a, b) => a[1].updatedAt - b[1].updatedAt);
234
+ while (this.uncommitted.size > MAX_IN_MEMORY_UNCOMMITTED_PROPOSALS && evictable.length > 0) {
235
+ const drop = evictable.shift();
236
+ if (drop) this.uncommitted.delete(drop[0]);
237
+ }
238
+ }
239
+ }
240
+ async getUncommittedProposalEntries(_chainId, _voterDid, checkpointHash) {
241
+ return this.uncommitted.get(normalizeHexCompare(checkpointHash))?.entries ?? null;
242
+ }
243
+ async getUncommittedProposalCheckpoint(_chainId, _voterDid, checkpointHash) {
244
+ return this.uncommitted.get(normalizeHexCompare(checkpointHash))?.checkpoint ?? null;
245
+ }
246
+ };
247
+ var HotStuffNodeRuntime = class {
248
+ constructor(options) {
249
+ this.role = "validator";
250
+ this.server = null;
251
+ this.boundPort = 0;
252
+ this.heartbeatTimer = null;
253
+ this.viewTimer = null;
254
+ this.mutexTail = Promise.resolve();
255
+ this.inConsensusLock = false;
256
+ this.startedAtMs = 0;
257
+ this.stopped = false;
258
+ this.halted = false;
259
+ this.haltReason = null;
260
+ this.currentView = 0;
261
+ this.lastSelfVotedView = -1;
262
+ this.lastSelfPreparedView = -1;
263
+ this.currentViewEnteredAtMs = Date.now();
264
+ this.pendingDemandForView = -1;
265
+ this.consecutiveViewTimeouts = 0;
266
+ this.highQC = null;
267
+ this.lockedQC = null;
268
+ this.lastTC = null;
269
+ this.quorumLeaseValid = true;
270
+ this.quorumContactObserved = false;
271
+ this.unleadableView = -1;
272
+ this.activeProposalSlot = null;
273
+ this.pendingBroadcastSegments = [];
274
+ this.peerLastSeenAtMs = /* @__PURE__ */ new Map();
275
+ this.replayCache = /* @__PURE__ */ new Map();
276
+ this.collectedTimeoutsByView = /* @__PURE__ */ new Map();
277
+ this.demandSendersByView = /* @__PURE__ */ new Map();
278
+ this.viewAdvanceWaiters = /* @__PURE__ */ new Set();
279
+ this.resolver = options.resolver;
280
+ this.writePolicy = options.writePolicy ?? "forward";
281
+ this.chainId = options.resolver.config.chainId || options.resolver.ledger.chainId;
282
+ this.replayer = new LedgerEntryReplayer(options.resolver);
283
+ this.consensusBindHost = assertValidConsensusBindHost(options.consensusBindHost, { allowPublicBind: options.allowPublicBind });
284
+ if (!Number.isSafeInteger(options.consensusPort) || options.consensusPort < 0 || options.consensusPort > 65535) throw new CustomError("INVALID_CONSENSUS_PORT", `Invalid consensusPort: ${String(options.consensusPort)}`);
285
+ this.configuredConsensusPort = options.consensusPort;
286
+ if (!Array.isArray(options.validators) || options.validators.length < 4) throw new CustomError("INVALID_HOTSTUFF_VALIDATORS", "HotStuffNodeRuntime requires at least 4 validators (3f+1 BFT)");
287
+ this.validatorMap = /* @__PURE__ */ new Map();
288
+ const normalizedValidators = [];
289
+ for (const v of options.validators) {
290
+ const normalizedConsensusUrl = assertValidConsensusPeerUrl(v.consensusUrl, { allowPrivateHttp: options.allowPrivateHttpPeers !== false });
291
+ const normalizedRpcUrl = normalizeHttpBaseUrl(v.rpcUrl, `validator(${v.did}).rpcUrl`);
292
+ const entry = {
293
+ did: v.did.trim(),
294
+ publicKey: v.publicKey.trim(),
295
+ rpcUrl: normalizedRpcUrl,
296
+ consensusUrl: normalizedConsensusUrl
297
+ };
298
+ this.validatorMap.set(entry.did, entry);
299
+ normalizedValidators.push(entry);
300
+ }
301
+ this.validators = normalizedValidators;
302
+ this.selfDid = options.validatorDid.trim();
303
+ if (!this.validatorMap.get(this.selfDid)) throw new CustomError("INVALID_HOTSTUFF_VALIDATORS", `Local validator DID ${this.selfDid} is not present in HOTSTUFF_VALIDATORS roster`);
304
+ this.peerValidators = this.validators.filter((v) => v.did !== this.selfDid);
305
+ this.clusterConfig = toHotStuffClusterConfig(this.chainId, this.validators, options.quorumThreshold);
306
+ this.validatorWallet = options.validatorWallet;
307
+ this.signDigest = createCheckpointSigner(options.validatorWallet, this.selfDid);
308
+ const rawAnchor = createHotStuffTrustAnchor(this.clusterConfig);
309
+ this.trustAnchorVerify = async (data, signature, signerDid) => Boolean(rawAnchor.verifier(data, signature, signerDid));
310
+ this.stateStore = options.stateStore ?? new InMemoryHotStuffStateStore();
311
+ this.proposalTimeoutMs = typeof options.proposalTimeoutMs === "number" && options.proposalTimeoutMs >= 100 ? options.proposalTimeoutMs : DEFAULT_PROPOSAL_TIMEOUT_MS;
312
+ this.httpTimeoutMs = typeof options.httpTimeoutMs === "number" && options.httpTimeoutMs >= 100 ? options.httpTimeoutMs : DEFAULT_HTTP_TIMEOUT_MS;
313
+ this.heartbeatIntervalMs = typeof options.heartbeatIntervalMs === "number" && options.heartbeatIntervalMs >= 40 ? options.heartbeatIntervalMs : DEFAULT_HEARTBEAT_INTERVAL_MS;
314
+ this.baseViewTimeoutMs = typeof options.viewTimeoutMs === "number" && options.viewTimeoutMs >= 100 ? options.viewTimeoutMs : DEFAULT_VIEW_TIMEOUT_MS;
315
+ this.maxEmptyViewMs = typeof options.maxEmptyViewMs === "number" && options.maxEmptyViewMs >= 200 ? options.maxEmptyViewMs : Math.max(DEFAULT_MAX_EMPTY_VIEW_MS, this.baseViewTimeoutMs * 6);
316
+ this.quorumLeaseTimeoutMs = typeof options.quorumLeaseTimeoutMs === "number" && options.quorumLeaseTimeoutMs >= 150 ? options.quorumLeaseTimeoutMs : Math.max(this.heartbeatIntervalMs * 4, this.baseViewTimeoutMs * 2);
317
+ this.startupQuorumGraceMs = typeof options.startupQuorumGraceMs === "number" && options.startupQuorumGraceMs >= 0 ? options.startupQuorumGraceMs : DEFAULT_STARTUP_QUORUM_GRACE_MS;
318
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
319
+ this.onOutboundConsensusRequest = options.onOutboundConsensusRequest;
320
+ this.onLeaderReplicaVoteReceived = options.onLeaderReplicaVoteReceived;
321
+ this.onLeaderReplicaPrecommitReceived = options.onLeaderReplicaPrecommitReceived;
322
+ this.leaderRouter = options.leaderRouter ?? new LeaderRouter({
323
+ chainId: this.chainId,
324
+ peerUrls: this.peerValidators.map((v) => v.rpcUrl),
325
+ hotstuffClusterConfig: this.clusterConfig,
326
+ requireSignedForwardReceipt: true,
327
+ fetchImpl: this.fetchImpl,
328
+ probeTimeoutMs: Math.min(2e3, this.httpTimeoutMs),
329
+ timeoutMs: Math.max(5e3, this.proposalTimeoutMs * 3),
330
+ failoverRetryTimeoutMs: Math.max(6e3, this.baseViewTimeoutMs * 4)
331
+ });
332
+ }
333
+ getConsensusMode() {
334
+ return "hotstuff";
335
+ }
336
+ getConsensusView() {
337
+ return this.currentView;
338
+ }
339
+ getHighQC() {
340
+ return this.highQC;
341
+ }
342
+ getLockedQC() {
343
+ return this.lockedQC;
344
+ }
345
+ getLastTC() {
346
+ return this.lastTC;
347
+ }
348
+ getListeningPort() {
349
+ return this.boundPort;
350
+ }
351
+ getConsensusBaseUrl() {
352
+ return `http://${this.consensusBindHost.includes(":") ? `[${this.consensusBindHost}]` : this.consensusBindHost}:${this.boundPort || this.configuredConsensusPort}`;
353
+ }
354
+ getConsensusCommitter() {
355
+ return this;
356
+ }
357
+ isHalted() {
358
+ return this.halted;
359
+ }
360
+ getHaltReason() {
361
+ return this.haltReason;
362
+ }
363
+ updateRuntimeConfig(patch) {
364
+ if (patch.peerUrls !== void 0) throw new CustomError("IMMUTABLE_CLUSTER_CONFIG", "Validator peerUrls cannot be mutated via runtime preferences in HotStuff mode");
365
+ if (patch.writePolicy !== void 0) {
366
+ if (patch.writePolicy !== "reject" && patch.writePolicy !== "forward") throw new CustomError("INVALID_CONFIG", `Invalid writePolicy "${String(patch.writePolicy)}"`);
367
+ this.writePolicy = patch.writePolicy;
368
+ }
369
+ }
370
+ getRuntimeDiagnostics(options) {
371
+ const includePrivate = options?.includePrivateTopology === true;
372
+ const nowMs = Date.now();
373
+ const quorumLeaseValid = this.refreshQuorumLease(nowMs);
374
+ const currentLeader = getLeaderForView(this.clusterConfig, this.currentView);
375
+ const livePeerCount = this.computeLivePeerCount(nowMs);
376
+ const validators = this.validators.slice(0, 64).map((v, idx) => {
377
+ const isSelf = v.did === this.selfDid;
378
+ const seenAt = this.peerLastSeenAtMs.get(v.did);
379
+ const reachable = isSelf ? !this.halted && !this.stopped : Boolean(seenAt && nowMs - seenAt <= this.quorumLeaseTimeoutMs);
380
+ return {
381
+ index: idx,
382
+ did: v.did,
383
+ publicKey: v.publicKey,
384
+ isSelf,
385
+ isCurrentViewLeader: v.did === currentLeader.did,
386
+ reachable,
387
+ lastSeenAgoMs: isSelf ? 0 : seenAt !== void 0 ? Math.max(0, nowMs - seenAt) : null,
388
+ ...includePrivate ? {
389
+ rpcUrl: v.rpcUrl,
390
+ consensusUrl: v.consensusUrl
391
+ } : {}
392
+ };
393
+ });
394
+ return {
395
+ mode: "hotstuff",
396
+ consensusMode: "hotstuff",
397
+ selfDid: this.selfDid,
398
+ writePolicy: this.writePolicy,
399
+ currentView: this.currentView,
400
+ currentLeaderDid: currentLeader.did,
401
+ isCurrentViewLeader: currentLeader.did === this.selfDid,
402
+ writableLocally: this.shouldHandleWriteLocally(),
403
+ quorumThreshold: this.clusterConfig.quorumThreshold ?? 3,
404
+ totalValidators: this.validators.length,
405
+ livePeerCount,
406
+ quorumLeaseValid,
407
+ quorumLeaseTimeoutMs: this.quorumLeaseTimeoutMs,
408
+ consecutiveViewTimeouts: this.consecutiveViewTimeouts,
409
+ ...includePrivate ? {
410
+ consensusBindHost: this.consensusBindHost,
411
+ consensusPort: this.boundPort || this.configuredConsensusPort
412
+ } : {},
413
+ highQC: this.highQC ? {
414
+ viewNumber: this.highQC.viewNumber,
415
+ height: this.highQC.height,
416
+ sequence: this.highQC.sequence,
417
+ proposer: this.highQC.proposer,
418
+ signerCount: this.highQC.signatures.length,
419
+ checkpointHash: this.highQC.checkpointHash
420
+ } : null,
421
+ lockedQC: this.lockedQC ? {
422
+ viewNumber: this.lockedQC.viewNumber,
423
+ height: this.lockedQC.height,
424
+ sequence: this.lockedQC.sequence,
425
+ proposer: this.lockedQC.proposer,
426
+ signerCount: this.lockedQC.signatures.length,
427
+ checkpointHash: this.lockedQC.checkpointHash
428
+ } : null,
429
+ lastTC: this.lastTC ? {
430
+ viewNumber: this.lastTC.viewNumber,
431
+ signerCount: this.lastTC.signatures.length,
432
+ highestQCView: this.lastTC.highestQC?.viewNumber ?? null
433
+ } : null,
434
+ validators
435
+ };
436
+ }
437
+ async triggerSyncOrProbe() {
438
+ if (this.halted) throw new CustomError("NODE_HALTED", `Validator node is halted: ${this.haltReason || "verification error"}`);
439
+ const promoted = await this.leaderRouter.probeAndPromoteLeader();
440
+ return {
441
+ mode: "hotstuff",
442
+ currentView: this.currentView,
443
+ currentLeaderDid: getLeaderForView(this.clusterConfig, this.currentView).did,
444
+ livePeerCount: this.computeLivePeerCount(),
445
+ quorumLeaseValid: this.refreshQuorumLease(),
446
+ hasReachablePeerLeader: Boolean(promoted)
447
+ };
448
+ }
449
+ haltFailClosed(reason) {
450
+ this.halted = true;
451
+ this.haltReason = reason;
452
+ this.clearTimers();
453
+ this.resolver.logger.error("CRITICAL: HotStuffNodeRuntime halted fail-closed", {
454
+ chainId: this.chainId,
455
+ validatorDid: this.selfDid,
456
+ haltReason: reason
457
+ });
458
+ }
459
+ computeLivePeerCount(nowMs = Date.now()) {
460
+ let live = 0;
461
+ for (const peer of this.peerValidators) {
462
+ const seenAt = this.peerLastSeenAtMs.get(peer.did);
463
+ if (seenAt !== void 0 && nowMs - seenAt <= this.quorumLeaseTimeoutMs) live++;
464
+ }
465
+ return live;
466
+ }
467
+ refreshQuorumLease(nowMs = Date.now()) {
468
+ const threshold = this.clusterConfig.quorumThreshold ?? 3;
469
+ if (this.computeLivePeerCount(nowMs) + 1 >= threshold) {
470
+ this.quorumContactObserved = true;
471
+ this.quorumLeaseValid = true;
472
+ return true;
473
+ }
474
+ if (!this.quorumContactObserved && this.startedAtMs > 0 && nowMs - this.startedAtMs <= this.startupQuorumGraceMs && this.currentView === 0 && this.highQC === null) return this.quorumLeaseValid;
475
+ this.quorumLeaseValid = false;
476
+ return false;
477
+ }
478
+ recordAuthenticatedPeerContact(peerDid, nowMs = Date.now()) {
479
+ if (peerDid && peerDid !== this.selfDid && this.validatorMap.has(peerDid)) {
480
+ this.peerLastSeenAtMs.set(peerDid, nowMs);
481
+ this.refreshQuorumLease(nowMs);
482
+ }
483
+ }
484
+ hasSpentTurnInView(viewNumber) {
485
+ return Math.max(this.lastSelfVotedView, this.lastSelfPreparedView) >= viewNumber;
486
+ }
487
+ advanceCurrentViewTo(nextView) {
488
+ if (nextView <= this.currentView) return;
489
+ this.currentView = nextView;
490
+ this.currentViewEnteredAtMs = Date.now();
491
+ if (this.pendingDemandForView < nextView) this.pendingDemandForView = -1;
492
+ for (const v of Array.from(this.demandSendersByView.keys())) if (v < nextView) this.demandSendersByView.delete(v);
493
+ for (const waiter of Array.from(this.viewAdvanceWaiters)) if (nextView > waiter.stalledView) {
494
+ this.viewAdvanceWaiters.delete(waiter);
495
+ waiter.resolve();
496
+ }
497
+ }
498
+ shouldSuppressHeartbeatKeepalive(lock, viewNumber, nowMs = Date.now()) {
499
+ const highQcHeight = this.highQC?.height ?? 0;
500
+ if ((lock?.lastTimedOutView ?? -1) >= viewNumber) return true;
501
+ if ((lock?.lastPreparedHeight ?? 0) > highQcHeight && (lock?.lastPreparedView ?? -1) >= viewNumber) return true;
502
+ if ((lock?.lastVotedHeight ?? 0) > highQcHeight && (lock?.lastVotedView ?? -1) >= viewNumber) return true;
503
+ if (this.lastTC && this.lastTC.viewNumber === viewNumber - 1 && this.lastTC.lockedCheckpoint && this.lastTC.lockedCheckpoint.height === highQcHeight + 1) return true;
504
+ if (this.pendingDemandForView === viewNumber) return true;
505
+ if (nowMs - this.currentViewEnteredAtMs >= this.maxEmptyViewMs) return true;
506
+ return false;
507
+ }
508
+ shouldHandleWriteLocally() {
509
+ if (this.halted || this.stopped) return false;
510
+ if (!this.refreshQuorumLease()) return false;
511
+ if (this.hasSpentTurnInView(this.currentView) || this.unleadableView === this.currentView) return false;
512
+ return getLeaderForView(this.clusterConfig, this.currentView).did === this.selfDid;
513
+ }
514
+ async isSynced() {
515
+ if (this.halted || this.stopped) return false;
516
+ const localHeight = (await this.resolver.ledger.getCheckpoint().catch(() => null))?.height ?? 0;
517
+ return (this.highQC?.height ?? 0) - localHeight <= 2;
518
+ }
519
+ async getFollowerStatus() {
520
+ const [localSequence, latestCp, synced] = await Promise.all([
521
+ this.resolver.ledger.getLatestSequence(),
522
+ this.resolver.ledger.getCheckpoint(),
523
+ this.isSynced()
524
+ ]);
525
+ const localStateCommitHash = typeof this.resolver.statedb.getCurrentCommitHash === "function" ? await this.resolver.statedb.getCurrentCommitHash() : "UNKNOWN";
526
+ const currentLeader = getLeaderForView(this.clusterConfig, this.currentView);
527
+ const upstreamSeq = this.highQC ? Math.max(localSequence, this.highQC.sequence) : localSequence;
528
+ return {
529
+ chainId: this.chainId,
530
+ nodeRole: "validator",
531
+ writePolicy: this.writePolicy,
532
+ syncMode: "primary",
533
+ synced,
534
+ halted: this.halted,
535
+ haltReason: this.haltReason,
536
+ localSequence,
537
+ upstreamSequence: upstreamSeq,
538
+ syncLagEntries: Math.max(0, upstreamSeq - localSequence),
539
+ verifiedCheckpointHeight: latestCp?.height ?? 0,
540
+ verifiedCheckpointHash: latestCp?.hash ?? null,
541
+ localStateCommitHash,
542
+ activeLeaderUrl: currentLeader.rpcUrl,
543
+ lastUpstreamSuccessAt: (/* @__PURE__ */ new Date()).toISOString()
544
+ };
545
+ }
546
+ async triggerClientDemandViewChange(stalledView) {
547
+ if (this.halted || this.stopped) return;
548
+ if (this.currentView === stalledView) {
549
+ this.pendingDemandForView = Math.max(this.pendingDemandForView, stalledView);
550
+ const t = setTimeout(() => {
551
+ this.onViewTimerExpired(stalledView).catch(() => void 0);
552
+ }, 0);
553
+ if (typeof t.unref === "function") t.unref();
554
+ await Promise.allSettled(this.peerValidators.map((peer) => this.sendConsensusJson(peer, "POST", "/consensus/demand", { viewNumber: stalledView }, Math.min(1e3, this.httpTimeoutMs), MAX_CONTROL_ROUTE_BYTES)));
555
+ }
556
+ if (this.currentView > stalledView) return;
557
+ const waitMs = Math.min(4500, Math.max(400, this.baseViewTimeoutMs * 3));
558
+ await new Promise((resolve) => {
559
+ const waiter = {
560
+ stalledView,
561
+ resolve: () => {}
562
+ };
563
+ const timer = setTimeout(() => {
564
+ this.viewAdvanceWaiters.delete(waiter);
565
+ resolve();
566
+ }, waitMs);
567
+ if (typeof timer.unref === "function") timer.unref();
568
+ waiter.resolve = () => {
569
+ clearTimeout(timer);
570
+ resolve();
571
+ };
572
+ this.viewAdvanceWaiters.add(waiter);
573
+ });
574
+ }
575
+ async forwardSendTx(args, ctx) {
576
+ if (this.halted) throw new CustomError("NODE_HALTED", `Validator node is halted fail-closed: ${this.haltReason || "verification error"}`);
577
+ try {
578
+ return await this.leaderRouter.forwardSendTx(args, ctx);
579
+ } catch (firstErr) {
580
+ if (this.halted || this.stopped || !this.refreshQuorumLease()) throw firstErr;
581
+ const stalledView = this.currentView;
582
+ await this.triggerClientDemandViewChange(stalledView);
583
+ if (this.shouldHandleWriteLocally() && typeof this.resolver.sendTx === "function") return this.resolver.sendTx(args, ctx);
584
+ return this.leaderRouter.forwardSendTx(args, ctx);
585
+ }
586
+ }
587
+ runExclusive(fn) {
588
+ const prev = this.mutexTail;
589
+ let release;
590
+ const gate = new Promise((resolve) => {
591
+ release = resolve;
592
+ });
593
+ this.mutexTail = prev.then(() => gate);
594
+ return prev.then(async () => {
595
+ this.inConsensusLock = true;
596
+ try {
597
+ return await fn();
598
+ } finally {
599
+ this.inConsensusLock = false;
600
+ release();
601
+ }
602
+ });
603
+ }
604
+ /**
605
+ * Serialized local leader execution wrapper (#1712):
606
+ * 1. Acquires `runExclusive` so `SqliteStateDB` never overlaps dry-run/replay transactions.
607
+ * 2. Catches up finalized segments if behind `highQC`, and recovers any pending `lastTC.lockedCheckpoint`
608
+ * BEFORE `executor.execute` opens `statedb.runAsLambda`.
609
+ * 3. Asserts active view leadership + valid quorum lease.
610
+ * 4. Runs `fn()` (`executor.execute`), then broadcasts `/consensus/commit` after releasing `runExclusive`.
611
+ */
612
+ async executeWithConsensusLock(fn) {
613
+ let segmentsToBroadcast = [];
614
+ let result;
615
+ try {
616
+ result = await this.runExclusive(async () => {
617
+ this.pendingBroadcastSegments = [];
618
+ this.activeProposalSlot = null;
619
+ await this.ensureReadyToLeadLocked();
620
+ try {
621
+ return await fn();
622
+ } finally {
623
+ if (this.pendingBroadcastSegments.length > 0) segmentsToBroadcast = [...this.pendingBroadcastSegments];
624
+ this.activeProposalSlot = null;
625
+ this.pendingBroadcastSegments = [];
626
+ }
627
+ });
628
+ } catch (err) {
629
+ if (segmentsToBroadcast.length > 0) await this.broadcastCommittedSegments(segmentsToBroadcast).catch(() => void 0);
630
+ throw err;
631
+ }
632
+ if (segmentsToBroadcast.length > 0) await this.broadcastCommittedSegments(segmentsToBroadcast).catch(() => void 0);
633
+ return result;
634
+ }
635
+ async ensureReadyToLeadLocked() {
636
+ if (this.halted || this.stopped) throw new ConsensusAbortError("CONSENSUS_ABORTED", "Validator runtime is halted or stopped");
637
+ const localHeight = (await this.resolver.ledger.getCheckpoint())?.height ?? 0;
638
+ if (this.highQC && localHeight < this.highQC.height) await this.catchUpToHeightLocked(this.highQC.height);
639
+ if (!this.refreshQuorumLease()) throw new ConsensusAbortError("CONSENSUS_QUORUM_LOST", `Validator ${this.selfDid} lacks active BFT quorum lease`);
640
+ let leader = getLeaderForView(this.clusterConfig, this.currentView);
641
+ if (leader.did !== this.selfDid) throw new ConsensusAbortError("CONSENSUS_NOT_LEADER", `Validator ${this.selfDid} is not leader for view ${this.currentView} (leader=${leader.did})`);
642
+ if (this.hasSpentTurnInView(this.currentView) || this.unleadableView === this.currentView) throw new ConsensusAbortError("CONSENSUS_VIEW_CHANGING", `Validator ${this.selfDid} cannot lead view ${this.currentView}; awaiting view change`);
643
+ const expectedNextHeight = (this.highQC?.height ?? 0) + 1;
644
+ if (this.lastTC && this.lastTC.viewNumber === this.currentView - 1 && this.lastTC.lockedCheckpoint && this.lastTC.lockedCheckpoint.height === expectedNextHeight) {
645
+ let recoveredSegment = null;
646
+ try {
647
+ recoveredSegment = await this.recoverLockedCheckpointLocked(this.lastTC);
648
+ } catch (err) {
649
+ this.markCurrentViewUnleadableAndScheduleTimeout();
650
+ throw err;
651
+ }
652
+ if (recoveredSegment) this.pendingBroadcastSegments.push(recoveredSegment);
653
+ else if (((await this.resolver.ledger.getCheckpoint())?.height ?? 0) < expectedNextHeight) {
654
+ this.markCurrentViewUnleadableAndScheduleTimeout();
655
+ throw new ConsensusAbortError("CONSENSUS_VIEW_CHANGING", `Validator ${this.selfDid} could not recover lockedCheckpoint at height ${expectedNextHeight} in view ${this.currentView}; rotating view`);
656
+ }
657
+ leader = getLeaderForView(this.clusterConfig, this.currentView);
658
+ if (leader.did !== this.selfDid) {
659
+ const toFlush = [...this.pendingBroadcastSegments];
660
+ this.pendingBroadcastSegments = [];
661
+ this.broadcastCommittedSegments(toFlush).catch(() => void 0);
662
+ throw new ConsensusAbortError("CONSENSUS_NOT_LEADER", `Recovered lockedCheckpoint at view ${this.currentView - 1}; leadership rotated to ${leader.did} for view ${this.currentView}`);
663
+ }
664
+ if (this.hasSpentTurnInView(this.currentView)) throw new ConsensusAbortError("CONSENSUS_VIEW_CHANGING", `Validator ${this.selfDid} already voted in view ${this.currentView}; awaiting view change`);
665
+ }
666
+ }
667
+ async prepareProposalSlot() {
668
+ if (!this.inConsensusLock) throw new ConsensusAbortError("CONSENSUS_ABORTED", "prepareProposalSlot must execute inside executeWithConsensusLock");
669
+ if (this.halted || this.stopped) throw new ConsensusAbortError("CONSENSUS_ABORTED", "Validator runtime is halted or stopped");
670
+ if (!this.refreshQuorumLease()) throw new ConsensusAbortError("CONSENSUS_QUORUM_LOST", "Validator lost BFT quorum lease");
671
+ if (getLeaderForView(this.clusterConfig, this.currentView).did !== this.selfDid) throw new ConsensusAbortError("CONSENSUS_NOT_LEADER", `Validator ${this.selfDid} is not leader for view ${this.currentView}`);
672
+ if (this.hasSpentTurnInView(this.currentView)) throw new ConsensusAbortError("CONSENSUS_VIEW_CHANGING", `Validator ${this.selfDid} already voted in view ${this.currentView}; awaiting view change`);
673
+ const latestCp = await this.resolver.ledger.getCheckpoint();
674
+ const sequence = (latestCp?.sequence ?? 0) + 1;
675
+ const timestampMs = Math.max(Date.now(), (latestCp?.timestamp ?? 0) + 1);
676
+ this.activeProposalSlot = {
677
+ sequence,
678
+ timestampMs,
679
+ viewNumber: this.currentView
680
+ };
681
+ return {
682
+ sequence,
683
+ timestampMs
684
+ };
685
+ }
686
+ async commitStagedEntry(params) {
687
+ if (!this.inConsensusLock || !this.activeProposalSlot) throw new ConsensusAbortError("CONSENSUS_ABORTED", "Missing active consensus proposal slot");
688
+ if (this.halted || this.stopped) throw new ConsensusAbortError("CONSENSUS_ABORTED", "Validator runtime is halted or stopped");
689
+ const slot = this.activeProposalSlot;
690
+ if (this.currentView !== slot.viewNumber) throw new ConsensusAbortError("CONSENSUS_VIEW_CHANGING", `Consensus view advanced during execution (${slot.viewNumber} -> ${this.currentView})`);
691
+ if (getLeaderForView(this.clusterConfig, this.currentView).did !== this.selfDid) throw new ConsensusAbortError("CONSENSUS_NOT_LEADER", `Validator ${this.selfDid} is no longer leader for view ${this.currentView}`);
692
+ const latestCp = await this.resolver.ledger.getCheckpoint();
693
+ const prevSequence = latestCp?.sequence ?? 0;
694
+ if (slot.sequence !== prevSequence + 1 || params.sequence !== slot.sequence) throw new ConsensusAbortError("CONSENSUS_ABORTED", `Proposal slot sequence (${slot.sequence}) no longer matches ledger tip + 1 (${prevSequence + 1})`);
695
+ const txInput = params.txInput;
696
+ const v2Cutoff = this.resolver.ledger.getEntryHashV2From?.() ?? 1;
697
+ const hashVersion = slot.sequence >= v2Cutoff ? 2 : 1;
698
+ const entryHash = computeEntryHash(slot.sequence, txInput.txRaw, params.stateCommitHash, hashVersion);
699
+ const entry = {
700
+ sequence: slot.sequence,
701
+ timestamp: slot.timestampMs,
702
+ hash: txInput.txHash.toUpperCase(),
703
+ from: txInput.from,
704
+ nonce: Number(txInput.nonce),
705
+ pk: txInput.pk,
706
+ signature: txInput.signature,
707
+ txRaw: txInput.txRaw,
708
+ tx: txInput.tx,
709
+ txType: txInput.txType,
710
+ ...txInput.txExtra !== void 0 ? { txExtra: txInput.txExtra } : {},
711
+ chainId: this.chainId,
712
+ entryHash,
713
+ stateCommitHash: params.stateCommitHash,
714
+ finalized: true
715
+ };
716
+ const tree = new IncrementalMerkleTree();
717
+ tree.append(entryHash);
718
+ const txRoot = tree.getHexRoot();
719
+ const unsignedCp = {
720
+ height: (latestCp?.height ?? 0) + 1,
721
+ sequence: slot.sequence,
722
+ prevSequence,
723
+ txCount: 1,
724
+ timestamp: slot.timestampMs,
725
+ txRoot,
726
+ stateRoot: params.stateCommitHash,
727
+ prevCheckpoint: latestCp?.hash ?? null,
728
+ proposer: this.selfDid
729
+ };
730
+ const cpHash = computeCheckpointHash(unsignedCp);
731
+ const cpSigRaw = await this.signDigest(cpHash);
732
+ const cpSignature = cpSigRaw.startsWith("0x") ? cpSigRaw : `0x${cpSigRaw}`;
733
+ const baseCheckpoint = {
734
+ ...unsignedCp,
735
+ hash: cpHash,
736
+ signature: cpSignature
737
+ };
738
+ const segmentContentHash = computeSegmentContentHash({
739
+ chainId: this.chainId,
740
+ checkpoint: baseCheckpoint,
741
+ entries: [entry]
742
+ });
743
+ const segCommitDigest = computeSegmentCommitmentDigest(cpHash, segmentContentHash);
744
+ const segCommitSigRaw = await this.signDigest(segCommitDigest);
745
+ const checkpoint = {
746
+ ...baseCheckpoint,
747
+ segmentContentHash,
748
+ segmentCommitmentSignature: segCommitSigRaw.startsWith("0x") ? segCommitSigRaw : `0x${segCommitSigRaw}`
749
+ };
750
+ const effectiveHighQC = selectHighestQC([this.highQC, this.lastTC?.winningHighQC]);
751
+ const needsTC = Boolean(this.lastTC) && this.lastTC.viewNumber === this.currentView - 1 && (effectiveHighQC ? this.currentView > effectiveHighQC.viewNumber + 1 : this.currentView > 0);
752
+ let proposal;
753
+ try {
754
+ proposal = await createHotStuffProposal({
755
+ config: this.clusterConfig,
756
+ viewNumber: this.currentView,
757
+ checkpoint,
758
+ leaderWallet: this.validatorWallet,
759
+ leaderDid: this.selfDid,
760
+ highQC: effectiveHighQC,
761
+ timeoutCert: needsTC ? this.lastTC : null,
762
+ timestamp: slot.timestampMs
763
+ });
764
+ } catch (err) {
765
+ if (err?.isConsensusAbort === true) throw err;
766
+ throw new ConsensusAbortError("CONSENSUS_ABORTED", err instanceof Error ? err.message : String(err));
767
+ }
768
+ const preVoteCheck = await canVoterPrepareProposal({
769
+ config: this.clusterConfig,
770
+ proposal,
771
+ voterDid: this.selfDid,
772
+ lockedQC: this.lockedQC,
773
+ voterStateStore: this.stateStore
774
+ });
775
+ if (!preVoteCheck.ok) throw new ConsensusAbortError("CONSENSUS_ABORTED", preVoteCheck.reason || "Leader voter lock rejected proposal");
776
+ await this.stateStore.saveUncommittedProposalEntries?.({
777
+ chainId: this.chainId,
778
+ voterDid: this.selfDid,
779
+ checkpointHash: checkpoint.hash,
780
+ height: checkpoint.height,
781
+ entries: [entry],
782
+ checkpoint,
783
+ updatedAt: slot.timestampMs
784
+ });
785
+ this.lastSelfPreparedView = Math.max(this.lastSelfPreparedView, proposal.viewNumber);
786
+ let qc;
787
+ try {
788
+ qc = await this.collectVotesAndFormQC(proposal, [entry], params.stateCommitHash, slot.timestampMs);
789
+ } catch (err) {
790
+ if (this.currentView === proposal.viewNumber) {
791
+ const stalledView = proposal.viewNumber;
792
+ const t = setTimeout(() => {
793
+ this.onViewTimerExpired(stalledView).catch(() => void 0);
794
+ }, 0);
795
+ if (typeof t.unref === "function") t.unref();
796
+ }
797
+ if (err?.isConsensusAbort === true) throw err;
798
+ throw new ConsensusAbortError("CONSENSUS_ABORTED", err instanceof Error ? err.message : String(err));
799
+ }
800
+ const sealedCheckpoint = {
801
+ ...checkpoint,
802
+ qc
803
+ };
804
+ const finalizedSegment = {
805
+ chainId: this.chainId,
806
+ checkpoint: sealedCheckpoint,
807
+ entries: [entry]
808
+ };
809
+ await this.resolver.ledger.importSegment(finalizedSegment, {
810
+ hotstuffClusterConfig: this.clusterConfig,
811
+ verifyStateRoot: true
812
+ });
813
+ this.lockedQC = selectHighestQC([this.lockedQC, effectiveHighQC]);
814
+ this.highQC = selectHighestQC([this.highQC, qc]);
815
+ this.advanceCurrentViewTo(qc.viewNumber + 1);
816
+ this.currentViewEnteredAtMs = Date.now();
817
+ this.pendingDemandForView = -1;
818
+ this.consecutiveViewTimeouts = 0;
819
+ this.leaderRouter.advanceMinVerifiedCheckpointHeight(sealedCheckpoint.height);
820
+ try {
821
+ await this.stateStore.saveRuntimeState?.({
822
+ chainId: this.chainId,
823
+ voterDid: this.selfDid,
824
+ currentView: this.currentView,
825
+ lockedQC: this.lockedQC,
826
+ highQC: this.highQC,
827
+ lastTC: this.lastTC,
828
+ pruneUncommittedUpToHeight: sealedCheckpoint.height
829
+ });
830
+ } catch (saveErr) {
831
+ this.resolver.logger.warn("Failed to persist post-commit HotStuff runtime metadata; continuing commit", {
832
+ chainId: this.chainId,
833
+ height: sealedCheckpoint.height,
834
+ error: saveErr instanceof Error ? saveErr.message : String(saveErr)
835
+ });
836
+ }
837
+ this.scheduleViewTimeout();
838
+ this.pendingBroadcastSegments.push(finalizedSegment);
839
+ return entry;
840
+ }
841
+ async collectVotesAndFormQC(proposal, entries, expectedStateRoot, createdAtMs) {
842
+ const threshold = this.clusterConfig.quorumThreshold ?? 3;
843
+ const peerPrepareVotes = [];
844
+ const seenPreparePeerDids = /* @__PURE__ */ new Set();
845
+ let reachablePeers = 0;
846
+ await Promise.all(this.peerValidators.map(async (peer) => {
847
+ try {
848
+ const res = await this.sendConsensusJson(peer, "POST", "/consensus/propose", {
849
+ proposal,
850
+ entries
851
+ }, this.proposalTimeoutMs, MAX_CONTROL_ROUTE_BYTES);
852
+ if (res.authenticated) reachablePeers++;
853
+ if (res.body?.highQC) this.tryAbsorbRemoteQC(res.body.highQC);
854
+ if (res.body?.lastTC) this.tryAbsorbRemoteTC(res.body.lastTC);
855
+ if (res.status === 200 && res.body?.prepareVote) {
856
+ const pv = res.body.prepareVote;
857
+ if (pv.voterDid === peer.did && pv.viewNumber === proposal.viewNumber && normalizeHexCompare(pv.checkpointHash) === normalizeHexCompare(proposal.checkpoint.hash) && !seenPreparePeerDids.has(peer.did) && verifyHotStuffPrepareVote(pv, this.clusterConfig).ok) {
858
+ seenPreparePeerDids.add(peer.did);
859
+ peerPrepareVotes.push(pv);
860
+ if (this.onLeaderReplicaVoteReceived) await this.onLeaderReplicaVoteReceived({
861
+ leaderDid: this.selfDid,
862
+ voterDid: peer.did,
863
+ viewNumber: proposal.viewNumber,
864
+ height: proposal.checkpoint.height,
865
+ voteCountIncludingSelf: peerPrepareVotes.length + 1
866
+ });
867
+ }
868
+ }
869
+ } catch {}
870
+ }));
871
+ if (reachablePeers + 1 >= threshold) {
872
+ this.quorumContactObserved = true;
873
+ this.quorumLeaseValid = true;
874
+ } else this.quorumLeaseValid = false;
875
+ if (this.currentView > proposal.viewNumber) throw new ConsensusAbortError("CONSENSUS_VIEW_CHANGING", `Stepped down during proposal view ${proposal.viewNumber} -> ${this.currentView}`);
876
+ if (peerPrepareVotes.length + 1 < threshold) throw new ConsensusAbortError(reachablePeers + 1 < threshold ? "CONSENSUS_QUORUM_LOST" : "CONSENSUS_ABORTED", `Failed to reach ${threshold} BFT PrepareVotes for height ${proposal.checkpoint.height} in view ${proposal.viewNumber} (got ${peerPrepareVotes.length + 1}, reachable=${reachablePeers + 1})`);
877
+ let selfPrepareVote;
878
+ try {
879
+ selfPrepareVote = await verifyProposalAndCreatePrepareVote({
880
+ config: this.clusterConfig,
881
+ proposal,
882
+ entries,
883
+ voterWallet: this.validatorWallet,
884
+ voterDid: this.selfDid,
885
+ lockedQC: this.lockedQC,
886
+ voterStateStore: this.stateStore,
887
+ expectedStateRoot,
888
+ requireSegmentCommitment: true,
889
+ timestamp: createdAtMs
890
+ });
891
+ } catch (err) {
892
+ if (err?.isConsensusAbort === true) throw err;
893
+ throw new ConsensusAbortError("CONSENSUS_ABORTED", err instanceof Error ? err.message : String(err));
894
+ }
895
+ const prepareQC = aggregatePrepareQuorumCertificate({
896
+ config: this.clusterConfig,
897
+ proposal,
898
+ votes: [selfPrepareVote, ...peerPrepareVotes],
899
+ createdAt: createdAtMs
900
+ });
901
+ const effectiveParentQC = selectHighestQC([proposal.highQC, proposal.timeoutCert?.winningHighQC]);
902
+ const peerCommitVotes = [];
903
+ const seenCommitPeerDids = /* @__PURE__ */ new Set();
904
+ let precommitReachablePeers = 0;
905
+ await Promise.all(this.peerValidators.map(async (peer) => {
906
+ try {
907
+ let res = await this.sendConsensusJson(peer, "POST", "/consensus/precommit", {
908
+ viewNumber: proposal.viewNumber,
909
+ prepareQC,
910
+ checkpoint: proposal.checkpoint,
911
+ parentHighQC: effectiveParentQC
912
+ }, this.proposalTimeoutMs, MAX_CONTROL_ROUTE_BYTES);
913
+ if (res.status === 409 && res.body?.code === "MISSING_UNCOMMITTED_ENTRIES") res = await this.sendConsensusJson(peer, "POST", "/consensus/precommit", {
914
+ viewNumber: proposal.viewNumber,
915
+ prepareQC,
916
+ checkpoint: proposal.checkpoint,
917
+ parentHighQC: effectiveParentQC,
918
+ entries
919
+ }, this.proposalTimeoutMs, MAX_CONTROL_ROUTE_BYTES);
920
+ if (res.authenticated) precommitReachablePeers++;
921
+ if (res.body?.highQC) this.tryAbsorbRemoteQC(res.body.highQC);
922
+ if (res.body?.lastTC) this.tryAbsorbRemoteTC(res.body.lastTC);
923
+ if (res.status === 200 && res.body?.vote) {
924
+ const cv = res.body.vote;
925
+ if (cv.voterDid === peer.did && cv.viewNumber === proposal.viewNumber && normalizeHexCompare(cv.checkpointHash) === normalizeHexCompare(proposal.checkpoint.hash) && !seenCommitPeerDids.has(peer.did) && verifyHotStuffVote(cv, this.clusterConfig).ok) {
926
+ seenCommitPeerDids.add(peer.did);
927
+ peerCommitVotes.push(cv);
928
+ if (this.onLeaderReplicaPrecommitReceived) await this.onLeaderReplicaPrecommitReceived({
929
+ leaderDid: this.selfDid,
930
+ voterDid: peer.did,
931
+ viewNumber: proposal.viewNumber,
932
+ height: proposal.checkpoint.height,
933
+ commitVoteCountIncludingSelf: peerCommitVotes.length + 1
934
+ });
935
+ }
936
+ }
937
+ } catch {}
938
+ }));
939
+ if (precommitReachablePeers + 1 < threshold) this.quorumLeaseValid = false;
940
+ if (this.currentView > proposal.viewNumber) throw new ConsensusAbortError("CONSENSUS_VIEW_CHANGING", `Stepped down during precommit view ${proposal.viewNumber} -> ${this.currentView}`);
941
+ if (peerCommitVotes.length + 1 < threshold) throw new ConsensusAbortError(precommitReachablePeers + 1 < threshold ? "CONSENSUS_QUORUM_LOST" : "CONSENSUS_ABORTED", `Failed to reach ${threshold} BFT CommitVotes for height ${proposal.checkpoint.height} in view ${proposal.viewNumber} (got ${peerCommitVotes.length + 1}, reachable=${precommitReachablePeers + 1})`);
942
+ const commitTimestampMs = Math.max(createdAtMs, Date.now());
943
+ let selfCommitVote;
944
+ try {
945
+ selfCommitVote = await verifyPrepareQCAndCreateCommitVote({
946
+ config: this.clusterConfig,
947
+ prepareQC,
948
+ checkpoint: proposal.checkpoint,
949
+ voterWallet: this.validatorWallet,
950
+ voterDid: this.selfDid,
951
+ parentHighQC: effectiveParentQC,
952
+ voterStateStore: this.stateStore,
953
+ timestamp: commitTimestampMs
954
+ });
955
+ } catch (err) {
956
+ if (err?.isConsensusAbort === true) throw err;
957
+ throw new ConsensusAbortError("CONSENSUS_ABORTED", err instanceof Error ? err.message : String(err));
958
+ }
959
+ this.lastSelfVotedView = Math.max(this.lastSelfVotedView, selfCommitVote.viewNumber);
960
+ return aggregateQuorumCertificate({
961
+ config: this.clusterConfig,
962
+ proposal,
963
+ votes: [selfCommitVote, ...peerCommitVotes],
964
+ createdAt: commitTimestampMs
965
+ });
966
+ }
967
+ async hasValidCheckpointSegmentCommitment(cp, expectedSegContentHash) {
968
+ if (!cp || !cp.segmentContentHash || !cp.segmentCommitmentSignature) return false;
969
+ if (normalizeHexCompare(cp.segmentContentHash) !== normalizeHexCompare(expectedSegContentHash)) return false;
970
+ const cpProposerMember = this.clusterConfig.validators.find((v) => v.did === cp.proposer);
971
+ if (!cpProposerMember) return false;
972
+ return verifySegmentCommitmentSignature(cp, expectedSegContentHash, cpProposerMember.publicKey, cpProposerMember.did);
973
+ }
974
+ async recoverLockedCheckpointLocked(tc) {
975
+ let lockedCp = tc.lockedCheckpoint;
976
+ if (!lockedCp) return null;
977
+ const localCp = await this.resolver.ledger.getCheckpoint();
978
+ if (localCp && localCp.height >= lockedCp.height) return null;
979
+ let entries = await this.stateStore.getUncommittedProposalEntries?.(this.chainId, this.selfDid, lockedCp.hash);
980
+ const savedCp = await this.stateStore.getUncommittedProposalCheckpoint?.(this.chainId, this.selfDid, lockedCp.hash);
981
+ let expectedSegContentHash = entries && entries.length === lockedCp.txCount ? computeSegmentContentHash({
982
+ chainId: this.chainId,
983
+ checkpoint: lockedCp,
984
+ entries
985
+ }) : "";
986
+ let hasValidCommitment = expectedSegContentHash ? await this.hasValidCheckpointSegmentCommitment(lockedCp, expectedSegContentHash) : false;
987
+ if (!hasValidCommitment && expectedSegContentHash && savedCp && normalizeHexCompare(savedCp.hash) === normalizeHexCompare(lockedCp.hash) && await this.hasValidCheckpointSegmentCommitment(savedCp, expectedSegContentHash)) {
988
+ lockedCp = {
989
+ ...lockedCp,
990
+ segmentContentHash: savedCp.segmentContentHash,
991
+ segmentCommitmentSignature: savedCp.segmentCommitmentSignature
992
+ };
993
+ hasValidCommitment = true;
994
+ }
995
+ if (!entries || entries.length !== lockedCp.txCount || !hasValidCommitment) for (const peer of this.peerValidators) try {
996
+ const res = await this.sendConsensusJson(peer, "GET", `/consensus/uncommitted?checkpointHash=${encodeURIComponent(lockedCp.hash)}`, void 0, this.httpTimeoutMs, MAX_DATA_ROUTE_BYTES);
997
+ if (!res.authenticated || res.status !== 200) continue;
998
+ if (!entries || entries.length !== lockedCp.txCount) {
999
+ if (!Array.isArray(res.body?.entries) || res.body.entries.length !== lockedCp.txCount) continue;
1000
+ const dryRun$1 = await this.replayer.dryRunVerifyEntries(res.body.entries, {
1001
+ expectedPrevSequence: lockedCp.prevSequence,
1002
+ prevStateRoot: localCp?.stateRoot ?? null
1003
+ }).catch(() => null);
1004
+ if (!dryRun$1 || normalizeHexCompare(dryRun$1.derivedStateRoot) !== normalizeHexCompare(lockedCp.stateRoot)) continue;
1005
+ const tree = new IncrementalMerkleTree();
1006
+ for (const h of dryRun$1.entryHashes) tree.append(h);
1007
+ if (normalizeHexCompare(tree.getHexRoot()) !== normalizeHexCompare(lockedCp.txRoot)) continue;
1008
+ entries = res.body.entries;
1009
+ expectedSegContentHash = computeSegmentContentHash({
1010
+ chainId: this.chainId,
1011
+ checkpoint: lockedCp,
1012
+ entries
1013
+ });
1014
+ hasValidCommitment = await this.hasValidCheckpointSegmentCommitment(lockedCp, expectedSegContentHash);
1015
+ if (!hasValidCommitment && savedCp && normalizeHexCompare(savedCp.hash) === normalizeHexCompare(lockedCp.hash) && await this.hasValidCheckpointSegmentCommitment(savedCp, expectedSegContentHash)) {
1016
+ lockedCp = {
1017
+ ...lockedCp,
1018
+ segmentContentHash: savedCp.segmentContentHash,
1019
+ segmentCommitmentSignature: savedCp.segmentCommitmentSignature
1020
+ };
1021
+ hasValidCommitment = true;
1022
+ }
1023
+ }
1024
+ if (!hasValidCommitment && expectedSegContentHash && res.body?.checkpoint && normalizeHexCompare(res.body.checkpoint.hash) === normalizeHexCompare(lockedCp.hash) && await this.hasValidCheckpointSegmentCommitment(res.body.checkpoint, expectedSegContentHash)) {
1025
+ lockedCp = {
1026
+ ...lockedCp,
1027
+ segmentContentHash: res.body.checkpoint.segmentContentHash,
1028
+ segmentCommitmentSignature: res.body.checkpoint.segmentCommitmentSignature
1029
+ };
1030
+ hasValidCommitment = true;
1031
+ }
1032
+ if (entries && entries.length === lockedCp.txCount && hasValidCommitment) break;
1033
+ } catch {}
1034
+ if (!entries || entries.length !== lockedCp.txCount) throw new ConsensusAbortError("CONSENSUS_ABORTED", `Unable to fetch uncommitted entries for lockedCheckpoint ${lockedCp.hash} at height ${lockedCp.height}`);
1035
+ if (!hasValidCommitment) throw new ConsensusAbortError("CONSENSUS_ABORTED", `Unable to recover verified segmentCommitmentSignature for lockedCheckpoint ${lockedCp.hash} at height ${lockedCp.height}`);
1036
+ const dryRun = await this.replayer.dryRunVerifyEntries(entries, {
1037
+ expectedPrevSequence: lockedCp.prevSequence,
1038
+ prevStateRoot: localCp?.stateRoot ?? null
1039
+ });
1040
+ if (normalizeHexCompare(dryRun.derivedStateRoot) !== normalizeHexCompare(lockedCp.stateRoot)) throw new ConsensusAbortError("CONSENSUS_ABORTED", `Recovered lockedCheckpoint stateRoot mismatch at height ${lockedCp.height}`);
1041
+ await this.stateStore.saveUncommittedProposalEntries?.({
1042
+ chainId: this.chainId,
1043
+ voterDid: this.selfDid,
1044
+ checkpointHash: lockedCp.hash,
1045
+ height: lockedCp.height,
1046
+ entries,
1047
+ checkpoint: lockedCp
1048
+ });
1049
+ const effectiveHighQC = selectHighestQC([this.highQC, tc.winningHighQC]);
1050
+ const nowMs = Date.now();
1051
+ let proposal;
1052
+ try {
1053
+ proposal = await createHotStuffProposal({
1054
+ config: this.clusterConfig,
1055
+ viewNumber: this.currentView,
1056
+ checkpoint: lockedCp,
1057
+ leaderWallet: this.validatorWallet,
1058
+ leaderDid: this.selfDid,
1059
+ highQC: effectiveHighQC,
1060
+ timeoutCert: tc,
1061
+ timestamp: nowMs
1062
+ });
1063
+ } catch (err) {
1064
+ if (err?.isConsensusAbort === true) throw err;
1065
+ throw new ConsensusAbortError("CONSENSUS_ABORTED", err instanceof Error ? err.message : String(err));
1066
+ }
1067
+ const preVoteCheck = await canVoterPrepareProposal({
1068
+ config: this.clusterConfig,
1069
+ proposal,
1070
+ voterDid: this.selfDid,
1071
+ lockedQC: this.lockedQC,
1072
+ voterStateStore: this.stateStore
1073
+ });
1074
+ if (!preVoteCheck.ok) throw new ConsensusAbortError("CONSENSUS_ABORTED", preVoteCheck.reason || "Leader voter lock rejected recovery proposal");
1075
+ this.lastSelfPreparedView = Math.max(this.lastSelfPreparedView, proposal.viewNumber);
1076
+ let qc;
1077
+ try {
1078
+ qc = await this.collectVotesAndFormQC(proposal, entries, dryRun.derivedStateRoot ?? void 0, nowMs);
1079
+ } catch (err) {
1080
+ if (this.currentView === proposal.viewNumber) {
1081
+ const stalledView = proposal.viewNumber;
1082
+ const t = setTimeout(() => {
1083
+ this.onViewTimerExpired(stalledView).catch(() => void 0);
1084
+ }, 0);
1085
+ if (typeof t.unref === "function") t.unref();
1086
+ }
1087
+ if (err?.isConsensusAbort === true) throw err;
1088
+ throw new ConsensusAbortError("CONSENSUS_ABORTED", err instanceof Error ? err.message : String(err));
1089
+ }
1090
+ const sealedCheckpoint = {
1091
+ ...lockedCp,
1092
+ qc
1093
+ };
1094
+ const finalizedSegment = {
1095
+ chainId: this.chainId,
1096
+ checkpoint: sealedCheckpoint,
1097
+ entries
1098
+ };
1099
+ if (typeof this.resolver.ledger.verifySegmentForImport === "function") await this.resolver.ledger.verifySegmentForImport(finalizedSegment, {
1100
+ hotstuffClusterConfig: this.clusterConfig,
1101
+ verifyStateRoot: true,
1102
+ allowAheadLocalSequence: true
1103
+ });
1104
+ await this.resolver.ledger.importSegment(finalizedSegment, {
1105
+ hotstuffClusterConfig: this.clusterConfig,
1106
+ verifyStateRoot: true
1107
+ });
1108
+ for (const entry of entries) await this.replayer.replayEntry(entry, { appendToLedger: false });
1109
+ this.lockedQC = selectHighestQC([this.lockedQC, effectiveHighQC]);
1110
+ this.highQC = selectHighestQC([this.highQC, qc]);
1111
+ this.advanceCurrentViewTo(qc.viewNumber + 1);
1112
+ this.currentViewEnteredAtMs = Date.now();
1113
+ this.pendingDemandForView = -1;
1114
+ this.consecutiveViewTimeouts = 0;
1115
+ this.leaderRouter.advanceMinVerifiedCheckpointHeight(sealedCheckpoint.height);
1116
+ try {
1117
+ await this.stateStore.saveRuntimeState?.({
1118
+ chainId: this.chainId,
1119
+ voterDid: this.selfDid,
1120
+ currentView: this.currentView,
1121
+ lockedQC: this.lockedQC,
1122
+ highQC: this.highQC,
1123
+ lastTC: this.lastTC,
1124
+ pruneUncommittedUpToHeight: sealedCheckpoint.height
1125
+ });
1126
+ } catch {}
1127
+ this.scheduleViewTimeout();
1128
+ return finalizedSegment;
1129
+ }
1130
+ async broadcastCommittedSegments(segments) {
1131
+ for (const segment of segments) {
1132
+ const nextView = (segment.checkpoint.qc?.viewNumber ?? this.currentView - 1) + 1;
1133
+ const nextLeader = getLeaderForView(this.clusterConfig, nextView);
1134
+ const tasks = this.peerValidators.map(async (peer) => {
1135
+ try {
1136
+ await this.sendConsensusJson(peer, "POST", "/consensus/commit", { segment }, this.httpTimeoutMs, MAX_CONTROL_ROUTE_BYTES);
1137
+ } catch {}
1138
+ });
1139
+ const nextLeaderIdx = this.peerValidators.findIndex((p) => p.did === nextLeader.did);
1140
+ if (nextLeaderIdx >= 0) await Promise.race([tasks[nextLeaderIdx], new Promise((resolve) => {
1141
+ const t = setTimeout(resolve, NEXT_LEADER_COMMIT_WAIT_MS);
1142
+ if (typeof t.unref === "function") t.unref();
1143
+ })]);
1144
+ Promise.allSettled(tasks);
1145
+ }
1146
+ }
1147
+ tryAbsorbRemoteQC(candidateQC) {
1148
+ if (!candidateQC) return false;
1149
+ if (!verifyQuorumCertificate(candidateQC, this.clusterConfig).ok) return false;
1150
+ const prevView = this.currentView;
1151
+ const prevHeight = this.highQC?.height ?? 0;
1152
+ this.highQC = selectHighestQC([this.highQC, candidateQC]);
1153
+ const heightAdvanced = (this.highQC?.height ?? 0) > prevHeight;
1154
+ if (this.highQC && this.highQC.viewNumber + 1 > this.currentView) {
1155
+ this.advanceCurrentViewTo(this.highQC.viewNumber + 1);
1156
+ this.consecutiveViewTimeouts = 0;
1157
+ } else if (heightAdvanced) {
1158
+ this.currentViewEnteredAtMs = Date.now();
1159
+ this.pendingDemandForView = -1;
1160
+ this.consecutiveViewTimeouts = 0;
1161
+ }
1162
+ return this.currentView > prevView || heightAdvanced;
1163
+ }
1164
+ isBetterTimeoutCertificate(nextTC) {
1165
+ if (!this.lastTC) return true;
1166
+ if (nextTC.viewNumber > this.lastTC.viewNumber) return true;
1167
+ if (nextTC.viewNumber === this.lastTC.viewNumber && nextTC.signatures.length > this.lastTC.signatures.length) return true;
1168
+ return false;
1169
+ }
1170
+ markCurrentViewUnleadableAndScheduleTimeout() {
1171
+ const stalledView = this.currentView;
1172
+ this.unleadableView = stalledView;
1173
+ const t = setTimeout(() => {
1174
+ this.onViewTimerExpired(stalledView).catch(() => void 0);
1175
+ }, 0);
1176
+ if (typeof t.unref === "function") t.unref();
1177
+ }
1178
+ tryAbsorbRemoteTC(candidateTC) {
1179
+ if (!candidateTC) return false;
1180
+ if (!verifyTimeoutCertificate(candidateTC, this.clusterConfig).ok) return false;
1181
+ if (candidateTC.winningHighQC) this.tryAbsorbRemoteQC(candidateTC.winningHighQC);
1182
+ const prevView = this.currentView;
1183
+ let upgradedSameViewTC = false;
1184
+ if (this.isBetterTimeoutCertificate(candidateTC)) {
1185
+ upgradedSameViewTC = Boolean(this.lastTC && candidateTC.viewNumber === this.lastTC.viewNumber);
1186
+ this.lastTC = candidateTC;
1187
+ if (upgradedSameViewTC && this.unleadableView === candidateTC.viewNumber + 1) this.unleadableView = -1;
1188
+ }
1189
+ if (candidateTC.viewNumber + 1 > this.currentView) {
1190
+ this.advanceCurrentViewTo(candidateTC.viewNumber + 1);
1191
+ this.consecutiveViewTimeouts = 0;
1192
+ }
1193
+ return this.currentView > prevView || upgradedSameViewTC;
1194
+ }
1195
+ async catchUpToHeightLocked(targetHeight) {
1196
+ let localCp = await this.resolver.ledger.getCheckpoint();
1197
+ let currentHeight = localCp?.height ?? 0;
1198
+ if (currentHeight >= targetHeight || this.peerValidators.length === 0) return;
1199
+ let rotationOffset = Math.max(0, this.currentView) % this.peerValidators.length;
1200
+ while (!this.halted && !this.stopped && currentHeight < targetHeight) {
1201
+ const fromHeight = currentHeight + 1;
1202
+ const toHeight = Math.min(targetHeight, fromHeight + MAX_CATCHUP_SEGMENTS_PER_REQUEST - 1);
1203
+ let importedInBatch = 0;
1204
+ for (let i = 0; i < this.peerValidators.length; i++) {
1205
+ const peer = this.peerValidators[(rotationOffset + i) % this.peerValidators.length];
1206
+ let candidateSegments = null;
1207
+ try {
1208
+ const res = await this.sendConsensusJson(peer, "GET", `/consensus/entries?fromHeight=${fromHeight}&toHeight=${toHeight}`, void 0, this.httpTimeoutMs, MAX_DATA_ROUTE_BYTES);
1209
+ if (res.authenticated && res.status === 200 && Array.isArray(res.body?.segments) && res.body.segments.length > 0) candidateSegments = res.body.segments;
1210
+ } catch {}
1211
+ if (!candidateSegments) continue;
1212
+ let importedFromPeer = 0;
1213
+ for (const seg of candidateSegments) {
1214
+ if (!seg || seg.chainId !== this.chainId || !seg.checkpoint || seg.checkpoint.height !== currentHeight + 1 || !Array.isArray(seg.entries)) break;
1215
+ if (!verifyCheckpointQuorumCertificate(seg.checkpoint, this.clusterConfig).ok) break;
1216
+ try {
1217
+ if (typeof this.resolver.ledger.verifySegmentForImport === "function") await this.resolver.ledger.verifySegmentForImport(seg, {
1218
+ hotstuffClusterConfig: this.clusterConfig,
1219
+ verifyStateRoot: true,
1220
+ allowAheadLocalSequence: true
1221
+ });
1222
+ if (seg.entries.length > 0 && typeof this.resolver.statedb.runWithinDryRunSession === "function") {
1223
+ if (normalizeHexCompare((await this.replayer.dryRunVerifyEntries(seg.entries, {
1224
+ expectedPrevSequence: localCp?.sequence ?? 0,
1225
+ prevStateRoot: localCp?.stateRoot ?? null
1226
+ })).derivedStateRoot) !== normalizeHexCompare(seg.checkpoint.stateRoot)) break;
1227
+ }
1228
+ } catch {
1229
+ break;
1230
+ }
1231
+ await this.resolver.ledger.importSegment(seg, {
1232
+ hotstuffClusterConfig: this.clusterConfig,
1233
+ verifyStateRoot: true
1234
+ });
1235
+ for (const entry of seg.entries) await this.replayer.replayEntry(entry, { appendToLedger: false });
1236
+ this.tryAbsorbRemoteQC(seg.checkpoint.qc);
1237
+ currentHeight = seg.checkpoint.height;
1238
+ localCp = seg.checkpoint;
1239
+ this.leaderRouter.advanceMinVerifiedCheckpointHeight(currentHeight);
1240
+ importedFromPeer++;
1241
+ importedInBatch++;
1242
+ }
1243
+ if (importedFromPeer > 0) {
1244
+ rotationOffset = (rotationOffset + i) % this.peerValidators.length;
1245
+ break;
1246
+ }
1247
+ }
1248
+ if (importedInBatch === 0) break;
1249
+ }
1250
+ if (localCp && localCp.height > 0) try {
1251
+ await this.stateStore.saveRuntimeState?.({
1252
+ chainId: this.chainId,
1253
+ voterDid: this.selfDid,
1254
+ currentView: this.currentView,
1255
+ lockedQC: this.lockedQC,
1256
+ highQC: this.highQC,
1257
+ lastTC: this.lastTC,
1258
+ pruneUncommittedUpToHeight: localCp.height
1259
+ });
1260
+ } catch {}
1261
+ }
1262
+ async reconcileCrashWindowLocked() {
1263
+ const latestSeq = await this.resolver.ledger.getLatestSequence();
1264
+ if (latestSeq <= 0) return;
1265
+ const latestEntry = await this.resolver.ledger.getBySequence(latestSeq);
1266
+ if (!latestEntry || latestEntry.finalized !== true) return;
1267
+ const currentCommit = typeof this.resolver.statedb.getCurrentCommitHash === "function" ? await this.resolver.statedb.getCurrentCommitHash() : null;
1268
+ if (!currentCommit || currentCommit === "UNKNOWN") return;
1269
+ const normCurrentCommit = normalizeHexCompare(currentCommit);
1270
+ const isGenesisState = currentCommit === "GENESIS" || !normCurrentCommit;
1271
+ if (!isGenesisState && latestEntry.stateCommitHash && normCurrentCommit === normalizeHexCompare(latestEntry.stateCommitHash)) return;
1272
+ const unappliedReversed = [];
1273
+ let matchedBase = false;
1274
+ for (let seq = latestSeq; seq >= 1; seq--) {
1275
+ const entry = await this.resolver.ledger.getBySequence(seq);
1276
+ if (!entry || entry.finalized !== true) break;
1277
+ const normEntryCommit = normalizeHexCompare(entry.stateCommitHash);
1278
+ if (!isGenesisState && normEntryCommit && normEntryCommit === normCurrentCommit) {
1279
+ matchedBase = true;
1280
+ break;
1281
+ }
1282
+ unappliedReversed.push(entry);
1283
+ if (seq === 1 && isGenesisState) matchedBase = true;
1284
+ }
1285
+ const unappliedOrdered = [...unappliedReversed].reverse();
1286
+ if (!matchedBase && unappliedOrdered.length > 0 && unappliedOrdered[0].sequence === 1 && typeof this.resolver.statedb.runWithinDryRunSession === "function") {
1287
+ const dryRun = await this.replayer.dryRunVerifyEntries(unappliedOrdered, {
1288
+ expectedPrevSequence: 0,
1289
+ prevStateRoot: currentCommit
1290
+ }).catch(() => null);
1291
+ if (dryRun && latestEntry.stateCommitHash && normalizeHexCompare(dryRun.derivedStateRoot) === normalizeHexCompare(latestEntry.stateCommitHash)) matchedBase = true;
1292
+ }
1293
+ if (!matchedBase) throw new CustomError("STATE_COMMIT_MISMATCH", `Validator crash reconciliation could not align statedb commit (${currentCommit}) with finalized ledger tip (seq=${latestSeq})`);
1294
+ for (const entry of unappliedOrdered) await this.replayer.replayEntry(entry, { appendToLedger: false });
1295
+ }
1296
+ async signHttpEnvelope(params) {
1297
+ const digest = buildCanonicalHttpAuthDigest({
1298
+ kind: params.kind,
1299
+ chainId: this.chainId,
1300
+ methodOrStatus: params.methodOrStatus,
1301
+ pathWithQuery: params.pathWithQuery,
1302
+ senderDid: this.selfDid,
1303
+ timestampMs: params.timestampMs,
1304
+ nonce: params.nonce,
1305
+ bodyBytes: params.bodyBytes
1306
+ });
1307
+ const sig = await this.signDigest(digest);
1308
+ return sig.startsWith("0x") ? sig : `0x${sig}`;
1309
+ }
1310
+ isReplayKeyActive(key, nowMs) {
1311
+ const existingExpiry = this.replayCache.get(key);
1312
+ return existingExpiry !== void 0 && existingExpiry > nowMs;
1313
+ }
1314
+ pruneAndCheckReplayKey(key, nowMs) {
1315
+ if (this.isReplayKeyActive(key, nowMs)) return false;
1316
+ if (this.replayCache.size >= MAX_REPLAY_CACHE_ENTRIES) for (const [k, exp] of this.replayCache.entries()) {
1317
+ if (exp <= nowMs || this.replayCache.size >= MAX_REPLAY_CACHE_ENTRIES) this.replayCache.delete(k);
1318
+ if (this.replayCache.size < MAX_REPLAY_CACHE_ENTRIES - 64) break;
1319
+ }
1320
+ this.replayCache.set(key, nowMs + REPLAY_TTL_MS);
1321
+ return true;
1322
+ }
1323
+ precheckIncomingHttpAuthHeaders(req) {
1324
+ const chainHeader = String(req.headers["x-ocap-consensus-chain-id"] ?? "").trim();
1325
+ const senderDid = String(req.headers["x-ocap-consensus-sender"] ?? "").trim();
1326
+ const tsRaw = String(req.headers["x-ocap-consensus-timestamp"] ?? "").trim();
1327
+ const nonce = String(req.headers["x-ocap-consensus-nonce"] ?? "").trim();
1328
+ const signature = String(req.headers["x-ocap-consensus-signature"] ?? "").trim();
1329
+ if (!chainHeader || !senderDid || !tsRaw || !nonce || !signature) return {
1330
+ ok: false,
1331
+ status: 401,
1332
+ code: "CONSENSUS_AUTH_REQUIRED",
1333
+ error: "Missing mandatory X-Ocap-Consensus-* authentication headers"
1334
+ };
1335
+ if (chainHeader !== this.chainId) return {
1336
+ ok: false,
1337
+ status: 403,
1338
+ code: "CHAIN_ID_MISMATCH",
1339
+ error: `Consensus chainId mismatch: expected ${this.chainId}, got ${chainHeader}`
1340
+ };
1341
+ if (!this.validatorMap.has(senderDid)) return {
1342
+ ok: false,
1343
+ status: 403,
1344
+ code: "UNKNOWN_VALIDATOR",
1345
+ error: `Sender ${senderDid} is not in HOTSTUFF_VALIDATORS allowlist`
1346
+ };
1347
+ if (senderDid === this.selfDid) return {
1348
+ ok: false,
1349
+ status: 403,
1350
+ code: "SELF_SENDER_REJECTED",
1351
+ error: `Loopback/self sender ${senderDid} is not permitted on peer consensus HTTP listener`
1352
+ };
1353
+ if (!/^[0-9a-f]{16,64}$/i.test(nonce)) return {
1354
+ ok: false,
1355
+ status: 401,
1356
+ code: "INVALID_NONCE",
1357
+ error: "Invalid X-Ocap-Consensus-Nonce format"
1358
+ };
1359
+ const timestampMs = Number(tsRaw);
1360
+ const nowMs = Date.now();
1361
+ if (!Number.isSafeInteger(timestampMs) || Math.abs(nowMs - timestampMs) > MAX_CLOCK_SKEW_MS) return {
1362
+ ok: false,
1363
+ status: 401,
1364
+ code: "CLOCK_SKEW_EXCEEDED",
1365
+ error: "Consensus request timestamp outside ±60s clock skew window"
1366
+ };
1367
+ const replayKey = `req:${senderDid}:${timestampMs}:${nonce}`;
1368
+ if (this.isReplayKeyActive(replayKey, nowMs)) return {
1369
+ ok: false,
1370
+ status: 401,
1371
+ code: "REPLAY_DETECTED",
1372
+ error: "Replayed consensus HTTP request rejected"
1373
+ };
1374
+ return {
1375
+ ok: true,
1376
+ senderDid,
1377
+ timestampMs,
1378
+ nonce,
1379
+ signature
1380
+ };
1381
+ }
1382
+ async verifyIncomingHttpAuth(req, pathWithQuery, bodyBytes, prechecked) {
1383
+ const headerCheck = prechecked ?? this.precheckIncomingHttpAuthHeaders(req);
1384
+ if ("ok" in headerCheck && headerCheck.ok === false) return headerCheck;
1385
+ const { senderDid, timestampMs, nonce, signature } = headerCheck;
1386
+ const nowMs = Date.now();
1387
+ if (Math.abs(nowMs - timestampMs) > MAX_CLOCK_SKEW_MS) return {
1388
+ ok: false,
1389
+ status: 401,
1390
+ code: "CLOCK_SKEW_EXCEEDED",
1391
+ error: "Consensus request timestamp outside ±60s clock skew window"
1392
+ };
1393
+ const digest = buildCanonicalHttpAuthDigest({
1394
+ kind: "req",
1395
+ chainId: this.chainId,
1396
+ methodOrStatus: req.method || "GET",
1397
+ pathWithQuery,
1398
+ senderDid,
1399
+ timestampMs,
1400
+ nonce,
1401
+ bodyBytes
1402
+ });
1403
+ if (!await this.trustAnchorVerify(digest, signature, senderDid)) return {
1404
+ ok: false,
1405
+ status: 401,
1406
+ code: "INVALID_CONSENSUS_SIGNATURE",
1407
+ error: `Invalid consensus Ed25519 signature from ${senderDid}`
1408
+ };
1409
+ const replayKey = `req:${senderDid}:${timestampMs}:${nonce}`;
1410
+ if (!this.pruneAndCheckReplayKey(replayKey, nowMs)) return {
1411
+ ok: false,
1412
+ status: 401,
1413
+ code: "REPLAY_DETECTED",
1414
+ error: "Replayed consensus HTTP request rejected"
1415
+ };
1416
+ this.recordAuthenticatedPeerContact(senderDid, nowMs);
1417
+ return {
1418
+ ok: true,
1419
+ senderDid
1420
+ };
1421
+ }
1422
+ async sendAuthenticatedJsonResponse(res, pathWithQuery, statusCode, payload) {
1423
+ const json = JSON.stringify(payload);
1424
+ const bodyBytes = new Uint8Array(Buffer.from(json, "utf8"));
1425
+ const timestampMs = Date.now();
1426
+ const nonce = randomBytes(16).toString("hex");
1427
+ const signature = await this.signHttpEnvelope({
1428
+ kind: "res",
1429
+ methodOrStatus: String(statusCode),
1430
+ pathWithQuery,
1431
+ timestampMs,
1432
+ nonce,
1433
+ bodyBytes
1434
+ });
1435
+ res.statusCode = statusCode;
1436
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
1437
+ res.setHeader("X-Content-Type-Options", "nosniff");
1438
+ res.setHeader("Cache-Control", "no-store");
1439
+ res.setHeader("X-Ocap-Consensus-Chain-Id", this.chainId);
1440
+ res.setHeader("X-Ocap-Consensus-Sender", this.selfDid);
1441
+ res.setHeader("X-Ocap-Consensus-Timestamp", String(timestampMs));
1442
+ res.setHeader("X-Ocap-Consensus-Nonce", nonce);
1443
+ res.setHeader("X-Ocap-Consensus-Signature", signature);
1444
+ res.end(Buffer.from(bodyBytes));
1445
+ }
1446
+ async sendConsensusJson(peer, method, pathWithQuery, bodyObj, timeoutMs, maxResponseBytes) {
1447
+ const url = `${peer.consensusUrl}${pathWithQuery}`;
1448
+ if (this.onOutboundConsensusRequest) await this.onOutboundConsensusRequest({
1449
+ fromDid: this.selfDid,
1450
+ toDid: peer.did,
1451
+ method,
1452
+ pathWithQuery,
1453
+ url
1454
+ });
1455
+ const bodyText = bodyObj !== void 0 ? JSON.stringify(bodyObj) : "";
1456
+ const bodyBytes = bodyText ? new Uint8Array(Buffer.from(bodyText, "utf8")) : new Uint8Array(0);
1457
+ const timestampMs = Date.now();
1458
+ const nonce = randomBytes(16).toString("hex");
1459
+ const signature = await this.signHttpEnvelope({
1460
+ kind: "req",
1461
+ methodOrStatus: method,
1462
+ pathWithQuery,
1463
+ timestampMs,
1464
+ nonce,
1465
+ bodyBytes
1466
+ });
1467
+ const response = await this.fetchImpl(url, {
1468
+ method,
1469
+ headers: {
1470
+ accept: "application/json",
1471
+ ...bodyText ? { "content-type": "application/json" } : {},
1472
+ "x-ocap-consensus-chain-id": this.chainId,
1473
+ "x-ocap-consensus-sender": this.selfDid,
1474
+ "x-ocap-consensus-timestamp": String(timestampMs),
1475
+ "x-ocap-consensus-nonce": nonce,
1476
+ "x-ocap-consensus-signature": signature
1477
+ },
1478
+ ...bodyText ? { body: bodyText } : {},
1479
+ redirect: "error",
1480
+ signal: AbortSignal.timeout(timeoutMs)
1481
+ });
1482
+ const respBytes = await readFetchResponseBytesBounded(response, maxResponseBytes);
1483
+ let authenticated = false;
1484
+ const respSender = String(response.headers.get("x-ocap-consensus-sender") ?? "").trim();
1485
+ const respChain = String(response.headers.get("x-ocap-consensus-chain-id") ?? "").trim();
1486
+ const respTs = Number(response.headers.get("x-ocap-consensus-timestamp") ?? "");
1487
+ const respNonce = String(response.headers.get("x-ocap-consensus-nonce") ?? "").trim();
1488
+ const respSig = String(response.headers.get("x-ocap-consensus-signature") ?? "").trim();
1489
+ const nowMs = Date.now();
1490
+ if (respSender === peer.did && respChain === this.chainId && Number.isSafeInteger(respTs) && Math.abs(nowMs - respTs) <= MAX_CLOCK_SKEW_MS && /^[0-9a-f]{16,64}$/i.test(respNonce) && respSig) {
1491
+ const respDigest = buildCanonicalHttpAuthDigest({
1492
+ kind: "res",
1493
+ chainId: this.chainId,
1494
+ methodOrStatus: String(response.status),
1495
+ pathWithQuery,
1496
+ senderDid: peer.did,
1497
+ timestampMs: respTs,
1498
+ nonce: respNonce,
1499
+ bodyBytes: respBytes
1500
+ });
1501
+ if (await this.trustAnchorVerify(respDigest, respSig, peer.did)) {
1502
+ const replayKey = `res:${peer.did}:${respTs}:${respNonce}`;
1503
+ if (this.pruneAndCheckReplayKey(replayKey, nowMs)) {
1504
+ authenticated = true;
1505
+ this.recordAuthenticatedPeerContact(peer.did, nowMs);
1506
+ }
1507
+ }
1508
+ }
1509
+ const decoded = respBytes.byteLength > 0 ? new TextDecoder().decode(respBytes) : "";
1510
+ const parsed = decoded ? JSON.parse(decoded) : {};
1511
+ return {
1512
+ status: response.status,
1513
+ body: parsed,
1514
+ authenticated
1515
+ };
1516
+ }
1517
+ async handleConsensusHttpRequest(req, res) {
1518
+ const rawUrl = req.url || "/";
1519
+ let parsedUrl;
1520
+ try {
1521
+ parsedUrl = new URL(rawUrl, "http://localhost");
1522
+ } catch {
1523
+ res.statusCode = 400;
1524
+ res.end(JSON.stringify({
1525
+ code: "INVALID_URL",
1526
+ error: "Malformed URL"
1527
+ }));
1528
+ return;
1529
+ }
1530
+ const pathname = parsedUrl.pathname;
1531
+ const pathWithQuery = `${pathname}${parsedUrl.search}`;
1532
+ const isDataRoute = pathname === "/consensus/propose" || pathname === "/consensus/precommit" || pathname === "/consensus/commit" || pathname === "/consensus/entries" || pathname === "/consensus/uncommitted";
1533
+ if (!isDataRoute && !(pathname === "/consensus/timeout" || pathname === "/consensus/new-view" || pathname === "/consensus/heartbeat" || pathname === "/consensus/demand" || pathname === "/consensus/status")) {
1534
+ res.statusCode = 404;
1535
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
1536
+ res.end(JSON.stringify({
1537
+ code: "NOT_FOUND",
1538
+ error: `Unknown consensus endpoint: ${pathname}`
1539
+ }));
1540
+ return;
1541
+ }
1542
+ const prechecked = this.precheckIncomingHttpAuthHeaders(req);
1543
+ if (!prechecked.ok) {
1544
+ req.resume();
1545
+ res.statusCode = prechecked.status;
1546
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
1547
+ res.end(JSON.stringify({
1548
+ code: prechecked.code,
1549
+ error: prechecked.error
1550
+ }));
1551
+ return;
1552
+ }
1553
+ const bodyRead = await readIncomingBytesBounded(req, isDataRoute ? MAX_DATA_ROUTE_BYTES : MAX_CONTROL_ROUTE_BYTES);
1554
+ if (!bodyRead.ok) {
1555
+ res.statusCode = bodyRead.status;
1556
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
1557
+ res.end(JSON.stringify({
1558
+ code: bodyRead.code,
1559
+ error: bodyRead.error
1560
+ }));
1561
+ return;
1562
+ }
1563
+ const auth = await this.verifyIncomingHttpAuth(req, pathWithQuery, bodyRead.bytes, prechecked);
1564
+ if (!auth.ok) {
1565
+ res.statusCode = auth.status;
1566
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
1567
+ res.end(JSON.stringify({
1568
+ code: auth.code,
1569
+ error: auth.error
1570
+ }));
1571
+ return;
1572
+ }
1573
+ if (this.halted) {
1574
+ await this.sendAuthenticatedJsonResponse(res, pathWithQuery, 503, {
1575
+ code: "NODE_HALTED",
1576
+ error: this.haltReason || "Validator halted fail-closed"
1577
+ });
1578
+ return;
1579
+ }
1580
+ let bodyJson = {};
1581
+ if (bodyRead.bytes.byteLength > 0) try {
1582
+ bodyJson = JSON.parse(new TextDecoder().decode(bodyRead.bytes));
1583
+ } catch {
1584
+ await this.sendAuthenticatedJsonResponse(res, pathWithQuery, 400, {
1585
+ code: "INVALID_JSON",
1586
+ error: "Malformed JSON body"
1587
+ });
1588
+ return;
1589
+ }
1590
+ try {
1591
+ if (req.method === "GET" && pathname === "/consensus/status") {
1592
+ const status = await this.buildConsensusStatus();
1593
+ await this.sendAuthenticatedJsonResponse(res, pathWithQuery, 200, status);
1594
+ return;
1595
+ }
1596
+ if (req.method === "GET" && pathname === "/consensus/entries") {
1597
+ const fromHeight = Number(parsedUrl.searchParams.get("fromHeight") ?? "0");
1598
+ const toHeight = Number(parsedUrl.searchParams.get("toHeight") ?? String(fromHeight));
1599
+ if (!Number.isSafeInteger(fromHeight) || !Number.isSafeInteger(toHeight) || fromHeight < 1 || toHeight < fromHeight) {
1600
+ await this.sendAuthenticatedJsonResponse(res, pathWithQuery, 400, {
1601
+ code: "INVALID_PARAMS",
1602
+ error: "Invalid fromHeight / toHeight"
1603
+ });
1604
+ return;
1605
+ }
1606
+ const cappedTo = Math.min(toHeight, fromHeight + MAX_CATCHUP_SEGMENTS_PER_REQUEST - 1);
1607
+ const segments = await this.readFinalizedSegmentsRange(fromHeight, cappedTo);
1608
+ await this.sendAuthenticatedJsonResponse(res, pathWithQuery, 200, { segments });
1609
+ return;
1610
+ }
1611
+ if (req.method === "GET" && pathname === "/consensus/uncommitted") {
1612
+ const checkpointHash = String(parsedUrl.searchParams.get("checkpointHash") ?? "").trim();
1613
+ const [entries, checkpoint] = checkpointHash ? await Promise.all([this.stateStore.getUncommittedProposalEntries?.(this.chainId, this.selfDid, checkpointHash), this.stateStore.getUncommittedProposalCheckpoint?.(this.chainId, this.selfDid, checkpointHash)]) : [null, null];
1614
+ if (!entries) {
1615
+ await this.sendAuthenticatedJsonResponse(res, pathWithQuery, 404, {
1616
+ code: "NOT_FOUND",
1617
+ error: "Uncommitted entries not found"
1618
+ });
1619
+ return;
1620
+ }
1621
+ await this.sendAuthenticatedJsonResponse(res, pathWithQuery, 200, {
1622
+ entries,
1623
+ ...checkpoint ? { checkpoint } : {}
1624
+ });
1625
+ return;
1626
+ }
1627
+ if (req.method === "POST" && pathname === "/consensus/heartbeat") {
1628
+ const result = await this.handleHeartbeat(auth.senderDid, bodyJson);
1629
+ await this.sendAuthenticatedJsonResponse(res, pathWithQuery, 200, result);
1630
+ return;
1631
+ }
1632
+ if (req.method === "POST" && pathname === "/consensus/propose") {
1633
+ const result = await this.handlePropose(auth.senderDid, bodyJson);
1634
+ await this.sendAuthenticatedJsonResponse(res, pathWithQuery, result.status, result.body);
1635
+ return;
1636
+ }
1637
+ if (req.method === "POST" && pathname === "/consensus/precommit") {
1638
+ const result = await this.handlePrecommit(auth.senderDid, bodyJson);
1639
+ await this.sendAuthenticatedJsonResponse(res, pathWithQuery, result.status, result.body);
1640
+ return;
1641
+ }
1642
+ if (req.method === "POST" && pathname === "/consensus/demand") {
1643
+ const result = await this.handleDemand(auth.senderDid, bodyJson);
1644
+ await this.sendAuthenticatedJsonResponse(res, pathWithQuery, result.status, result.body);
1645
+ return;
1646
+ }
1647
+ if (req.method === "POST" && pathname === "/consensus/commit") {
1648
+ const result = await this.handleCommit(bodyJson);
1649
+ await this.sendAuthenticatedJsonResponse(res, pathWithQuery, result.status, result.body);
1650
+ return;
1651
+ }
1652
+ if (req.method === "POST" && pathname === "/consensus/timeout") {
1653
+ const result = await this.handleTimeoutMessage(bodyJson);
1654
+ await this.sendAuthenticatedJsonResponse(res, pathWithQuery, result.status, result.body);
1655
+ return;
1656
+ }
1657
+ if (req.method === "POST" && pathname === "/consensus/new-view") {
1658
+ const result = await this.handleNewView(bodyJson);
1659
+ await this.sendAuthenticatedJsonResponse(res, pathWithQuery, result.status, result.body);
1660
+ return;
1661
+ }
1662
+ await this.sendAuthenticatedJsonResponse(res, pathWithQuery, 405, {
1663
+ code: "METHOD_NOT_ALLOWED",
1664
+ error: `Unsupported method ${String(req.method)} for ${pathname}`
1665
+ });
1666
+ } catch (err) {
1667
+ const message = err instanceof Error ? err.message : String(err);
1668
+ await this.sendAuthenticatedJsonResponse(res, pathWithQuery, 500, {
1669
+ code: err?.code || "CONSENSUS_INTERNAL_ERROR",
1670
+ error: message
1671
+ });
1672
+ }
1673
+ }
1674
+ async buildConsensusStatus() {
1675
+ const [latestSequence, latestCp] = await Promise.all([this.resolver.ledger.getLatestSequence(), this.resolver.ledger.getCheckpoint()]);
1676
+ return {
1677
+ chainId: this.chainId,
1678
+ validatorDid: this.selfDid,
1679
+ currentView: this.currentView,
1680
+ latestSequence,
1681
+ checkpointHeight: latestCp?.height ?? 0,
1682
+ highQC: this.highQC,
1683
+ lockedQC: this.lockedQC,
1684
+ lastTC: this.lastTC,
1685
+ quorumLeaseValid: this.refreshQuorumLease()
1686
+ };
1687
+ }
1688
+ async readFinalizedSegmentsRange(fromHeight, toHeight) {
1689
+ const out = [];
1690
+ for (let h = fromHeight; h <= toHeight; h++) {
1691
+ const cp = await this.resolver.ledger.getCheckpoint(h);
1692
+ if (!cp || !cp.qc) break;
1693
+ const entries = cp.sequence > cp.prevSequence ? await this.resolver.ledger.getRange(cp.prevSequence + 1, cp.sequence) : [];
1694
+ if (entries.length !== cp.txCount) break;
1695
+ out.push({
1696
+ chainId: this.chainId,
1697
+ checkpoint: cp,
1698
+ entries
1699
+ });
1700
+ }
1701
+ return out;
1702
+ }
1703
+ async handleHeartbeat(senderDid, body) {
1704
+ const hbHighQC = body.highQC ?? null;
1705
+ const hbLastTC = body.lastTC ?? null;
1706
+ const hbView = typeof body.viewNumber === "number" ? body.viewNumber : -1;
1707
+ const advancedFromQC = this.tryAbsorbRemoteQC(hbHighQC);
1708
+ const advancedFromTC = this.tryAbsorbRemoteTC(hbLastTC);
1709
+ if (advancedFromQC || advancedFromTC) this.runExclusive(async () => {
1710
+ if (this.highQC) await this.catchUpToHeightLocked(this.highQC.height);
1711
+ }).catch(() => void 0);
1712
+ if (senderDid === getLeaderForView(this.clusterConfig, this.currentView).did && hbView === this.currentView) {
1713
+ const lock = await Promise.resolve(this.stateStore.getLock(this.chainId, this.selfDid)).catch(() => null);
1714
+ if (!this.shouldSuppressHeartbeatKeepalive(lock, this.currentView)) this.scheduleViewTimeout();
1715
+ }
1716
+ return {
1717
+ ok: true,
1718
+ currentView: this.currentView,
1719
+ highQC: this.highQC,
1720
+ lastTC: this.lastTC
1721
+ };
1722
+ }
1723
+ async handleDemand(senderDid, body) {
1724
+ const demandView = Number(body.viewNumber);
1725
+ if (!Number.isSafeInteger(demandView) || demandView < 0) return {
1726
+ status: 400,
1727
+ body: {
1728
+ code: "INVALID_DEMAND_VIEW",
1729
+ error: "Invalid viewNumber in /consensus/demand"
1730
+ }
1731
+ };
1732
+ if (demandView !== this.currentView) return {
1733
+ status: 200,
1734
+ body: {
1735
+ ok: true,
1736
+ ignored: true,
1737
+ currentView: this.currentView,
1738
+ highQC: this.highQC
1739
+ }
1740
+ };
1741
+ let senders = this.demandSendersByView.get(demandView);
1742
+ if (!senders) {
1743
+ senders = /* @__PURE__ */ new Set();
1744
+ this.demandSendersByView.set(demandView, senders);
1745
+ }
1746
+ if (!senders.has(senderDid)) {
1747
+ senders.add(senderDid);
1748
+ this.pendingDemandForView = demandView;
1749
+ if (!this.stopped && !this.halted) {
1750
+ if (this.viewTimer) {
1751
+ clearTimeout(this.viewTimer);
1752
+ this.viewTimer = null;
1753
+ }
1754
+ const scheduledView = this.currentView;
1755
+ const clampMs = Math.min(this.baseViewTimeoutMs, 400);
1756
+ this.viewTimer = setTimeout(() => {
1757
+ this.onViewTimerExpired(scheduledView).catch(() => void 0);
1758
+ }, clampMs);
1759
+ if (typeof this.viewTimer.unref === "function") this.viewTimer.unref();
1760
+ }
1761
+ }
1762
+ return {
1763
+ status: 200,
1764
+ body: {
1765
+ ok: true,
1766
+ currentView: this.currentView,
1767
+ highQC: this.highQC
1768
+ }
1769
+ };
1770
+ }
1771
+ async handlePropose(senderDid, body) {
1772
+ return this.runExclusive(async () => {
1773
+ const proposal = body.proposal;
1774
+ const entries = body.entries;
1775
+ if (!proposal || typeof proposal !== "object" || !proposal.checkpoint || !Array.isArray(entries)) return {
1776
+ status: 400,
1777
+ body: {
1778
+ code: "INVALID_PROPOSAL",
1779
+ error: "Missing proposal or entries array"
1780
+ }
1781
+ };
1782
+ if (proposal.proposerDid !== senderDid) return {
1783
+ status: 403,
1784
+ body: {
1785
+ code: "PROPOSER_SENDER_MISMATCH",
1786
+ error: "Authenticated sender does not match proposal.proposerDid"
1787
+ }
1788
+ };
1789
+ if (proposal.highQC) this.tryAbsorbRemoteQC(proposal.highQC);
1790
+ if (proposal.timeoutCert) this.tryAbsorbRemoteTC(proposal.timeoutCert);
1791
+ if (proposal.viewNumber < this.currentView) return {
1792
+ status: 409,
1793
+ body: {
1794
+ code: "VIEW_REGRESSION",
1795
+ error: `Proposal view (${proposal.viewNumber}) < local currentView (${this.currentView})`,
1796
+ currentView: this.currentView,
1797
+ highQC: this.highQC,
1798
+ lastTC: this.lastTC
1799
+ }
1800
+ };
1801
+ const effectiveParentQC = selectHighestQC([proposal.highQC, proposal.timeoutCert?.winningHighQC]);
1802
+ const parentHeight = effectiveParentQC?.height ?? 0;
1803
+ let localCp = await this.resolver.ledger.getCheckpoint();
1804
+ if ((localCp?.height ?? 0) < parentHeight) {
1805
+ await this.catchUpToHeightLocked(parentHeight);
1806
+ localCp = await this.resolver.ledger.getCheckpoint();
1807
+ }
1808
+ const localHeight = localCp?.height ?? 0;
1809
+ if (localHeight >= proposal.checkpoint.height) return {
1810
+ status: 409,
1811
+ body: {
1812
+ code: "HEIGHT_ALREADY_COMMITTED",
1813
+ error: `Height ${proposal.checkpoint.height} is already finalized locally`,
1814
+ currentView: this.currentView,
1815
+ highQC: this.highQC,
1816
+ lastTC: this.lastTC
1817
+ }
1818
+ };
1819
+ if (localHeight !== proposal.checkpoint.height - 1) return {
1820
+ status: 409,
1821
+ body: {
1822
+ code: "PARENT_HEIGHT_MISSING",
1823
+ error: `Local height (${localHeight}) is behind parent height (${proposal.checkpoint.height - 1})`,
1824
+ currentView: this.currentView,
1825
+ highQC: this.highQC,
1826
+ lastTC: this.lastTC
1827
+ }
1828
+ };
1829
+ const expectedViewLeader = getLeaderForView(this.clusterConfig, proposal.viewNumber);
1830
+ if (proposal.proposerDid !== expectedViewLeader.did) return {
1831
+ status: 403,
1832
+ body: {
1833
+ code: "NOT_VIEW_LEADER",
1834
+ error: `Validator ${proposal.proposerDid} is not leader (${expectedViewLeader.did}) for view ${proposal.viewNumber}`
1835
+ }
1836
+ };
1837
+ const segContentHash = computeSegmentContentHash({
1838
+ chainId: this.chainId,
1839
+ checkpoint: proposal.checkpoint,
1840
+ entries
1841
+ });
1842
+ if (!proposal.checkpoint.segmentContentHash || normalizeHexCompare(proposal.checkpoint.segmentContentHash) !== normalizeHexCompare(segContentHash)) return {
1843
+ status: 400,
1844
+ body: {
1845
+ code: "SEGMENT_CONTENT_HASH_MISMATCH",
1846
+ error: "Proposal checkpoint is missing or mismatched segmentContentHash"
1847
+ }
1848
+ };
1849
+ if (!await this.hasValidCheckpointSegmentCommitment(proposal.checkpoint, segContentHash)) return {
1850
+ status: 400,
1851
+ body: {
1852
+ code: "INVALID_SEGMENT_COMMITMENT_SIGNATURE",
1853
+ error: "Proposal checkpoint is missing a valid proposer segmentCommitmentSignature"
1854
+ }
1855
+ };
1856
+ const preparePreCheck = await canVoterPrepareProposal({
1857
+ config: this.clusterConfig,
1858
+ proposal,
1859
+ voterDid: this.selfDid,
1860
+ lockedQC: this.lockedQC,
1861
+ voterStateStore: this.stateStore
1862
+ });
1863
+ if (!preparePreCheck.ok) return {
1864
+ status: 409,
1865
+ body: {
1866
+ code: "VOTER_PREPARE_REJECTED",
1867
+ error: preparePreCheck.reason || "Proposal rejected by voter safety lock",
1868
+ currentView: this.currentView,
1869
+ highQC: this.highQC,
1870
+ lastTC: this.lastTC
1871
+ }
1872
+ };
1873
+ let dryRun;
1874
+ try {
1875
+ dryRun = await this.replayer.dryRunVerifyEntries(entries, {
1876
+ expectedPrevSequence: proposal.checkpoint.prevSequence,
1877
+ prevStateRoot: localCp?.stateRoot ?? null
1878
+ });
1879
+ } catch (err) {
1880
+ return {
1881
+ status: 400,
1882
+ body: {
1883
+ code: "PROPOSAL_DRY_RUN_FAILED",
1884
+ error: err instanceof Error ? err.message : String(err)
1885
+ }
1886
+ };
1887
+ }
1888
+ if (dryRun.derivedStateRoot && normalizeHexCompare(dryRun.derivedStateRoot) !== normalizeHexCompare(proposal.checkpoint.stateRoot)) return {
1889
+ status: 400,
1890
+ body: {
1891
+ code: "STATE_ROOT_MISMATCH",
1892
+ error: `Proposal stateRoot ${proposal.checkpoint.stateRoot} != derived ${dryRun.derivedStateRoot}`
1893
+ }
1894
+ };
1895
+ let prepareVote;
1896
+ try {
1897
+ prepareVote = await verifyProposalAndCreatePrepareVote({
1898
+ config: this.clusterConfig,
1899
+ proposal,
1900
+ entries,
1901
+ voterWallet: this.validatorWallet,
1902
+ voterDid: this.selfDid,
1903
+ lockedQC: this.lockedQC,
1904
+ voterStateStore: this.stateStore,
1905
+ expectedStateRoot: dryRun.derivedStateRoot ?? void 0,
1906
+ requireSegmentCommitment: true
1907
+ });
1908
+ } catch (err) {
1909
+ return {
1910
+ status: 409,
1911
+ body: {
1912
+ code: "VOTER_PREPARE_REJECTED",
1913
+ error: err instanceof Error ? err.message : String(err),
1914
+ currentView: this.currentView,
1915
+ highQC: this.highQC,
1916
+ lastTC: this.lastTC
1917
+ }
1918
+ };
1919
+ }
1920
+ await this.stateStore.saveUncommittedProposalEntries?.({
1921
+ chainId: this.chainId,
1922
+ voterDid: this.selfDid,
1923
+ checkpointHash: proposal.checkpoint.hash,
1924
+ height: proposal.checkpoint.height,
1925
+ entries,
1926
+ checkpoint: proposal.checkpoint
1927
+ });
1928
+ this.lastSelfPreparedView = Math.max(this.lastSelfPreparedView, prepareVote.viewNumber);
1929
+ this.lockedQC = selectHighestQC([this.lockedQC, effectiveParentQC]);
1930
+ this.advanceCurrentViewTo(proposal.viewNumber);
1931
+ try {
1932
+ await this.stateStore.saveRuntimeState?.({
1933
+ chainId: this.chainId,
1934
+ voterDid: this.selfDid,
1935
+ currentView: this.currentView,
1936
+ lockedQC: this.lockedQC,
1937
+ highQC: this.highQC,
1938
+ lastTC: this.lastTC
1939
+ });
1940
+ } catch {}
1941
+ this.scheduleViewTimeout();
1942
+ return {
1943
+ status: 200,
1944
+ body: {
1945
+ prepareVote,
1946
+ currentView: this.currentView,
1947
+ highQC: this.highQC
1948
+ }
1949
+ };
1950
+ });
1951
+ }
1952
+ async handlePrecommit(senderDid, body) {
1953
+ return this.runExclusive(async () => {
1954
+ const prepareQC = body.prepareQC;
1955
+ const checkpoint = body.checkpoint;
1956
+ const parentHighQC = body.parentHighQC ?? null;
1957
+ const inlineEntries = Array.isArray(body.entries) ? body.entries : void 0;
1958
+ if (!prepareQC || typeof prepareQC !== "object" || !checkpoint || typeof checkpoint !== "object") return {
1959
+ status: 400,
1960
+ body: {
1961
+ code: "INVALID_PRECOMMIT",
1962
+ error: "Missing prepareQC or checkpoint in /consensus/precommit"
1963
+ }
1964
+ };
1965
+ if (prepareQC.leaderDid !== senderDid) return {
1966
+ status: 403,
1967
+ body: {
1968
+ code: "LEADER_SENDER_MISMATCH",
1969
+ error: "Authenticated sender does not match prepareQC.leaderDid"
1970
+ }
1971
+ };
1972
+ const expectedViewLeader = getLeaderForView(this.clusterConfig, prepareQC.viewNumber);
1973
+ if (expectedViewLeader.did !== senderDid) return {
1974
+ status: 403,
1975
+ body: {
1976
+ code: "NOT_VIEW_LEADER",
1977
+ error: `Sender ${senderDid} is not leader (${expectedViewLeader.did}) for view ${prepareQC.viewNumber}`
1978
+ }
1979
+ };
1980
+ if (prepareQC.height !== checkpoint.height || normalizeHexCompare(prepareQC.checkpointHash) !== normalizeHexCompare(checkpoint.hash)) return {
1981
+ status: 400,
1982
+ body: {
1983
+ code: "PREPARE_QC_CHECKPOINT_MISMATCH",
1984
+ error: "PrepareQC does not match checkpoint"
1985
+ }
1986
+ };
1987
+ const pqcCheck = verifyPrepareQuorumCertificate(prepareQC, this.clusterConfig);
1988
+ if (!pqcCheck.ok) return {
1989
+ status: 400,
1990
+ body: {
1991
+ code: "INVALID_PREPARE_QC",
1992
+ error: pqcCheck.reason || "Invalid PrepareQuorumCertificate"
1993
+ }
1994
+ };
1995
+ if (parentHighQC) this.tryAbsorbRemoteQC(parentHighQC);
1996
+ if (prepareQC.viewNumber < this.currentView) return {
1997
+ status: 409,
1998
+ body: {
1999
+ code: "VIEW_REGRESSION",
2000
+ error: `PrepareQC view (${prepareQC.viewNumber}) < local currentView (${this.currentView})`,
2001
+ currentView: this.currentView,
2002
+ highQC: this.highQC,
2003
+ lastTC: this.lastTC
2004
+ }
2005
+ };
2006
+ let localCp = await this.resolver.ledger.getCheckpoint();
2007
+ const targetParentHeight = checkpoint.height - 1;
2008
+ if ((localCp?.height ?? 0) < targetParentHeight && (this.highQC?.height ?? 0) >= targetParentHeight) {
2009
+ await this.catchUpToHeightLocked(targetParentHeight);
2010
+ localCp = await this.resolver.ledger.getCheckpoint();
2011
+ }
2012
+ const localHeight = localCp?.height ?? 0;
2013
+ if (localHeight >= checkpoint.height) return {
2014
+ status: 409,
2015
+ body: {
2016
+ code: "HEIGHT_ALREADY_COMMITTED",
2017
+ error: `Height ${checkpoint.height} is already finalized locally`,
2018
+ currentView: this.currentView,
2019
+ highQC: this.highQC,
2020
+ lastTC: this.lastTC
2021
+ }
2022
+ };
2023
+ if (localHeight !== targetParentHeight) return {
2024
+ status: 409,
2025
+ body: {
2026
+ code: "PARENT_HEIGHT_MISSING",
2027
+ error: `Local height (${localHeight}) is behind parent height (${targetParentHeight})`,
2028
+ currentView: this.currentView,
2029
+ highQC: this.highQC,
2030
+ lastTC: this.lastTC
2031
+ }
2032
+ };
2033
+ let stagedEntries = await this.stateStore.getUncommittedProposalEntries?.(this.chainId, this.selfDid, checkpoint.hash);
2034
+ if (!stagedEntries || stagedEntries.length !== checkpoint.txCount) {
2035
+ if (!inlineEntries || inlineEntries.length !== checkpoint.txCount) return {
2036
+ status: 409,
2037
+ body: {
2038
+ code: "MISSING_UNCOMMITTED_ENTRIES",
2039
+ error: "Replica lacks staged uncommitted entries for PrepareQC; retry with inline entries",
2040
+ currentView: this.currentView,
2041
+ highQC: this.highQC
2042
+ }
2043
+ };
2044
+ const inlineSegContentHash = computeSegmentContentHash({
2045
+ chainId: this.chainId,
2046
+ checkpoint,
2047
+ entries: inlineEntries
2048
+ });
2049
+ if (!await this.hasValidCheckpointSegmentCommitment(checkpoint, inlineSegContentHash)) return {
2050
+ status: 400,
2051
+ body: {
2052
+ code: "INVALID_SEGMENT_COMMITMENT_SIGNATURE",
2053
+ error: "Inline precommit entries failed segmentContentHash / segmentCommitmentSignature verification"
2054
+ }
2055
+ };
2056
+ let dryRun;
2057
+ try {
2058
+ dryRun = await this.replayer.dryRunVerifyEntries(inlineEntries, {
2059
+ expectedPrevSequence: checkpoint.prevSequence,
2060
+ prevStateRoot: localCp?.stateRoot ?? null
2061
+ });
2062
+ } catch (err) {
2063
+ return {
2064
+ status: 400,
2065
+ body: {
2066
+ code: "PRECOMMIT_DRY_RUN_FAILED",
2067
+ error: err instanceof Error ? err.message : String(err)
2068
+ }
2069
+ };
2070
+ }
2071
+ const tree = new IncrementalMerkleTree();
2072
+ for (const h of dryRun.entryHashes) tree.append(h);
2073
+ if (normalizeHexCompare(dryRun.derivedStateRoot) !== normalizeHexCompare(checkpoint.stateRoot) || normalizeHexCompare(tree.getHexRoot()) !== normalizeHexCompare(checkpoint.txRoot)) return {
2074
+ status: 400,
2075
+ body: {
2076
+ code: "STATE_ROOT_MISMATCH",
2077
+ error: "Inline precommit entries failed txRoot/stateRoot check"
2078
+ }
2079
+ };
2080
+ await this.stateStore.saveUncommittedProposalEntries?.({
2081
+ chainId: this.chainId,
2082
+ voterDid: this.selfDid,
2083
+ checkpointHash: checkpoint.hash,
2084
+ height: checkpoint.height,
2085
+ entries: inlineEntries,
2086
+ checkpoint
2087
+ });
2088
+ stagedEntries = inlineEntries;
2089
+ } else {
2090
+ const expectedSegContentHash = computeSegmentContentHash({
2091
+ chainId: this.chainId,
2092
+ checkpoint,
2093
+ entries: stagedEntries
2094
+ });
2095
+ if (!await this.hasValidCheckpointSegmentCommitment(checkpoint, expectedSegContentHash)) return {
2096
+ status: 400,
2097
+ body: {
2098
+ code: "INVALID_SEGMENT_COMMITMENT_SIGNATURE",
2099
+ error: "Precommit checkpoint failed segmentContentHash / segmentCommitmentSignature verification"
2100
+ }
2101
+ };
2102
+ }
2103
+ let vote;
2104
+ try {
2105
+ vote = await verifyPrepareQCAndCreateCommitVote({
2106
+ config: this.clusterConfig,
2107
+ prepareQC,
2108
+ checkpoint,
2109
+ voterWallet: this.validatorWallet,
2110
+ voterDid: this.selfDid,
2111
+ parentHighQC,
2112
+ voterStateStore: this.stateStore
2113
+ });
2114
+ } catch (err) {
2115
+ return {
2116
+ status: 409,
2117
+ body: {
2118
+ code: "VOTER_COMMIT_REJECTED",
2119
+ error: err instanceof Error ? err.message : String(err),
2120
+ currentView: this.currentView,
2121
+ highQC: this.highQC,
2122
+ lastTC: this.lastTC
2123
+ }
2124
+ };
2125
+ }
2126
+ this.lastSelfVotedView = Math.max(this.lastSelfVotedView, vote.viewNumber);
2127
+ this.lockedQC = selectHighestQC([this.lockedQC, parentHighQC]);
2128
+ this.advanceCurrentViewTo(prepareQC.viewNumber);
2129
+ try {
2130
+ await this.stateStore.saveRuntimeState?.({
2131
+ chainId: this.chainId,
2132
+ voterDid: this.selfDid,
2133
+ currentView: this.currentView,
2134
+ lockedQC: this.lockedQC,
2135
+ highQC: this.highQC,
2136
+ lastTC: this.lastTC
2137
+ });
2138
+ } catch {}
2139
+ this.scheduleViewTimeout();
2140
+ return {
2141
+ status: 200,
2142
+ body: {
2143
+ vote,
2144
+ currentView: this.currentView,
2145
+ highQC: this.highQC
2146
+ }
2147
+ };
2148
+ });
2149
+ }
2150
+ async handleCommit(body) {
2151
+ return this.runExclusive(async () => {
2152
+ const segment = body.segment;
2153
+ if (!segment || segment.chainId !== this.chainId || !segment.checkpoint?.qc || !Array.isArray(segment.entries)) return {
2154
+ status: 400,
2155
+ body: {
2156
+ code: "INVALID_COMMIT_SEGMENT",
2157
+ error: "Malformed committed segment"
2158
+ }
2159
+ };
2160
+ if (!verifyCheckpointQuorumCertificate(segment.checkpoint, this.clusterConfig).ok) return {
2161
+ status: 400,
2162
+ body: {
2163
+ code: "INVALID_CHECKPOINT_QC",
2164
+ error: "Invalid 2f+1 QuorumCertificate on commit"
2165
+ }
2166
+ };
2167
+ let localCp = await this.resolver.ledger.getCheckpoint();
2168
+ const targetHeight = segment.checkpoint.height;
2169
+ if (localCp && localCp.height >= targetHeight) {
2170
+ const existingAtTarget = await this.resolver.ledger.getCheckpoint(targetHeight);
2171
+ if (existingAtTarget && normalizeHexCompare(existingAtTarget.hash) !== normalizeHexCompare(segment.checkpoint.hash)) {
2172
+ this.haltFailClosed(`BFT safety violation at height ${targetHeight}: local ${existingAtTarget.hash} vs QC ${segment.checkpoint.hash}`);
2173
+ return {
2174
+ status: 503,
2175
+ body: {
2176
+ code: "EQUIVOCATION_HALT",
2177
+ error: this.haltReason
2178
+ }
2179
+ };
2180
+ }
2181
+ this.tryAbsorbRemoteQC(segment.checkpoint.qc);
2182
+ this.scheduleViewTimeout();
2183
+ return {
2184
+ status: 200,
2185
+ body: {
2186
+ ok: true,
2187
+ alreadyCommitted: true,
2188
+ currentView: this.currentView
2189
+ }
2190
+ };
2191
+ }
2192
+ if ((localCp?.height ?? 0) < targetHeight - 1) {
2193
+ await this.catchUpToHeightLocked(targetHeight - 1);
2194
+ localCp = await this.resolver.ledger.getCheckpoint();
2195
+ }
2196
+ if ((localCp?.height ?? 0) !== targetHeight - 1) return {
2197
+ status: 409,
2198
+ body: {
2199
+ code: "MISSING_PRIOR_HEIGHTS",
2200
+ error: `Cannot commit height ${targetHeight} while at local height ${localCp?.height ?? 0}`
2201
+ }
2202
+ };
2203
+ try {
2204
+ await this.resolver.ledger.verifySegmentForImport(segment, {
2205
+ hotstuffClusterConfig: this.clusterConfig,
2206
+ verifyStateRoot: true,
2207
+ allowAheadLocalSequence: true
2208
+ });
2209
+ } catch (err) {
2210
+ return {
2211
+ status: 400,
2212
+ body: {
2213
+ code: "INVALID_COMMIT_SEGMENT",
2214
+ error: err instanceof Error ? err.message : String(err)
2215
+ }
2216
+ };
2217
+ }
2218
+ let dryRun;
2219
+ try {
2220
+ dryRun = await this.replayer.dryRunVerifyEntries(segment.entries, {
2221
+ expectedPrevSequence: localCp?.sequence ?? 0,
2222
+ prevStateRoot: localCp?.stateRoot ?? null
2223
+ });
2224
+ } catch (err) {
2225
+ return {
2226
+ status: 400,
2227
+ body: {
2228
+ code: "COMMIT_DRY_RUN_FAILED",
2229
+ error: err instanceof Error ? err.message : String(err)
2230
+ }
2231
+ };
2232
+ }
2233
+ if (dryRun.derivedStateRoot && normalizeHexCompare(dryRun.derivedStateRoot) !== normalizeHexCompare(segment.checkpoint.stateRoot)) return {
2234
+ status: 400,
2235
+ body: {
2236
+ code: "STATE_ROOT_MISMATCH",
2237
+ error: "Segment stateRoot mismatch"
2238
+ }
2239
+ };
2240
+ await this.resolver.ledger.importSegment(segment, {
2241
+ hotstuffClusterConfig: this.clusterConfig,
2242
+ verifyStateRoot: true
2243
+ });
2244
+ for (const entry of segment.entries) await this.replayer.replayEntry(entry, { appendToLedger: false });
2245
+ this.lockedQC = selectHighestQC([this.lockedQC, this.highQC]);
2246
+ this.highQC = selectHighestQC([this.highQC, segment.checkpoint.qc]);
2247
+ this.advanceCurrentViewTo(segment.checkpoint.qc.viewNumber + 1);
2248
+ this.currentViewEnteredAtMs = Date.now();
2249
+ this.pendingDemandForView = -1;
2250
+ this.consecutiveViewTimeouts = 0;
2251
+ this.leaderRouter.advanceMinVerifiedCheckpointHeight(targetHeight);
2252
+ try {
2253
+ await this.stateStore.saveRuntimeState?.({
2254
+ chainId: this.chainId,
2255
+ voterDid: this.selfDid,
2256
+ currentView: this.currentView,
2257
+ lockedQC: this.lockedQC,
2258
+ highQC: this.highQC,
2259
+ lastTC: this.lastTC,
2260
+ pruneUncommittedUpToHeight: targetHeight
2261
+ });
2262
+ } catch {}
2263
+ this.scheduleViewTimeout();
2264
+ return {
2265
+ status: 200,
2266
+ body: {
2267
+ ok: true,
2268
+ currentView: this.currentView
2269
+ }
2270
+ };
2271
+ });
2272
+ }
2273
+ currentEffectiveViewTimeoutMs() {
2274
+ const exp = Math.min(3, Math.max(0, this.consecutiveViewTimeouts));
2275
+ const mult = Math.min(MAX_VIEW_TIMEOUT_BACKOFF_MULTIPLIER, 2 ** exp);
2276
+ return this.baseViewTimeoutMs * mult;
2277
+ }
2278
+ scheduleViewTimeout() {
2279
+ if (this.viewTimer) {
2280
+ clearTimeout(this.viewTimer);
2281
+ this.viewTimer = null;
2282
+ }
2283
+ if (this.stopped || this.halted) return;
2284
+ const scheduledView = this.currentView;
2285
+ const delayMs = this.currentEffectiveViewTimeoutMs();
2286
+ this.viewTimer = setTimeout(() => {
2287
+ this.onViewTimerExpired(scheduledView).catch(() => void 0);
2288
+ }, delayMs);
2289
+ if (typeof this.viewTimer.unref === "function") this.viewTimer.unref();
2290
+ }
2291
+ clearTimers() {
2292
+ if (this.heartbeatTimer) {
2293
+ clearInterval(this.heartbeatTimer);
2294
+ this.heartbeatTimer = null;
2295
+ }
2296
+ if (this.viewTimer) {
2297
+ clearTimeout(this.viewTimer);
2298
+ this.viewTimer = null;
2299
+ }
2300
+ }
2301
+ async sendHeartbeatsTick() {
2302
+ if (this.stopped || this.halted) return;
2303
+ if (getLeaderForView(this.clusterConfig, this.currentView).did !== this.selfDid) return;
2304
+ if (this.hasSpentTurnInView(this.currentView) || this.unleadableView === this.currentView) return;
2305
+ const threshold = this.clusterConfig.quorumThreshold ?? 3;
2306
+ let reachablePeers = 0;
2307
+ const viewSnapshot = this.currentView;
2308
+ await Promise.all(this.peerValidators.map(async (peer) => {
2309
+ try {
2310
+ const res = await this.sendConsensusJson(peer, "POST", "/consensus/heartbeat", {
2311
+ viewNumber: viewSnapshot,
2312
+ highQC: this.highQC,
2313
+ lastTC: this.lastTC
2314
+ }, Math.min(this.httpTimeoutMs, Math.max(250, this.heartbeatIntervalMs * 2)), MAX_CONTROL_ROUTE_BYTES);
2315
+ if (res.authenticated) reachablePeers++;
2316
+ const advancedQC = this.tryAbsorbRemoteQC(res.body?.highQC);
2317
+ const advancedTC = this.tryAbsorbRemoteTC(res.body?.lastTC);
2318
+ if (advancedQC || advancedTC) this.runExclusive(async () => {
2319
+ if (this.highQC) await this.catchUpToHeightLocked(this.highQC.height);
2320
+ }).catch(() => void 0);
2321
+ } catch {}
2322
+ }));
2323
+ if (reachablePeers + 1 >= threshold) {
2324
+ this.quorumContactObserved = true;
2325
+ this.quorumLeaseValid = true;
2326
+ if (getLeaderForView(this.clusterConfig, this.currentView).did === this.selfDid && !this.hasSpentTurnInView(this.currentView) && this.unleadableView !== this.currentView) {
2327
+ const lock = await Promise.resolve(this.stateStore.getLock(this.chainId, this.selfDid)).catch(() => null);
2328
+ if (!this.shouldSuppressHeartbeatKeepalive(lock, this.currentView)) this.scheduleViewTimeout();
2329
+ }
2330
+ } else this.quorumLeaseValid = false;
2331
+ }
2332
+ async onViewTimerExpired(timedOutView) {
2333
+ if (this.stopped || this.halted || timedOutView !== this.currentView) return;
2334
+ if (getLeaderForView(this.clusterConfig, timedOutView).did === this.selfDid && !this.hasSpentTurnInView(timedOutView) && this.unleadableView !== timedOutView && this.refreshQuorumLease()) {
2335
+ const lock = await Promise.resolve(this.stateStore.getLock(this.chainId, this.selfDid)).catch(() => null);
2336
+ if (!this.shouldSuppressHeartbeatKeepalive(lock, timedOutView)) {
2337
+ this.scheduleViewTimeout();
2338
+ return;
2339
+ }
2340
+ }
2341
+ let timeoutMsg = null;
2342
+ let formedTC = null;
2343
+ await this.runExclusive(async () => {
2344
+ if (this.stopped || this.halted || timedOutView !== this.currentView) return;
2345
+ this.consecutiveViewTimeouts++;
2346
+ timeoutMsg = await createHotStuffTimeoutMessage({
2347
+ config: this.clusterConfig,
2348
+ viewNumber: timedOutView,
2349
+ voterWallet: this.validatorWallet,
2350
+ voterDid: this.selfDid,
2351
+ highQC: this.highQC,
2352
+ voterStateStore: this.stateStore,
2353
+ usePrepareQCLock: true
2354
+ });
2355
+ formedTC = await this.recordTimeoutMessageAndMaybeAggregateLocked(timeoutMsg);
2356
+ this.scheduleViewTimeout();
2357
+ });
2358
+ if (formedTC) {
2359
+ await this.broadcastNewViewAndMaybeRecover(formedTC);
2360
+ return;
2361
+ }
2362
+ if (timeoutMsg) {
2363
+ const msgToSend = timeoutMsg;
2364
+ await Promise.allSettled(this.peerValidators.map(async (peer) => {
2365
+ const res = await this.sendConsensusJson(peer, "POST", "/consensus/timeout", { timeout: msgToSend }, this.httpTimeoutMs, MAX_CONTROL_ROUTE_BYTES);
2366
+ if (res.authenticated && res.body?.tc) await this.handleNewView({ tc: res.body.tc });
2367
+ }));
2368
+ }
2369
+ }
2370
+ recordTimeoutMessageAndMaybeAggregateLocked(msg) {
2371
+ if (!Number.isSafeInteger(msg?.viewNumber) || msg.viewNumber < 0 || !verifyHotStuffTimeoutMessage(msg, this.clusterConfig).ok) return Promise.resolve(null);
2372
+ if (msg.highQC) this.tryAbsorbRemoteQC(msg.highQC);
2373
+ for (const view of Array.from(this.collectedTimeoutsByView.keys())) if (!Number.isSafeInteger(view) || view < this.currentView - 1) this.collectedTimeoutsByView.delete(view);
2374
+ if (msg.viewNumber < this.currentView - 1) return Promise.resolve(null);
2375
+ if (msg.viewNumber === this.currentView - 1 && this.hasSpentTurnInView(this.currentView)) return Promise.resolve(this.lastTC && this.lastTC.viewNumber === msg.viewNumber ? this.lastTC : null);
2376
+ const maxFutureTimeoutWindow = Math.max(8, this.clusterConfig.validators.length * 2);
2377
+ if (msg.viewNumber > this.currentView + maxFutureTimeoutWindow) return Promise.resolve(null);
2378
+ let bucket = this.collectedTimeoutsByView.get(msg.viewNumber);
2379
+ if (!bucket && msg.viewNumber > this.currentView) {
2380
+ let voterFutureBuckets = 0;
2381
+ for (const [view, existingBucket] of this.collectedTimeoutsByView.entries()) if (view > this.currentView && existingBucket.has(msg.voterDid)) voterFutureBuckets++;
2382
+ if (voterFutureBuckets >= 4) return Promise.resolve(null);
2383
+ }
2384
+ if (!bucket) {
2385
+ bucket = /* @__PURE__ */ new Map();
2386
+ this.collectedTimeoutsByView.set(msg.viewNumber, bucket);
2387
+ if (this.collectedTimeoutsByView.size > 32) {
2388
+ const evictableViews = Array.from(this.collectedTimeoutsByView.keys()).filter((v) => v !== this.currentView && v !== this.currentView - 1);
2389
+ if (evictableViews.length > 0) {
2390
+ const highestFutureView = Math.max(...evictableViews);
2391
+ this.collectedTimeoutsByView.delete(highestFutureView);
2392
+ }
2393
+ }
2394
+ }
2395
+ const sanitizedMsg = {
2396
+ chainId: msg.chainId,
2397
+ viewNumber: msg.viewNumber,
2398
+ voterDid: msg.voterDid,
2399
+ highQC: msg.highQC ?? null,
2400
+ lastVotedHeight: msg.lastVotedHeight ?? null,
2401
+ lastVotedView: msg.lastVotedView ?? null,
2402
+ lastVotedCheckpointHash: msg.lastVotedCheckpointHash ?? null,
2403
+ ...msg.lastVotedCheckpoint ? { lastVotedCheckpoint: msg.lastVotedCheckpoint } : {},
2404
+ ...msg.lastVotedVoteSignature ? { lastVotedVoteSignature: msg.lastVotedVoteSignature } : {},
2405
+ ...msg.lastVotedVoteTimestamp !== void 0 && msg.lastVotedVoteTimestamp !== null ? { lastVotedVoteTimestamp: msg.lastVotedVoteTimestamp } : {},
2406
+ ...msg.priorVotesByView ? { priorVotesByView: msg.priorVotesByView } : {},
2407
+ ...msg.highestPrepareQC !== void 0 ? { highestPrepareQC: msg.highestPrepareQC } : {},
2408
+ ...msg.highestPrepareCheckpoint ? { highestPrepareCheckpoint: msg.highestPrepareCheckpoint } : {},
2409
+ ...msg.observedPrepareQCs ? { observedPrepareQCs: msg.observedPrepareQCs } : {},
2410
+ timestamp: msg.timestamp,
2411
+ signature: msg.signature
2412
+ };
2413
+ bucket.set(sanitizedMsg.voterDid, sanitizedMsg);
2414
+ const threshold = this.clusterConfig.quorumThreshold ?? 3;
2415
+ if (bucket.size < threshold) return Promise.resolve(null);
2416
+ if (this.lastTC && (this.lastTC.viewNumber > sanitizedMsg.viewNumber || this.lastTC.viewNumber === sanitizedMsg.viewNumber && bucket.size <= this.lastTC.signatures.length)) return Promise.resolve(this.lastTC.viewNumber === sanitizedMsg.viewNumber ? this.lastTC : null);
2417
+ let tc;
2418
+ try {
2419
+ tc = aggregateTimeoutCertificate({
2420
+ config: this.clusterConfig,
2421
+ viewNumber: sanitizedMsg.viewNumber,
2422
+ messages: Array.from(bucket.values())
2423
+ });
2424
+ } catch {
2425
+ return Promise.resolve(null);
2426
+ }
2427
+ if (!verifyTimeoutCertificate(tc, this.clusterConfig).ok) return Promise.resolve(null);
2428
+ return this.applyVerifiedTimeoutCertificateLocked(tc).then(() => tc);
2429
+ }
2430
+ async applyVerifiedTimeoutCertificateLocked(tc) {
2431
+ if (tc.winningHighQC) {
2432
+ this.tryAbsorbRemoteQC(tc.winningHighQC);
2433
+ const persistedLock = await Promise.resolve(this.stateStore.getLock(this.chainId, this.selfDid)).catch(() => null);
2434
+ if (persistedLock) {
2435
+ this.lastSelfVotedView = Math.max(this.lastSelfVotedView, persistedLock.lastVotedView, persistedLock.lastCommitVotedView ?? -1);
2436
+ this.lastSelfPreparedView = Math.max(this.lastSelfPreparedView, persistedLock.lastPreparedView ?? -1);
2437
+ }
2438
+ if (((await this.resolver.ledger.getCheckpoint())?.height ?? 0) < tc.winningHighQC.height) await this.catchUpToHeightLocked(tc.winningHighQC.height);
2439
+ }
2440
+ const prevView = this.currentView;
2441
+ let upgradedSameViewTC = false;
2442
+ if (this.isBetterTimeoutCertificate(tc)) {
2443
+ upgradedSameViewTC = Boolean(this.lastTC && tc.viewNumber === this.lastTC.viewNumber);
2444
+ this.lastTC = tc;
2445
+ if (upgradedSameViewTC && this.unleadableView === tc.viewNumber + 1) this.unleadableView = -1;
2446
+ }
2447
+ if (tc.viewNumber + 1 > this.currentView) {
2448
+ this.advanceCurrentViewTo(tc.viewNumber + 1);
2449
+ this.consecutiveViewTimeouts = 0;
2450
+ if (this.unleadableView < this.currentView) this.unleadableView = -1;
2451
+ }
2452
+ for (const view of Array.from(this.collectedTimeoutsByView.keys())) if (!Number.isSafeInteger(view) || view < this.currentView - 1) this.collectedTimeoutsByView.delete(view);
2453
+ try {
2454
+ await this.stateStore.saveRuntimeState?.({
2455
+ chainId: this.chainId,
2456
+ voterDid: this.selfDid,
2457
+ currentView: this.currentView,
2458
+ lockedQC: this.lockedQC,
2459
+ highQC: this.highQC,
2460
+ lastTC: this.lastTC
2461
+ });
2462
+ } catch {}
2463
+ this.scheduleViewTimeout();
2464
+ return this.currentView > prevView || upgradedSameViewTC;
2465
+ }
2466
+ async broadcastNewViewAndMaybeRecover(tc) {
2467
+ await Promise.allSettled(this.peerValidators.map((peer) => this.sendConsensusJson(peer, "POST", "/consensus/new-view", { tc }, this.httpTimeoutMs, MAX_CONTROL_ROUTE_BYTES)));
2468
+ await this.maybeRecoverLockedCheckpointAsNewLeader(tc);
2469
+ }
2470
+ async maybeRecoverLockedCheckpointAsNewLeader(tc) {
2471
+ if (!tc.lockedCheckpoint || this.stopped || this.halted) return;
2472
+ let recovered = null;
2473
+ await this.runExclusive(async () => {
2474
+ const expectedLeader = getLeaderForView(this.clusterConfig, this.currentView);
2475
+ const targetHeight = (this.highQC?.height ?? 0) + 1;
2476
+ if (expectedLeader.did === this.selfDid && this.currentView === tc.viewNumber + 1 && tc.lockedCheckpoint && tc.lockedCheckpoint.height === targetHeight) {
2477
+ let recoveryFailed = false;
2478
+ try {
2479
+ recovered = await this.recoverLockedCheckpointLocked(tc);
2480
+ } catch {
2481
+ recoveryFailed = true;
2482
+ recovered = null;
2483
+ }
2484
+ if (recoveryFailed || !recovered) {
2485
+ if (((await this.resolver.ledger.getCheckpoint().catch(() => null))?.height ?? 0) < targetHeight) this.markCurrentViewUnleadableAndScheduleTimeout();
2486
+ }
2487
+ }
2488
+ });
2489
+ if (recovered) await this.broadcastCommittedSegments([recovered]).catch(() => void 0);
2490
+ }
2491
+ async handleTimeoutMessage(body) {
2492
+ const msg = body.timeout;
2493
+ if (!msg || typeof msg !== "object") return {
2494
+ status: 400,
2495
+ body: {
2496
+ code: "INVALID_TIMEOUT",
2497
+ error: "Missing timeout message"
2498
+ }
2499
+ };
2500
+ const check = verifyHotStuffTimeoutMessage(msg, this.clusterConfig);
2501
+ if (!check.ok) return {
2502
+ status: 400,
2503
+ body: {
2504
+ code: "INVALID_TIMEOUT_SIGNATURE",
2505
+ error: check.reason || "Invalid timeout"
2506
+ }
2507
+ };
2508
+ let formedTC = null;
2509
+ let outOfRangeError = null;
2510
+ let leaderAbdicatedView = null;
2511
+ await this.runExclusive(async () => {
2512
+ if (msg.highQC) this.tryAbsorbRemoteQC(msg.highQC);
2513
+ const maxFutureTimeoutWindow = Math.max(8, this.clusterConfig.validators.length * 2);
2514
+ if (msg.viewNumber > this.currentView + maxFutureTimeoutWindow) {
2515
+ outOfRangeError = `Timeout view (${msg.viewNumber}) exceeds max future window (${this.currentView + maxFutureTimeoutWindow})`;
2516
+ return;
2517
+ }
2518
+ const currentViewLeader = getLeaderForView(this.clusterConfig, this.currentView);
2519
+ const existingBucket = this.collectedTimeoutsByView.get(this.currentView);
2520
+ if (msg.viewNumber === this.currentView && msg.voterDid === currentViewLeader.did && msg.voterDid !== this.selfDid && !existingBucket?.has(this.selfDid)) leaderAbdicatedView = this.currentView;
2521
+ formedTC = await this.recordTimeoutMessageAndMaybeAggregateLocked(msg);
2522
+ });
2523
+ if (outOfRangeError) return {
2524
+ status: 400,
2525
+ body: {
2526
+ code: "TIMEOUT_VIEW_OUT_OF_RANGE",
2527
+ error: outOfRangeError,
2528
+ currentView: this.currentView
2529
+ }
2530
+ };
2531
+ if (formedTC) this.broadcastNewViewAndMaybeRecover(formedTC).catch(() => void 0);
2532
+ else if (leaderAbdicatedView !== null && leaderAbdicatedView === this.currentView) {
2533
+ const viewToExpire = leaderAbdicatedView;
2534
+ const t = setTimeout(() => {
2535
+ this.onViewTimerExpired(viewToExpire).catch(() => void 0);
2536
+ }, 0);
2537
+ if (typeof t.unref === "function") t.unref();
2538
+ }
2539
+ return {
2540
+ status: 200,
2541
+ body: {
2542
+ ok: true,
2543
+ currentView: this.currentView,
2544
+ tc: formedTC
2545
+ }
2546
+ };
2547
+ }
2548
+ async handleNewView(body) {
2549
+ const tc = body.tc;
2550
+ if (!tc || typeof tc !== "object") return {
2551
+ status: 400,
2552
+ body: {
2553
+ code: "INVALID_TC",
2554
+ error: "Missing TimeoutCertificate"
2555
+ }
2556
+ };
2557
+ const check = verifyTimeoutCertificate(tc, this.clusterConfig);
2558
+ if (!check.ok) return {
2559
+ status: 400,
2560
+ body: {
2561
+ code: "INVALID_TC",
2562
+ error: check.reason || "Invalid TimeoutCertificate"
2563
+ }
2564
+ };
2565
+ let accepted = false;
2566
+ await this.runExclusive(async () => {
2567
+ accepted = await this.applyVerifiedTimeoutCertificateLocked(tc);
2568
+ });
2569
+ if (accepted && tc.lockedCheckpoint) this.maybeRecoverLockedCheckpointAsNewLeader(tc).catch(() => void 0);
2570
+ return {
2571
+ status: 200,
2572
+ body: {
2573
+ ok: true,
2574
+ currentView: this.currentView,
2575
+ highQC: this.highQC
2576
+ }
2577
+ };
2578
+ }
2579
+ async probePeersOnStartup() {
2580
+ let reachablePeers = 0;
2581
+ await Promise.allSettled(this.peerValidators.map(async (peer) => {
2582
+ const res = await this.sendConsensusJson(peer, "GET", "/consensus/status", void 0, Math.min(1e3, this.httpTimeoutMs), MAX_CONTROL_ROUTE_BYTES);
2583
+ if (res.status === 200 && res.authenticated) {
2584
+ reachablePeers++;
2585
+ this.tryAbsorbRemoteQC(res.body.highQC);
2586
+ this.tryAbsorbRemoteTC(res.body.lastTC);
2587
+ }
2588
+ }));
2589
+ if (reachablePeers + 1 >= (this.clusterConfig.quorumThreshold ?? 3)) {
2590
+ this.quorumContactObserved = true;
2591
+ this.quorumLeaseValid = true;
2592
+ }
2593
+ if (this.highQC) await this.runExclusive(async () => {
2594
+ await this.catchUpToHeightLocked(this.highQC.height);
2595
+ });
2596
+ }
2597
+ async start() {
2598
+ if (this.server) return;
2599
+ this.stopped = false;
2600
+ this.startedAtMs = Date.now();
2601
+ await this.runExclusive(async () => {
2602
+ const persisted = await this.stateStore.loadRuntimeState?.(this.chainId, this.selfDid);
2603
+ if (persisted) {
2604
+ if (persisted.lockedQC && verifyQuorumCertificate(persisted.lockedQC, this.clusterConfig).ok) this.lockedQC = persisted.lockedQC;
2605
+ if (persisted.highQC && verifyQuorumCertificate(persisted.highQC, this.clusterConfig).ok) this.highQC = persisted.highQC;
2606
+ if (persisted.lastTC && verifyTimeoutCertificate(persisted.lastTC, this.clusterConfig).ok) this.lastTC = persisted.lastTC;
2607
+ this.currentView = Math.max(this.currentView, persisted.currentView, this.highQC ? this.highQC.viewNumber + 1 : 0, this.lastTC ? this.lastTC.viewNumber + 1 : 0);
2608
+ }
2609
+ const persistedLock = await Promise.resolve(this.stateStore.getLock(this.chainId, this.selfDid)).catch(() => null);
2610
+ if (persistedLock) {
2611
+ this.lastSelfVotedView = Math.max(this.lastSelfVotedView, persistedLock.lastVotedView, persistedLock.lastCommitVotedView ?? -1);
2612
+ this.lastSelfPreparedView = Math.max(this.lastSelfPreparedView, persistedLock.lastPreparedView ?? -1);
2613
+ }
2614
+ const localCp = await this.resolver.ledger.getCheckpoint();
2615
+ if (localCp?.qc && verifyQuorumCertificate(localCp.qc, this.clusterConfig).ok) {
2616
+ this.highQC = selectHighestQC([this.highQC, localCp.qc]);
2617
+ this.currentView = Math.max(this.currentView, localCp.qc.viewNumber + 1);
2618
+ }
2619
+ this.currentViewEnteredAtMs = Date.now();
2620
+ if (localCp && localCp.height > 0) this.leaderRouter.advanceMinVerifiedCheckpointHeight(localCp.height);
2621
+ await this.reconcileCrashWindowLocked();
2622
+ });
2623
+ const srv = http.createServer((req, res) => {
2624
+ this.handleConsensusHttpRequest(req, res).catch((err) => {
2625
+ if (!res.headersSent) {
2626
+ res.statusCode = 500;
2627
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
2628
+ res.end(JSON.stringify({
2629
+ code: "INTERNAL_ERROR",
2630
+ error: err instanceof Error ? err.message : String(err)
2631
+ }));
2632
+ }
2633
+ });
2634
+ });
2635
+ await new Promise((resolve, reject) => {
2636
+ srv.once("error", reject);
2637
+ srv.listen(this.configuredConsensusPort, this.consensusBindHost, () => {
2638
+ srv.removeListener("error", reject);
2639
+ resolve();
2640
+ });
2641
+ });
2642
+ this.server = srv;
2643
+ this.boundPort = srv.address()?.port ?? this.configuredConsensusPort;
2644
+ await this.probePeersOnStartup().catch(() => void 0);
2645
+ this.heartbeatTimer = setInterval(() => {
2646
+ this.sendHeartbeatsTick().catch(() => void 0);
2647
+ }, this.heartbeatIntervalMs);
2648
+ if (typeof this.heartbeatTimer.unref === "function") this.heartbeatTimer.unref();
2649
+ this.scheduleViewTimeout();
2650
+ }
2651
+ async close() {
2652
+ this.stopped = true;
2653
+ this.clearTimers();
2654
+ for (const waiter of Array.from(this.viewAdvanceWaiters)) {
2655
+ this.viewAdvanceWaiters.delete(waiter);
2656
+ waiter.resolve();
2657
+ }
2658
+ if (this.server) {
2659
+ const srv = this.server;
2660
+ this.server = null;
2661
+ await new Promise((resolve) => srv.close(() => resolve()));
2662
+ }
2663
+ await this.mutexTail.catch(() => void 0);
2664
+ }
2665
+ };
2666
+
2667
+ //#endregion
2668
+ export { ConsensusAbortError, HotStuffNodeRuntime };