@ocap/resolver 1.31.9 → 1.32.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/esm/_virtual/rolldown_runtime.mjs +7 -0
  2. package/esm/api.d.mts +33 -5
  3. package/esm/api.mjs +939 -53
  4. package/esm/dashboard.d.mts +199 -0
  5. package/esm/dashboard.mjs +2481 -0
  6. package/esm/explorer.d.mts +29 -0
  7. package/esm/explorer.mjs +227 -0
  8. package/esm/follower.d.mts +294 -0
  9. package/esm/follower.mjs +2452 -0
  10. package/esm/hooks.mjs +1 -1
  11. package/esm/hotstuff-runtime.d.mts +271 -0
  12. package/esm/hotstuff-runtime.mjs +2668 -0
  13. package/esm/index.d.mts +79 -4
  14. package/esm/index.mjs +911 -174
  15. package/esm/node-preferences.d.mts +203 -0
  16. package/esm/node-preferences.mjs +1021 -0
  17. package/esm/replayer.d.mts +114 -0
  18. package/esm/replayer.mjs +430 -0
  19. package/esm/token-distribution.mjs +2 -2
  20. package/esm/token-flow.mjs +1 -1
  21. package/esm/types.d.mts +25 -2
  22. package/lib/api.cjs +941 -52
  23. package/lib/api.d.cts +33 -5
  24. package/lib/dashboard.cjs +2491 -0
  25. package/lib/dashboard.d.cts +199 -0
  26. package/lib/explorer.cjs +227 -0
  27. package/lib/explorer.d.cts +29 -0
  28. package/lib/follower.cjs +2458 -0
  29. package/lib/follower.d.cts +294 -0
  30. package/lib/hooks.cjs +1 -1
  31. package/lib/hotstuff-runtime.cjs +2671 -0
  32. package/lib/hotstuff-runtime.d.cts +271 -0
  33. package/lib/index.cjs +946 -174
  34. package/lib/index.d.cts +79 -4
  35. package/lib/node-preferences.cjs +1043 -0
  36. package/lib/node-preferences.d.cts +203 -0
  37. package/lib/replayer.cjs +432 -0
  38. package/lib/replayer.d.cts +114 -0
  39. package/lib/token-distribution.cjs +2 -2
  40. package/lib/token-flow.cjs +1 -1
  41. package/lib/types.d.cts +25 -2
  42. package/package.json +20 -14
package/esm/index.mjs CHANGED
@@ -1,26 +1,33 @@
1
+ import { MAX_BLOCKED_ACCOUNTS, MAX_CONFIG_BODY_BYTES, MAX_MEMO_LENGTH, MAX_PEER_URLS, MAX_RESERVED_SYMBOLS, MAX_TRUSTED_ACCOUNTS, NodePreferencesError, NodePreferencesManager, applyBootRuntimePreferences, createAdminAuthGuard, createFollowerPeerFetchGuard, isPrivateOrReservedIpAddress, isValidAccountAddressCandidate, loadNodePreferences, normalizeBlockedAccountKey, timingSafeTokenEqual, validateFollowerPeerUrls } from "./node-preferences.mjs";
2
+ import { UNIFIED_CONSOLE_APP_JS, buildUnifiedConsoleHtml, collectLedgerHealthSummary, createNodeDashboardRouter, createNodeMaintenanceController, createUnifiedConsoleMiddleware, isDashboardEnabled } from "./dashboard.mjs";
3
+ import { createExplorerMiddleware, isExplorerEnabled } from "./explorer.mjs";
4
+ import { FUTURE_LEDGER_ENTRY_TIMESTAMP, LedgerEntryReplayer } from "./replayer.mjs";
5
+ import { DEFAULT_FOLLOWER_MAX_SYNC_LAG, DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS, DEFAULT_FOLLOWER_POLL_INTERVAL_MS, FollowerSyncService, isTransientSqliteLockError } from "./follower.mjs";
1
6
  import { name } from "./package.mjs";
2
7
  import { onCreateRollup, onCreateRollupBlock, onCreateTx, onUpdateToken } from "./hooks.mjs";
8
+ import { ConsensusAbortError, HotStuffNodeRuntime } from "./hotstuff-runtime.mjs";
3
9
  import { MigrationChainManager } from "./migration-chain.mjs";
4
10
  import { getInstance } from "./token-cache.mjs";
5
11
  import { TokenDistributionManager } from "./token-distribution.mjs";
6
12
  import { listTokenFlows, verifyAccountRisk } from "./token-flow.mjs";
7
- import { toStakeAddress } from "@arcblock/did-util";
13
+ import { computeForwardReceiptDigest } from "@arcblock/ledger-core";
14
+ import { types } from "@ocap/mcrypto";
15
+ import { TxTimer, assertRawWireEnvelope, assertStatelessTxRules, assertTxAdmission, classifyErrorStrikeCategory, createExecutor, getTxSecurityWarningByHash, inspectTransactionPreFlight, recordActorSecurityStrike, resolveVerifiedStrikeActors, setTxSecurityWarningForHash } from "@ocap/tx-protocols";
16
+ import { randomUUID } from "node:crypto";
17
+ import { fromPublicKey, isValid, toTypeInfo } from "@arcblock/did";
8
18
  import { BN, fromTokenToUnit, toAddress, toBN } from "@ocap/util";
19
+ import { CustomError } from "@ocap/util/lib/error";
20
+ import * as states from "@ocap/state";
21
+ import { toStakeAddress } from "@arcblock/did-util";
9
22
  import createDebug from "debug";
10
23
  import pick from "lodash/pick.js";
11
- import { randomUUID } from "node:crypto";
12
- import { fromPublicKey, isValid, toTypeInfo } from "@arcblock/did";
13
24
  import { patterns, v, vDID, vValidate } from "@arcblock/validator";
14
25
  import * as Config from "@ocap/config";
15
26
  import { formatSearchResult, rebuildIndexFromState } from "@ocap/indexdb";
16
- import { types } from "@ocap/mcrypto";
17
27
  import { fromTypeUrl } from "@ocap/message";
18
- import * as states from "@ocap/state";
19
- import { TxTimer, assertRawWireEnvelope, assertStatelessTxRules, assertTxAdmission, classifyErrorStrikeCategory, createExecutor, getTxSecurityWarningByHash, inspectTransactionPreFlight, recordActorSecurityStrike, resolveVerifiedStrikeActors, setTxSecurityWarningForHash } from "@ocap/tx-protocols";
20
28
  import { decodeAnySafe } from "@ocap/tx-protocols/lib/util";
21
29
  import { DEFAULT_TOKEN_DECIMAL } from "@ocap/util/lib/constant";
22
30
  import { stripDefaultDepositV2BridgeFields } from "@ocap/util/lib/deposit-v2-bridge-fields";
23
- import { CustomError } from "@ocap/util/lib/error";
24
31
  import { md5 } from "@ocap/util/lib/md5";
25
32
  import cloneDeep from "lodash/cloneDeep.js";
26
33
  import get from "lodash/get.js";
@@ -31,13 +38,16 @@ import set from "lodash/set.js";
31
38
  import uniqBy from "lodash/unionBy.js";
32
39
  import uniq from "lodash/uniq.js";
33
40
  import Queue from "queue";
34
- import { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, isDefaultTokenChanged } from "@ocap/indexdb/lib/util";
41
+ import { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, formatTxBeforeInsert, isDefaultTokenChanged } from "@ocap/indexdb/lib/util";
35
42
  import { attachPaidTxGas, getTxReceipts, getTxReceiver, getTxSender, mergeTxReceipts } from "@ocap/state/lib/states/tx";
36
43
 
37
44
  //#region src/index.ts
38
45
  const debug = createDebug(name);
39
46
  const noop = (x) => x;
40
47
  const CHAIN_ADDR = md5("OCAP_CHAIN_ADDR");
48
+ function getNormalizedEnvLower(key) {
49
+ return String(process.env[key] ?? "").trim().toLowerCase();
50
+ }
41
51
  const maxGasOps = {
42
52
  "fg:t:account_migrate": {
43
53
  create: 2,
@@ -267,6 +277,11 @@ const withTxProjection = (args, ctx) => ctx?.graphqlTxProjection === true ? {
267
277
  ...args,
268
278
  columns: GRAPHQL_INDEXED_TX_COLUMNS
269
279
  } : args;
280
+ const assertResolverNotHaltedForDataRead = (self) => {
281
+ const runtime = self?.nodeRuntime;
282
+ if (runtime?.isHalted?.() === true) throw new CustomError("NODE_HALTED", "Chain node is halted fail-closed");
283
+ if (runtime?.isReconciling?.() === true) throw new CustomError("FOLLOWER_RECONCILING", "Follower is reconciling local statedb with imported ledger segment");
284
+ };
270
285
  var OCAPResolver = class {
271
286
  /**
272
287
  * Creates an instance of OCAPResolver.
@@ -278,24 +293,44 @@ var OCAPResolver = class {
278
293
  * @param params.filter bloom filter to do anti-replay check
279
294
  * @param params.validateTokenConfig should we validate token supply and token-holder balance, should be disabled when starting an existing chain
280
295
  */
281
- constructor({ statedb, indexdb, ledger, config, filter, validateTokenConfig = true, logger }) {
296
+ constructor({ statedb, indexdb, ledger, config, filter, admissionBlockedCheck, admissionReservedSymbolCheck, validateTokenConfig = true, skipInitializeStateDB = false, deferInitialize = false, consensusMode, txQueueConfig, now, nodeRuntime, logger }) {
282
297
  this.inFlightPreFlights = 0;
298
+ this.initializationPromise = null;
299
+ this.shutdownPromise = null;
300
+ this.isShuttingDown = false;
301
+ this.preFlightDrainWaiters = [];
302
+ this.pendingIndexWrites = /* @__PURE__ */ new Set();
303
+ this.txAcceptedTotal = 0;
304
+ this.txPersistedFailedTotal = 0;
305
+ this.txPreFlightRejectedTotal = 0;
306
+ this.txForwardedTotal = 0;
307
+ this.txBucketsSec = new Int32Array(60);
308
+ this.txBucketCounts = new Int32Array(60);
283
309
  if (!statedb) throw new Error("OCAP Resolver requires a valid statedb implementation to work");
284
310
  if (!indexdb) throw new Error("OCAP Resolver requires a valid indexdb implementation to work");
285
311
  if (!ledger) throw new Error("OCAP Resolver requires a valid ledger implementation to work");
286
312
  this.logger = logger || console;
313
+ this.now = typeof now === "function" ? now : () => Date.now();
314
+ this.deferInitialize = Boolean(deferInitialize);
315
+ this.explicitConsensusMode = consensusMode;
287
316
  this.statedb = statedb;
288
317
  this.indexdb = indexdb;
289
318
  this.ledger = ledger;
290
319
  this.filter = filter;
320
+ this.admissionBlockedCheck = admissionBlockedCheck;
321
+ this.admissionReservedSymbolCheck = admissionReservedSymbolCheck;
322
+ this.skipInitializeStateDB = Boolean(skipInitializeStateDB);
323
+ this.nodeRuntime = nodeRuntime;
291
324
  this.config = Object.freeze(Config.validate(config));
292
325
  this.chainAddr = md5(config.chainId);
293
326
  this.tokenItx = Config.genTokenItx(this.config);
294
327
  this.consensus = `${statedb.name} v${statedb.version}`;
328
+ const isHotStuffMode = consensusMode === "hotstuff" || !consensusMode && getNormalizedEnvLower("CONSENSUS_MODE") === "hotstuff" || Boolean(nodeRuntime?.getConsensusCommitter?.());
329
+ if (txQueueConfig?.maxRequest !== void 0) this.setMaxTxRequest(txQueueConfig.maxRequest);
295
330
  this.queue = new Queue({
296
331
  autostart: true,
297
- concurrency: txRequestConfig.concurrent,
298
- timeout: txRequestConfig.timeout
332
+ concurrency: isHotStuffMode ? 1 : txQueueConfig?.concurrent ?? txRequestConfig.concurrent,
333
+ timeout: txQueueConfig?.timeoutMs ?? txRequestConfig.timeout
299
334
  });
300
335
  if (indexdb) {
301
336
  this.tokenCache = getInstance(indexdb.token);
@@ -310,28 +345,387 @@ var OCAPResolver = class {
310
345
  runAsLambda: typeof statedb.runAsLambda === "function" ? statedb.runAsLambda.bind(statedb) : void 0
311
346
  });
312
347
  this.formatTx = this._formatTx.bind(this);
313
- if (validateTokenConfig) this.validateTokenConfig();
348
+ const normalizedRole = getNormalizedEnvLower("CHAIN_ROLE");
349
+ const normalizedMode = getNormalizedEnvLower("CHAIN_MODE");
350
+ const isReadonlyStartRole = Boolean(skipInitializeStateDB) || nodeRuntime && nodeRuntime.role !== "validator" || normalizedRole === "follower" || normalizedRole === "standby" || normalizedMode === "readonly";
351
+ if (validateTokenConfig && !isReadonlyStartRole) this.validateTokenConfig();
314
352
  this.connectIndexDB();
315
- this.initializationPromise = this.initializeStateDB().catch((err) => {
353
+ if (!this.deferInitialize) this.initializationPromise = this.initializeStateDB().catch((err) => {
316
354
  this.logger.error("Failed to initialize statedb:", err.message);
317
355
  process.exit(1);
318
356
  });
319
357
  }
358
+ initialize() {
359
+ if (!this.initializationPromise) this.initializationPromise = this.initializeStateDB();
360
+ return this.initializationPromise;
361
+ }
362
+ setNodeRuntime(runtime) {
363
+ this.nodeRuntime = runtime;
364
+ if (runtime?.getConsensusCommitter?.()) this.queue.concurrency = 1;
365
+ }
366
+ getNodeRuntime() {
367
+ return this.nodeRuntime;
368
+ }
369
+ setAdmissionBlockedCheck(fn) {
370
+ this.admissionBlockedCheck = fn;
371
+ }
372
+ setAdmissionReservedSymbolCheck(fn) {
373
+ this.admissionReservedSymbolCheck = fn;
374
+ }
375
+ getMaxTxRequest() {
376
+ if (this.maxTxRequestOverride !== void 0) return this.maxTxRequestOverride;
377
+ return Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
378
+ }
379
+ setMaxTxRequest(maxRequest) {
380
+ if (maxRequest === void 0) {
381
+ this.maxTxRequestOverride = void 0;
382
+ return;
383
+ }
384
+ if (!Number.isSafeInteger(maxRequest) || maxRequest < 1 || maxRequest > 1e4) throw new CustomError("INVALID_CONFIG", "txMaxRequest must be an integer between 1 and 10000");
385
+ this.maxTxRequestOverride = maxRequest;
386
+ }
387
+ recordCommittedTxSample(nowMs = Date.now()) {
388
+ const sec = Math.floor(nowMs / 1e3);
389
+ const slot = (sec % 60 + 60) % 60;
390
+ if (this.txBucketsSec[slot] !== sec) {
391
+ this.txBucketsSec[slot] = sec;
392
+ this.txBucketCounts[slot] = 1;
393
+ } else this.txBucketCounts[slot] += 1;
394
+ }
395
+ getPipelineTelemetry(nowMs = Date.now()) {
396
+ const nowSec = Math.floor(nowMs / 1e3);
397
+ let sum10 = 0;
398
+ let sum60 = 0;
399
+ for (let i = 0; i < 60; i++) {
400
+ const bucketSec = this.txBucketsSec[i];
401
+ if (bucketSec <= 0) continue;
402
+ const age = nowSec - bucketSec;
403
+ if (age >= 0 && age < 60) {
404
+ sum60 += this.txBucketCounts[i];
405
+ if (age < 10) sum10 += this.txBucketCounts[i];
406
+ }
407
+ }
408
+ return {
409
+ queueDepth: this.queue.length,
410
+ inFlightPreFlights: this.inFlightPreFlights,
411
+ maxTxRequest: this.getMaxTxRequest(),
412
+ concurrency: this.queue.concurrency,
413
+ acceptedTotal: this.txAcceptedTotal,
414
+ persistedFailedTotal: this.txPersistedFailedTotal,
415
+ preFlightRejectedTotal: this.txPreFlightRejectedTotal,
416
+ forwardedTotal: this.txForwardedTotal,
417
+ tps10s: Number((sum10 / 10).toFixed(2)),
418
+ tps60s: Number((sum60 / 60).toFixed(2))
419
+ };
420
+ }
421
+ async assertNotBlockedAtAdmission(context) {
422
+ const hasBlockedCheck = typeof this.admissionBlockedCheck === "function";
423
+ const hasReservedCheck = typeof this.admissionReservedSymbolCheck === "function";
424
+ if (!hasBlockedCheck && !hasReservedCheck) return;
425
+ const txObj = context.tx && typeof context.tx === "object" ? context.tx : {};
426
+ const itxObj = context.itxJson && typeof context.itxJson === "object" ? context.itxJson : context.itx && typeof context.itx === "object" ? context.itx : {};
427
+ const txType = String(context.txType || txObj.itx?.type || "");
428
+ if (hasReservedCheck) {
429
+ if (txType === "fg:t:create_token_factory" || txType === "CreateTokenFactoryTx" || txType === "fg:t:create_token" || txType === "CreateTokenTx") {
430
+ const tokenNested = itxObj.token && typeof itxObj.token === "object" ? itxObj.token : null;
431
+ const normalizedSym = (typeof tokenNested?.symbol === "string" ? tokenNested.symbol : typeof itxObj.symbol === "string" ? itxObj.symbol : "").trim().toUpperCase();
432
+ if (normalizedSym && await Promise.resolve(this.admissionReservedSymbolCheck(normalizedSym))) {
433
+ const symErr = new CustomError("INVALID_SYMBOL", `Token symbol "${normalizedSym}" is reserved by node admission policy`);
434
+ symErr._strikeRecorded = true;
435
+ throw symErr;
436
+ }
437
+ }
438
+ }
439
+ if (!hasBlockedCheck) return;
440
+ const sigs = Array.isArray(txObj.signaturesList) ? txObj.signaturesList : Array.isArray(txObj.signatures) ? txObj.signatures : [];
441
+ const inputs = Array.isArray(itxObj.inputs) ? itxObj.inputs : Array.isArray(itxObj.inputsList) ? itxObj.inputsList : [];
442
+ const outputs = Array.isArray(itxObj.outputs) ? itxObj.outputs : Array.isArray(itxObj.outputsList) ? itxObj.outputsList : [];
443
+ const trustedIssuers = Array.isArray(itxObj.trustedIssuers) ? itxObj.trustedIssuers : Array.isArray(itxObj.trustedIssuersList) ? itxObj.trustedIssuersList : [];
444
+ const issuerField = itxObj.issuer;
445
+ const issuerCandidates = typeof issuerField === "string" ? [issuerField] : issuerField && typeof issuerField === "object" ? [issuerField.id, issuerField.address] : [];
446
+ const candidateActors = /* @__PURE__ */ new Set();
447
+ const addCandidate = (raw) => {
448
+ if (typeof raw === "string") {
449
+ const trimmed = raw.trim();
450
+ if (trimmed) candidateActors.add(trimmed);
451
+ }
452
+ };
453
+ const isRevokeDelegate = txType === "fg:t:revoke_delegate" || txType === "RevokeDelegateTx";
454
+ for (const candidate of [
455
+ txObj.from,
456
+ txObj.delegator,
457
+ ...isRevokeDelegate ? [] : [itxObj.to],
458
+ itxObj.receiver,
459
+ itxObj.owner,
460
+ itxObj.delegatee,
461
+ ...txType === "fg:t:account_migrate" || txType === "AccountMigrateTx" ? [itxObj.address] : [],
462
+ ...issuerCandidates,
463
+ ...trustedIssuers,
464
+ ...sigs.flatMap((s) => [s?.signer, s?.delegator]),
465
+ ...inputs.flatMap((inp) => [inp?.owner, inp?.address]),
466
+ ...outputs.flatMap((out) => [out?.owner, out?.address])
467
+ ]) addCandidate(candidate);
468
+ if (this.statedb) {
469
+ if (txType === "fg:t:claim_stake" || txType === "ClaimStakeTx") {
470
+ const stakeAddr = typeof itxObj.address === "string" ? itxObj.address.trim() : "";
471
+ if (stakeAddr && typeof this.statedb.stake?.get === "function") addCandidate((await this.statedb.stake.get(stakeAddr).catch(() => null))?.sender);
472
+ const evidenceHash = itxObj.evidence && typeof itxObj.evidence === "object" ? itxObj.evidence.hash : void 0;
473
+ if (typeof evidenceHash === "string" && evidenceHash.trim() && typeof this.statedb.tx?.get === "function") {
474
+ const evTxState = await this.statedb.tx.get(evidenceHash.trim()).catch(() => null);
475
+ const evItx = evTxState?.tx?.itxJson && typeof evTxState.tx.itxJson === "object" ? evTxState.tx.itxJson : (evTxState?.tx)?.itx && typeof (evTxState?.tx).itx === "object" ? (evTxState?.tx).itx : {};
476
+ const evOutputs = Array.isArray(evItx.outputs) ? evItx.outputs : Array.isArray(evItx.outputsList) ? evItx.outputsList : [];
477
+ for (const out of evOutputs) {
478
+ addCandidate(out?.owner);
479
+ addCandidate(out?.address);
480
+ }
481
+ }
482
+ } else if (txType === "fg:t:revoke_stake" || txType === "RevokeStakeTx") {
483
+ const stakeAddr = typeof itxObj.address === "string" ? itxObj.address.trim() : "";
484
+ if (stakeAddr && typeof this.statedb.stake?.get === "function") addCandidate((await this.statedb.stake.get(stakeAddr).catch(() => null))?.sender);
485
+ }
486
+ const isAcquireAsset = txType === "fg:t:acquire_asset_v2" || txType === "AcquireAssetV2Tx" || txType === "fg:t:acquire_asset_v3" || txType === "AcquireAssetV3Tx";
487
+ if (isAcquireAsset || txType === "fg:t:mint_asset" || txType === "MintAssetTx") {
488
+ const factoryAddr = typeof itxObj.factory === "string" ? itxObj.factory.trim() : "";
489
+ if (factoryAddr && typeof this.statedb.factory?.get === "function") {
490
+ const factoryState = await this.statedb.factory.get(factoryAddr).catch(() => null);
491
+ addCandidate(factoryState?.owner);
492
+ if (Array.isArray(factoryState?.trustedIssuers)) for (const ti of factoryState.trustedIssuers) addCandidate(ti);
493
+ if (isAcquireAsset && factoryState?.settlement === "instant" && Array.isArray(factoryState?.hooks)) {
494
+ for (const hook of factoryState.hooks) if (hook?.name === "mint" && hook?.type === "contract" && Array.isArray(hook?.compiled)) for (const cmd of hook.compiled) addCandidate(cmd?.args?.to);
495
+ }
496
+ }
497
+ }
498
+ if (txType === "fg:t:update_asset" || txType === "UpdateAssetTx" || txType === "fg:t:consume_asset" || txType === "ConsumeAssetTx") {
499
+ const assetAddr = typeof itxObj.address === "string" ? itxObj.address.trim() : "";
500
+ if (assetAddr && typeof this.statedb.asset?.get === "function") {
501
+ const assetState = await this.statedb.asset.get(assetAddr).catch(() => null);
502
+ addCandidate(assetState?.issuer);
503
+ if (txType === "fg:t:consume_asset" || txType === "ConsumeAssetTx") addCandidate(assetState?.owner);
504
+ }
505
+ }
506
+ }
507
+ const findBlockedInLineage = async (seedActor) => {
508
+ const visited = /* @__PURE__ */ new Set();
509
+ const queue = [seedActor];
510
+ const MAX_LINEAGE_EXPAND = 32;
511
+ while (queue.length > 0 && visited.size < MAX_LINEAGE_EXPAND) {
512
+ const rawCurr = queue.shift();
513
+ if (!rawCurr) continue;
514
+ const bareCurr = toAddress(rawCurr).trim();
515
+ const keyCurr = bareCurr || rawCurr;
516
+ if (visited.has(keyCurr)) continue;
517
+ visited.add(keyCurr);
518
+ if (await Promise.resolve(this.admissionBlockedCheck(rawCurr))) return rawCurr;
519
+ if (bareCurr && bareCurr !== rawCurr && await Promise.resolve(this.admissionBlockedCheck(bareCurr))) return bareCurr;
520
+ if (isValid(keyCurr) && typeof this.statedb?.account?.get === "function") {
521
+ const accState = await this.statedb.account.get(keyCurr, { traceMigration: false }).catch(() => null);
522
+ if (accState) {
523
+ if (typeof accState.address === "string" && accState.address.trim()) {
524
+ const nextKey = toAddress(accState.address.trim()).trim();
525
+ if (nextKey && !visited.has(nextKey)) queue.push(nextKey);
526
+ }
527
+ if (Array.isArray(accState.migratedFrom)) {
528
+ for (const prev of accState.migratedFrom) if (typeof prev === "string" && prev.trim()) {
529
+ const prevKey = toAddress(prev.trim()).trim();
530
+ if (prevKey && !visited.has(prevKey)) queue.push(prevKey);
531
+ }
532
+ }
533
+ if (Array.isArray(accState.migratedTo)) {
534
+ for (const nextAddr of accState.migratedTo) if (typeof nextAddr === "string" && nextAddr.trim()) {
535
+ const toKey = toAddress(nextAddr.trim()).trim();
536
+ if (toKey && !visited.has(toKey)) queue.push(toKey);
537
+ }
538
+ }
539
+ }
540
+ }
541
+ }
542
+ return null;
543
+ };
544
+ for (const actor of candidateActors) {
545
+ const blockedMatch = await findBlockedInLineage(actor);
546
+ if (blockedMatch) {
547
+ const blockErr = new CustomError("FORBIDDEN", `Account ${blockedMatch} is blocked by node admission policy`);
548
+ blockErr._strikeRecorded = true;
549
+ throw blockErr;
550
+ }
551
+ }
552
+ const extraObj = context.extra && typeof context.extra === "object" ? context.extra : {};
553
+ const rawTxExtra = extraObj.txExtra && typeof extraObj.txExtra === "object" ? extraObj.txExtra : void 0;
554
+ for (const candidateHeaders of [extraObj.gasStakeHeaders, rawTxExtra?.gasStakeHeaders]) {
555
+ const gasHeaders = candidateHeaders;
556
+ if (typeof gasHeaders?.token === "string" && gasHeaders.token.includes(".")) try {
557
+ const parts = gasHeaders.token.split(".");
558
+ if (parts.length === 3 && parts[1].length <= 16384) {
559
+ const payloadJson = Buffer.from(parts[1], "base64url").toString("utf8");
560
+ const decoded = JSON.parse(payloadJson);
561
+ if (typeof decoded?.iss === "string" && decoded.iss.trim()) {
562
+ const blockedSponsor = await findBlockedInLineage(decoded.iss.trim());
563
+ if (blockedSponsor) {
564
+ const sponsorErr = new CustomError("FORBIDDEN", `Gas sponsor ${blockedSponsor} is blocked by node admission policy`);
565
+ sponsorErr._unauthenticatedExtraFailure = true;
566
+ sponsorErr._strikeRecorded = true;
567
+ throw sponsorErr;
568
+ }
569
+ }
570
+ }
571
+ } catch (err) {
572
+ if (err?.code === "FORBIDDEN") throw err;
573
+ }
574
+ }
575
+ for (const candidatePass of [extraObj.gasPass, rawTxExtra?.gasPass]) {
576
+ const gasPass = candidatePass;
577
+ if (typeof gasPass?.stakeId === "string" && gasPass.stakeId.trim() && typeof this.statedb?.stake?.get === "function") {
578
+ const stakeState = await this.statedb.stake.get(gasPass.stakeId.trim()).catch(() => null);
579
+ for (const passActor of [stakeState?.sender, stakeState?.owner]) if (typeof passActor === "string" && passActor.trim()) {
580
+ const blockedPassActor = await findBlockedInLineage(passActor.trim());
581
+ if (blockedPassActor) {
582
+ const passErr = new CustomError("FORBIDDEN", `Gas pass sponsor ${blockedPassActor} is blocked by node admission policy`);
583
+ passErr._unauthenticatedExtraFailure = true;
584
+ passErr._strikeRecorded = true;
585
+ throw passErr;
586
+ }
587
+ }
588
+ }
589
+ }
590
+ }
591
+ async getFollowerStatus() {
592
+ if (this.nodeRuntime && typeof this.nodeRuntime.getFollowerStatus === "function") return this.nodeRuntime.getFollowerStatus();
593
+ return null;
594
+ }
595
+ async signForwardedSendTxReceipt(txHash) {
596
+ if (this.readonly || this.nodeRuntime && this.nodeRuntime.role !== "validator") return null;
597
+ const normalizedTxHash = txHash ? txHash.replace(/^0x/i, "").toUpperCase() : "";
598
+ const localEntry = txHash && typeof this.ledger?.get === "function" ? await this.ledger.get(txHash) || (normalizedTxHash && normalizedTxHash !== txHash ? await this.ledger.get(normalizedTxHash) : null) : null;
599
+ if (typeof this.nodeRuntime?.shouldHandleWriteLocally === "function" && !this.nodeRuntime.shouldHandleWriteLocally() && !localEntry) return null;
600
+ const proposer = this.ledger?.getProposer?.() || null;
601
+ if (!proposer || typeof this.ledger?.signConsensusDigest !== "function") return null;
602
+ const digest = computeForwardReceiptDigest({
603
+ chainId: this.config?.chainId || this.ledger.chainId,
604
+ txHash,
605
+ proposer
606
+ });
607
+ const signature = await this.ledger.signConsensusDigest(digest);
608
+ if (!signature) return null;
609
+ let commitProof;
610
+ if (localEntry && typeof this.ledger?.getCheckpointForSequence === "function" && typeof this.ledger?.getMerkleProof === "function") {
611
+ const [checkpoint, merkleProof] = await Promise.all([this.ledger.getCheckpointForSequence(localEntry.sequence).catch(() => null), this.ledger.getMerkleProof(localEntry.sequence).catch(() => null)]);
612
+ if (checkpoint?.qc && merkleProof) commitProof = Buffer.from(JSON.stringify({
613
+ sequence: localEntry.sequence,
614
+ entryHash: localEntry.entryHash,
615
+ stateCommitHash: localEntry.stateCommitHash ?? "",
616
+ proof: merkleProof,
617
+ checkpoint
618
+ }), "utf8").toString("base64");
619
+ }
620
+ return {
621
+ proposer,
622
+ signature,
623
+ ...commitProof ? { commitProof } : {}
624
+ };
625
+ }
626
+ trackIndexWrite(promise) {
627
+ const settled = promise.then(() => void 0, () => void 0);
628
+ this.pendingIndexWrites.add(settled);
629
+ settled.finally(() => {
630
+ this.pendingIndexWrites.delete(settled);
631
+ });
632
+ }
633
+ async flushIndexWrites() {
634
+ while (this.pendingIndexWrites.size > 0) await Promise.allSettled([...this.pendingIndexWrites]);
635
+ }
320
636
  sendTx({ tx: txBase64, extra }, ctx = {}) {
321
637
  debug("sendTx", {
322
638
  txBase64,
323
639
  request: ctx.request
324
640
  });
325
- if (process.env.CHAIN_MODE === "readonly") throw new CustomError("FORBIDDEN", "This chain node is running in readonly mode");
326
- const maxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
327
- if (this.queue.length + this.inFlightPreFlights >= maxRequest) throw new CustomError("FORBIDDEN", "Chain is busy");
641
+ if (this.isShuttingDown) throw new CustomError("SERVICE_UNAVAILABLE", "Resolver is shutting down");
642
+ const runtime = this.nodeRuntime;
643
+ if (runtime?.isHalted?.()) throw new CustomError("NODE_HALTED", "Chain node is halted fail-closed");
644
+ if (runtime ? runtime.role !== "validator" : (() => {
645
+ const normalizedRole = getNormalizedEnvLower("CHAIN_ROLE");
646
+ const normalizedMode = getNormalizedEnvLower("CHAIN_MODE");
647
+ return normalizedRole === "follower" || normalizedRole === "standby" || normalizedMode === "readonly";
648
+ })()) {
649
+ if ((runtime ? runtime.writePolicy : getNormalizedEnvLower("CHAIN_WRITE_POLICY") === "forward" ? "forward" : "reject") !== "forward" || typeof runtime?.forwardSendTx !== "function") throw new CustomError("FORBIDDEN", "This chain node is running in readonly mode (FOLLOWER_READ_ONLY)");
650
+ assertRawWireEnvelope(txBase64, this.config);
651
+ if (ctx.forwardedHop !== void 0) throw new CustomError("FORWARD_LOOP_DETECTED", "Refusing to forward sendTx: request already carries X-Ocap-Forwarded-Hop header");
652
+ const pinnedTxTime$1 = ctx.txTime !== void 0 ? ctx.txTime : typeof this.now === "function" ? this.now() : Date.now();
653
+ return (async () => {
654
+ await this.initialize();
655
+ if (runtime?.isHalted?.()) throw new CustomError("NODE_HALTED", "Chain node is halted fail-closed");
656
+ const forwardContext = {
657
+ txBase64,
658
+ statedb: this.statedb,
659
+ indexdb: this.indexdb,
660
+ ledger: this.ledger,
661
+ config: this.config,
662
+ filter: this.filter,
663
+ logger: this.logger,
664
+ extra: {
665
+ ...ctx,
666
+ txTime: pinnedTxTime$1,
667
+ txExtra: extra
668
+ }
669
+ };
670
+ await inspectTransactionPreFlight(forwardContext);
671
+ await assertStatelessTxRules(forwardContext);
672
+ await this.assertNotBlockedAtAdmission(forwardContext);
673
+ const forwarded = await runtime.forwardSendTx({
674
+ tx: txBase64,
675
+ extra
676
+ }, ctx);
677
+ this.txForwardedTotal += 1;
678
+ if (forwarded?.hash && forwarded?.warning !== void 0) setTxSecurityWarningForHash(forwarded.hash, forwarded.warning, this.statedb);
679
+ return forwarded.hash;
680
+ })();
681
+ }
682
+ if (runtime?.role === "validator" && typeof runtime.shouldHandleWriteLocally === "function" && !runtime.shouldHandleWriteLocally()) {
683
+ if (ctx.forwardedHop !== void 0) throw new CustomError("CONSENSUS_NOT_LEADER", "Validator is not the active view leader for forwarded sendTx");
684
+ if (runtime.writePolicy !== "forward" || typeof runtime.forwardSendTx !== "function") throw new CustomError("CONSENSUS_NOT_LEADER", "Validator is not the active view leader");
685
+ assertRawWireEnvelope(txBase64, this.config);
686
+ const pinnedTxTime$1 = ctx.txTime !== void 0 ? ctx.txTime : typeof this.now === "function" ? this.now() : Date.now();
687
+ return (async () => {
688
+ await this.initialize();
689
+ if (runtime.isHalted()) throw new CustomError("NODE_HALTED", "Chain node is halted fail-closed");
690
+ const forwardContext = {
691
+ txBase64,
692
+ statedb: this.statedb,
693
+ indexdb: this.indexdb,
694
+ ledger: this.ledger,
695
+ config: this.config,
696
+ filter: this.filter,
697
+ logger: this.logger,
698
+ extra: {
699
+ ...ctx,
700
+ txTime: pinnedTxTime$1,
701
+ txExtra: extra
702
+ }
703
+ };
704
+ await inspectTransactionPreFlight(forwardContext);
705
+ await assertStatelessTxRules(forwardContext);
706
+ await this.assertNotBlockedAtAdmission(forwardContext);
707
+ const forwarded = await runtime.forwardSendTx({
708
+ tx: txBase64,
709
+ extra
710
+ }, ctx);
711
+ this.txForwardedTotal += 1;
712
+ if (forwarded?.hash && forwarded?.warning !== void 0) setTxSecurityWarningForHash(forwarded.hash, forwarded.warning, this.statedb);
713
+ return forwarded.hash;
714
+ })();
715
+ }
716
+ const maxRequest = this.getMaxTxRequest();
717
+ if (this.queue.length + this.inFlightPreFlights >= maxRequest) {
718
+ this.txPreFlightRejectedTotal += 1;
719
+ throw new CustomError("FORBIDDEN", "Chain is busy");
720
+ }
328
721
  assertRawWireEnvelope(txBase64, this.config);
329
722
  const timer = new TxTimer();
330
723
  timer.setQueueState({
331
724
  waitingAtEnqueue: Math.max(0, this.queue.length - (this.queue.pending ?? 0)),
332
725
  runningAtEnqueue: this.queue.pending ?? 0,
333
- concurrencyConfig: txRequestConfig.concurrent
726
+ concurrencyConfig: this.queue.concurrency ?? txRequestConfig.concurrent
334
727
  });
728
+ const pinnedTxTime = ctx.txTime !== void 0 ? ctx.txTime : typeof this.now === "function" ? this.now() : Date.now();
335
729
  const context = {
336
730
  txBase64,
337
731
  statedb: this.statedb,
@@ -341,8 +735,10 @@ var OCAPResolver = class {
341
735
  filter: this.filter,
342
736
  logger: this.logger,
343
737
  timer,
738
+ ...runtime?.getConsensusCommitter ? { consensusCommitter: runtime.getConsensusCommitter() } : {},
344
739
  extra: {
345
740
  ...ctx,
741
+ txTime: pinnedTxTime,
346
742
  txExtra: extra
347
743
  }
348
744
  };
@@ -353,13 +749,18 @@ var OCAPResolver = class {
353
749
  if (!preFlightSlotReleased) {
354
750
  preFlightSlotReleased = true;
355
751
  this.inFlightPreFlights = Math.max(0, this.inFlightPreFlights - 1);
752
+ if (this.inFlightPreFlights === 0 && this.preFlightDrainWaiters.length > 0) {
753
+ const waiters = this.preFlightDrainWaiters.splice(0, this.preFlightDrainWaiters.length);
754
+ for (const notify of waiters) notify();
755
+ }
356
756
  }
357
757
  };
358
758
  const enqueueAfterPreFlight = async () => {
359
759
  try {
360
- await this.initializationPromise;
760
+ await this.initialize();
361
761
  await inspectTransactionPreFlight(context);
362
762
  await assertStatelessTxRules(context);
763
+ await this.assertNotBlockedAtAdmission(context);
363
764
  const preTx = context.tx;
364
765
  const preTxHash = context.txHash;
365
766
  if (preTx) await assertTxAdmission({
@@ -393,27 +794,54 @@ var OCAPResolver = class {
393
794
  this.logger?.warn?.("Failed to record security strike", { error: strikeErr });
394
795
  }
395
796
  releasePreFlightSlot();
797
+ this.txPreFlightRejectedTotal += 1;
396
798
  reject(preFlightErr);
397
799
  return;
398
800
  }
399
- releasePreFlightSlot();
400
- const currentMaxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
801
+ const currentMaxRequest = this.getMaxTxRequest();
401
802
  if (this.queue.length >= currentMaxRequest) {
803
+ releasePreFlightSlot();
804
+ this.txPreFlightRejectedTotal += 1;
402
805
  reject(new CustomError("FORBIDDEN", "Chain is busy"));
403
806
  return;
404
807
  }
405
808
  const task = async () => {
406
809
  timer.mark("queueWait");
407
810
  try {
408
- const result = await this.executor.execute(context);
811
+ const activeRuntime = this.nodeRuntime;
812
+ if (activeRuntime?.getConsensusCommitter && !("consensusCommitter" in context)) context.consensusCommitter = activeRuntime.getConsensusCommitter();
813
+ const result = typeof activeRuntime?.executeWithConsensusLock === "function" ? await activeRuntime.executeWithConsensusLock(() => this.executor.execute(context)) : await this.executor.execute(context);
409
814
  if (result?.txHash && result?.securityWarning) setTxSecurityWarningForHash(result.txHash, result.securityWarning, this.statedb);
815
+ this.txAcceptedTotal += 1;
816
+ this.recordCommittedTxSample();
410
817
  resolve(result.txHash);
411
818
  } catch (err) {
819
+ if (err?.isConsensusAbort === true) {
820
+ const activeRuntime = this.nodeRuntime;
821
+ if (ctx.forwardedHop === void 0 && activeRuntime?.writePolicy === "forward" && typeof activeRuntime.forwardSendTx === "function") try {
822
+ const forwarded = await activeRuntime.forwardSendTx({
823
+ tx: txBase64,
824
+ extra
825
+ }, ctx);
826
+ if (forwarded?.hash && forwarded?.warning !== void 0) setTxSecurityWarningForHash(forwarded.hash, forwarded.warning, this.statedb);
827
+ this.txForwardedTotal += 1;
828
+ resolve(forwarded.hash);
829
+ return;
830
+ } catch (forwardErr) {
831
+ reject(forwardErr);
832
+ return;
833
+ }
834
+ reject(err);
835
+ return;
836
+ }
837
+ if (Number(context.ledgerSequence ?? 0) > 0) this.txPersistedFailedTotal += 1;
838
+ else this.txPreFlightRejectedTotal += 1;
412
839
  await this._indexRejectedLedgerTx(context, err);
413
840
  reject(err);
414
841
  }
415
842
  };
416
843
  this.queue.push(task);
844
+ releasePreFlightSlot();
417
845
  };
418
846
  enqueueAfterPreFlight().catch((err) => {
419
847
  releasePreFlightSlot();
@@ -520,6 +948,7 @@ var OCAPResolver = class {
520
948
  return getTxSecurityWarningByHash(txHash, this.statedb);
521
949
  }
522
950
  async getTx({ hash }, ctx) {
951
+ assertResolverNotHaltedForDataRead(this);
523
952
  if (patterns.txHash.test(hash)) {
524
953
  const normalizedHash = hash.toUpperCase();
525
954
  const stateTx = await this._getState({
@@ -539,18 +968,60 @@ var OCAPResolver = class {
539
968
  return null;
540
969
  }
541
970
  getBlock() {
971
+ assertResolverNotHaltedForDataRead(this);
542
972
  return null;
543
973
  }
544
974
  getBlocks() {
975
+ assertResolverNotHaltedForDataRead(this);
545
976
  return [];
546
977
  }
547
978
  getUnconfirmedTxs() {
979
+ assertResolverNotHaltedForDataRead(this);
548
980
  return [];
549
981
  }
982
+ async resolveNodeSyncMetadata() {
983
+ if (this.nodeRuntime) {
984
+ const reconciling = Boolean(this.nodeRuntime.isReconciling?.());
985
+ if (typeof this.nodeRuntime.getFollowerStatus === "function") {
986
+ const status = await this.nodeRuntime.getFollowerStatus();
987
+ return {
988
+ synced: status.synced && !status.halted && !reconciling,
989
+ nodeRole: status.nodeRole,
990
+ writePolicy: status.writePolicy,
991
+ syncLagEntries: status.syncLagEntries,
992
+ verifiedCheckpointHeight: status.verifiedCheckpointHeight,
993
+ halted: status.halted
994
+ };
995
+ }
996
+ const [synced, latestCp$1] = await Promise.all([Promise.resolve(this.nodeRuntime.isSynced()), this.ledger?.getCheckpoint ? this.ledger.getCheckpoint().catch(() => null) : Promise.resolve(null)]);
997
+ const halted = this.nodeRuntime.isHalted();
998
+ return {
999
+ synced: synced && !halted && !reconciling,
1000
+ nodeRole: this.nodeRuntime.role,
1001
+ writePolicy: this.nodeRuntime.writePolicy,
1002
+ syncLagEntries: null,
1003
+ verifiedCheckpointHeight: latestCp$1?.height ?? 0,
1004
+ halted
1005
+ };
1006
+ }
1007
+ const latestCp = this.ledger?.getCheckpoint ? await this.ledger.getCheckpoint().catch(() => null) : null;
1008
+ const rawRole = getNormalizedEnvLower("CHAIN_ROLE");
1009
+ const rawMode = getNormalizedEnvLower("CHAIN_MODE");
1010
+ const nodeRole = rawRole === "follower" || rawRole === "standby" ? rawRole : rawMode === "readonly" ? "follower" : "validator";
1011
+ return {
1012
+ synced: true,
1013
+ nodeRole,
1014
+ writePolicy: getNormalizedEnvLower("CHAIN_WRITE_POLICY") === "forward" ? "forward" : "reject",
1015
+ syncLagEntries: nodeRole === "validator" ? 0 : null,
1016
+ verifiedCheckpointHeight: latestCp?.height ?? 0,
1017
+ halted: false
1018
+ };
1019
+ }
550
1020
  async getChainInfo() {
1021
+ const [totalTxs, syncMeta] = await Promise.all([this.indexdb.tx.count(), this.resolveNodeSyncMetadata()]);
551
1022
  return {
552
1023
  id: this.chainAddr,
553
- totalTxs: await this.indexdb.tx.count(),
1024
+ totalTxs,
554
1025
  blockHash: md5(""),
555
1026
  blockHeight: 0,
556
1027
  blockTime: "",
@@ -562,12 +1033,18 @@ var OCAPResolver = class {
562
1033
  moniker: this.config.chainId,
563
1034
  network: this.config.chainId,
564
1035
  supportedTxs: this.config.transaction.supportedTxs,
565
- synced: true,
566
- votingPower: "10"
1036
+ synced: syncMeta.synced,
1037
+ nodeRole: syncMeta.nodeRole,
1038
+ writePolicy: syncMeta.writePolicy,
1039
+ syncLagEntries: syncMeta.syncLagEntries,
1040
+ verifiedCheckpointHeight: syncMeta.verifiedCheckpointHeight,
1041
+ halted: syncMeta.halted,
1042
+ votingPower: syncMeta.nodeRole === "validator" ? "10" : "0"
567
1043
  };
568
1044
  }
569
- getNodeInfo() {
570
- return Promise.resolve({
1045
+ async getNodeInfo() {
1046
+ const syncMeta = await this.resolveNodeSyncMetadata();
1047
+ return {
571
1048
  address: this.chainAddr,
572
1049
  appHash: md5((/* @__PURE__ */ new Date()).toISOString()),
573
1050
  consensusVersion: this.consensus,
@@ -584,53 +1061,166 @@ var OCAPResolver = class {
584
1061
  network: this.config.chainId,
585
1062
  p2pAddress: "",
586
1063
  supportedTxs: this.config.transaction.supportedTxs,
587
- synced: true,
588
- votingPower: "10"
589
- });
1064
+ synced: syncMeta.synced,
1065
+ nodeRole: syncMeta.nodeRole,
1066
+ writePolicy: syncMeta.writePolicy,
1067
+ syncLagEntries: syncMeta.syncLagEntries,
1068
+ verifiedCheckpointHeight: syncMeta.verifiedCheckpointHeight,
1069
+ halted: syncMeta.halted,
1070
+ votingPower: syncMeta.nodeRole === "validator" ? "10" : "0"
1071
+ };
590
1072
  }
591
- getNetInfo() {
592
- return Promise.resolve({
1073
+ async getNetInfo() {
1074
+ if (!this.nodeRuntime || typeof this.nodeRuntime.getRuntimeDiagnostics !== "function") return {
593
1075
  listeners: [],
594
1076
  listening: true,
595
1077
  nPeers: 0,
596
1078
  peers: []
597
- });
1079
+ };
1080
+ const diag = await Promise.resolve(this.nodeRuntime.getRuntimeDiagnostics({ includePrivateTopology: false }));
1081
+ const listening = !this.nodeRuntime.isHalted();
1082
+ const defaultGeo = {
1083
+ city: "Unknown",
1084
+ country: "Unknown",
1085
+ latitude: 0,
1086
+ longitude: 0
1087
+ };
1088
+ if (diag.mode === "hotstuff" && Array.isArray(diag.validators)) {
1089
+ const peerValidators = diag.validators.filter((v$1) => !v$1.isSelf && v$1.reachable && typeof v$1.did === "string");
1090
+ return {
1091
+ listeners: [],
1092
+ listening,
1093
+ nPeers: peerValidators.length,
1094
+ peers: peerValidators.map((peer) => ({
1095
+ id: peer.did,
1096
+ moniker: peer.did,
1097
+ network: this.config.chainId,
1098
+ consensusVersion: this.consensus,
1099
+ ip: "",
1100
+ geoInfo: defaultGeo
1101
+ }))
1102
+ };
1103
+ }
1104
+ if (diag.mode === "follower") {
1105
+ const leaderRouter = diag.leaderRouter;
1106
+ const candidates = Array.isArray(leaderRouter?.candidates) ? leaderRouter.candidates : [];
1107
+ const activePeers = candidates.length > 0 ? candidates.filter((c) => c.reachable) : Number(diag.peerCount ?? 0) > 0 && Boolean(diag.hasActiveLeader) ? [{
1108
+ id: "upstream-peer-1",
1109
+ reachable: true
1110
+ }] : [];
1111
+ return {
1112
+ listeners: [],
1113
+ listening,
1114
+ nPeers: activePeers.length,
1115
+ peers: activePeers.map((c, idx) => ({
1116
+ id: c.id || `upstream-peer-${idx + 1}`,
1117
+ moniker: c.id || `upstream-peer-${idx + 1}`,
1118
+ network: this.config.chainId,
1119
+ consensusVersion: this.consensus,
1120
+ ip: "",
1121
+ geoInfo: defaultGeo
1122
+ }))
1123
+ };
1124
+ }
1125
+ return {
1126
+ listeners: [],
1127
+ listening,
1128
+ nPeers: 0,
1129
+ peers: []
1130
+ };
598
1131
  }
599
- getValidatorsInfo() {
600
- return Promise.resolve({
1132
+ async getValidatorsInfo() {
1133
+ assertResolverNotHaltedForDataRead(this);
1134
+ const formatPubKey = (rawPk) => {
1135
+ const cleanPkHex = rawPk ? rawPk.replace(/^0x/i, "") : "";
1136
+ if (!cleanPkHex || !/^[0-9a-fA-F]+$/.test(cleanPkHex)) return;
1137
+ return {
1138
+ type: cleanPkHex.length === 64 ? "ed25519" : "secp256k1",
1139
+ data: cleanPkHex
1140
+ };
1141
+ };
1142
+ if (this.nodeRuntime && this.nodeRuntime.getConsensusMode?.() === "hotstuff" && typeof this.nodeRuntime.getRuntimeDiagnostics === "function") {
1143
+ const diag = await Promise.resolve(this.nodeRuntime.getRuntimeDiagnostics({ includePrivateTopology: false }));
1144
+ if (Array.isArray(diag.validators) && diag.validators.length > 0) {
1145
+ const leaderDid = typeof diag.currentLeaderDid === "string" ? diag.currentLeaderDid : "";
1146
+ return {
1147
+ blockHeight: 0,
1148
+ validators: diag.validators.map((v$1) => {
1149
+ const pk$1 = formatPubKey(v$1.publicKey);
1150
+ return {
1151
+ address: v$1.did,
1152
+ ...pk$1 ? { pubKey: pk$1 } : {},
1153
+ name: "",
1154
+ proposerPriority: v$1.isCurrentViewLeader || v$1.did === leaderDid ? "1" : "0",
1155
+ votingPower: "10"
1156
+ };
1157
+ })
1158
+ };
1159
+ }
1160
+ }
1161
+ const activeProposer = this.ledger?.getProposer?.() || this.config?.moderator?.address || fromPublicKey(this.chainAddr);
1162
+ const pk = formatPubKey(this.ledger?.getProposerPublicKey?.());
1163
+ return {
601
1164
  blockHeight: 0,
602
1165
  validators: [{
603
- address: this.config?.moderator?.address || fromPublicKey(this.chainAddr),
1166
+ address: activeProposer,
1167
+ ...pk ? { pubKey: pk } : {},
604
1168
  name: "",
605
1169
  proposerPriority: "0",
606
1170
  votingPower: "10"
607
1171
  }]
608
- });
1172
+ };
1173
+ }
1174
+ async getLedgerInfo() {
1175
+ assertResolverNotHaltedForDataRead(this);
1176
+ if (!this.ledger) return null;
1177
+ const latestSequence = await this.ledger.getLatestSequence();
1178
+ const rawV2From = typeof this.ledger.getEntryHashV2From === "function" ? this.ledger.getEntryHashV2From() : void 0;
1179
+ const entryHashV2From = rawV2From === void 0 ? null : rawV2From === Number.POSITIVE_INFINITY ? "infinity" : String(rawV2From);
1180
+ const proposer = this.ledger.getProposer?.() || this.config?.moderator?.address || null;
1181
+ const proposerPublicKey = this.ledger.getProposerPublicKey?.() || null;
1182
+ const checkpointSigningEnabled = typeof this.ledger.isCheckpointSigningEnabled === "function" ? this.ledger.isCheckpointSigningEnabled() : Boolean(proposerPublicKey);
1183
+ return {
1184
+ chainId: this.config?.chainId || this.ledger.chainId,
1185
+ latestSequence,
1186
+ entryHashV2From,
1187
+ proposer,
1188
+ proposerPublicKey,
1189
+ checkpointSigningEnabled
1190
+ };
609
1191
  }
610
1192
  async getLatestCheckpoint({ height } = {}) {
1193
+ assertResolverNotHaltedForDataRead(this);
611
1194
  if (!this.ledger) return null;
612
1195
  const targetHeight = height !== void 0 && height !== null ? Number(height) : void 0;
613
1196
  return this.ledger.getCheckpoint(targetHeight);
614
1197
  }
615
1198
  async getLedgerEntry({ hash, sequence } = {}) {
1199
+ assertResolverNotHaltedForDataRead(this);
616
1200
  if (!this.ledger) return null;
617
1201
  if (sequence !== void 0 && sequence !== null) return this.ledger.getBySequence(Number(sequence));
618
1202
  if (hash) return this.ledger.get(String(hash));
619
1203
  return null;
620
1204
  }
621
1205
  async getMerkleProof({ sequence }) {
1206
+ assertResolverNotHaltedForDataRead(this);
622
1207
  if (!this.ledger || sequence === void 0 || sequence === null) return null;
623
1208
  const seq = Number(sequence);
624
1209
  const [proof, checkpoint] = await Promise.all([this.ledger.getMerkleProof(seq), this.ledger.getCheckpointForSequence(seq)]);
1210
+ const rawV2From = typeof this.ledger.getEntryHashV2From === "function" ? this.ledger.getEntryHashV2From() : void 0;
1211
+ const entryHashV2From = rawV2From === void 0 ? void 0 : rawV2From === Number.POSITIVE_INFINITY ? "infinity" : String(rawV2From);
625
1212
  return {
626
1213
  proof,
627
- checkpoint
1214
+ checkpoint,
1215
+ ...entryHashV2From !== void 0 ? { entryHashV2From } : {}
628
1216
  };
629
1217
  }
630
1218
  getConfig() {
1219
+ assertResolverNotHaltedForDataRead(this);
631
1220
  return JSON.stringify(this.config);
632
1221
  }
633
1222
  getAccountState({ address, traceMigration = true, expandContext = true }, ctx) {
1223
+ assertResolverNotHaltedForDataRead(this);
634
1224
  return this._getState({
635
1225
  table: "account",
636
1226
  id: address,
@@ -647,6 +1237,7 @@ var OCAPResolver = class {
647
1237
  });
648
1238
  }
649
1239
  getStakeState({ address }, ctx) {
1240
+ assertResolverNotHaltedForDataRead(this);
650
1241
  return this._getState({
651
1242
  table: "stake",
652
1243
  id: address,
@@ -662,6 +1253,7 @@ var OCAPResolver = class {
662
1253
  });
663
1254
  }
664
1255
  async getRollupState({ address }, ctx) {
1256
+ assertResolverNotHaltedForDataRead(this);
665
1257
  const rollup = await this._getState({
666
1258
  table: "rollup",
667
1259
  id: address,
@@ -684,6 +1276,7 @@ var OCAPResolver = class {
684
1276
  return rollup;
685
1277
  }
686
1278
  async getRollupBlock({ hash, height, rollupAddress }, ctx) {
1279
+ assertResolverNotHaltedForDataRead(this);
687
1280
  if (hash) return this._getState({
688
1281
  table: "rollupBlock",
689
1282
  id: hash,
@@ -707,6 +1300,7 @@ var OCAPResolver = class {
707
1300
  throw new Error("Can not get rollup block without hash or height + rollup");
708
1301
  }
709
1302
  getAssetState({ address }, ctx) {
1303
+ assertResolverNotHaltedForDataRead(this);
710
1304
  return this._getState({
711
1305
  table: "asset",
712
1306
  id: address,
@@ -719,6 +1313,7 @@ var OCAPResolver = class {
719
1313
  });
720
1314
  }
721
1315
  getEvidenceState({ hash }, ctx) {
1316
+ assertResolverNotHaltedForDataRead(this);
722
1317
  return this._getState({
723
1318
  table: "evidence",
724
1319
  id: hash,
@@ -727,6 +1322,7 @@ var OCAPResolver = class {
727
1322
  });
728
1323
  }
729
1324
  getFactoryState({ address }, ctx) {
1325
+ assertResolverNotHaltedForDataRead(this);
730
1326
  return this._getState({
731
1327
  table: "factory",
732
1328
  id: address,
@@ -745,6 +1341,7 @@ var OCAPResolver = class {
745
1341
  });
746
1342
  }
747
1343
  async getTokenState({ address }, ctx) {
1344
+ assertResolverNotHaltedForDataRead(this);
748
1345
  const state = await this._getState({
749
1346
  table: "token",
750
1347
  id: address,
@@ -758,6 +1355,7 @@ var OCAPResolver = class {
758
1355
  return state;
759
1356
  }
760
1357
  getTokenFactoryState(args, ctx) {
1358
+ assertResolverNotHaltedForDataRead(this);
761
1359
  return this._getState({
762
1360
  table: "tokenFactory",
763
1361
  id: args.address,
@@ -780,6 +1378,7 @@ var OCAPResolver = class {
780
1378
  });
781
1379
  }
782
1380
  getDelegateState({ address }, ctx) {
1381
+ assertResolverNotHaltedForDataRead(this);
783
1382
  return this._getState({
784
1383
  table: "delegation",
785
1384
  id: address,
@@ -795,6 +1394,7 @@ var OCAPResolver = class {
795
1394
  });
796
1395
  }
797
1396
  async getAccountTokens({ address, token }, ctx) {
1397
+ assertResolverNotHaltedForDataRead(this);
798
1398
  if (!address) return [];
799
1399
  let state = null;
800
1400
  if (toTypeInfo(address).role === types.RoleType.ROLE_ASSET) state = await this._getState({
@@ -836,6 +1436,7 @@ var OCAPResolver = class {
836
1436
  }));
837
1437
  }
838
1438
  getForgeState() {
1439
+ assertResolverNotHaltedForDataRead(this);
839
1440
  const { accounts, token, transaction, vaults } = this.config;
840
1441
  return Promise.resolve({
841
1442
  accountConfig: accounts,
@@ -874,6 +1475,7 @@ var OCAPResolver = class {
874
1475
  });
875
1476
  }
876
1477
  async getForgeStats() {
1478
+ assertResolverNotHaltedForDataRead(this);
877
1479
  const [accountCount, assetCount, txCount] = await Promise.all([
878
1480
  this.indexdb.account.count(),
879
1481
  this.indexdb.asset.count(),
@@ -903,12 +1505,15 @@ var OCAPResolver = class {
903
1505
  };
904
1506
  }
905
1507
  async listTransactions(args = {}, ctx) {
1508
+ assertResolverNotHaltedForDataRead(this);
906
1509
  return await this._doPaginatedSearch("listTransactions", withTxProjection(args, ctx), "transactions", "tx.itxJson.data", ctx);
907
1510
  }
908
1511
  listAssets(args = {}, ctx) {
1512
+ assertResolverNotHaltedForDataRead(this);
909
1513
  return this._doPaginatedSearch("listAssets", args, "assets", "data", ctx);
910
1514
  }
911
1515
  listAssetTransactions(args = {}, ctx = {}) {
1516
+ assertResolverNotHaltedForDataRead(this);
912
1517
  if (!args.address) return Promise.resolve({ transactions: [] });
913
1518
  return this._doPaginatedSearch("listTransactions", withTxProjection({
914
1519
  ...args,
@@ -916,6 +1521,7 @@ var OCAPResolver = class {
916
1521
  }, ctx), "transactions", "tx.itxJson.data", ctx);
917
1522
  }
918
1523
  async listFactories(args = {}, ctx) {
1524
+ assertResolverNotHaltedForDataRead(this);
919
1525
  const result = await this._doPaginatedSearch("listFactories", args, "factories", "data", ctx);
920
1526
  result.factories = result.factories.map((x) => {
921
1527
  const output = x.output;
@@ -925,24 +1531,31 @@ var OCAPResolver = class {
925
1531
  return result;
926
1532
  }
927
1533
  listTopAccounts(args = {}) {
1534
+ assertResolverNotHaltedForDataRead(this);
928
1535
  return this._doPaginatedSearch("listTopAccounts", args, "accounts");
929
1536
  }
930
1537
  listTokens(args = {}, ctx) {
1538
+ assertResolverNotHaltedForDataRead(this);
931
1539
  return this._doPaginatedSearch("listTokens", args, "tokens", ["data", "metadata"], ctx);
932
1540
  }
933
1541
  listTokenFactories(args = {}, ctx) {
1542
+ assertResolverNotHaltedForDataRead(this);
934
1543
  return this._doPaginatedSearch("listTokenFactories", args, "tokenFactories", "data", ctx);
935
1544
  }
936
1545
  listStakes(args = {}, ctx) {
1546
+ assertResolverNotHaltedForDataRead(this);
937
1547
  return this._doPaginatedSearch("listStakes", args, "stakes", "data", ctx);
938
1548
  }
939
1549
  listRollups(args = {}, ctx) {
1550
+ assertResolverNotHaltedForDataRead(this);
940
1551
  return this._doPaginatedSearch("listRollups", args, "rollups", "data", ctx);
941
1552
  }
942
1553
  listRollupBlocks(args = {}, ctx) {
1554
+ assertResolverNotHaltedForDataRead(this);
943
1555
  return this._doPaginatedSearch("listRollupBlocks", args, "blocks", "data", ctx);
944
1556
  }
945
1557
  async listRollupValidators(args = {}, ctx) {
1558
+ assertResolverNotHaltedForDataRead(this);
946
1559
  if (!args.rollupAddress) return { validators: [] };
947
1560
  const rollup = await this.statedb.rollup.get(args.rollupAddress);
948
1561
  if (!rollup) return { validators: [] };
@@ -959,9 +1572,11 @@ var OCAPResolver = class {
959
1572
  return result;
960
1573
  }
961
1574
  listDelegations(args = {}, ctx) {
1575
+ assertResolverNotHaltedForDataRead(this);
962
1576
  return this._doPaginatedSearch("listDelegations", args, "delegations", "data", ctx);
963
1577
  }
964
1578
  verifyAccountRisk(args = {}, ctx) {
1579
+ assertResolverNotHaltedForDataRead(this);
965
1580
  if (process.env.TOKEN_FLOW_ENABLED === "true") return verifyAccountRisk({
966
1581
  ...args,
967
1582
  tokenAddress: toAddress(args.tokenAddress || this.config.token.address),
@@ -973,10 +1588,12 @@ var OCAPResolver = class {
973
1588
  return null;
974
1589
  }
975
1590
  listTokenFlows(args = {}, ctx) {
1591
+ assertResolverNotHaltedForDataRead(this);
976
1592
  if (process.env.TOKEN_FLOW_ENABLED === "true") return listTokenFlows(args, this, ctx);
977
1593
  return [];
978
1594
  }
979
1595
  async search(args) {
1596
+ assertResolverNotHaltedForDataRead(this);
980
1597
  if (!args.keyword) return { results: [] };
981
1598
  const doSearch = async (type, keyword) => {
982
1599
  const result = await this.indexdb[type].get(keyword);
@@ -1002,6 +1619,7 @@ var OCAPResolver = class {
1002
1619
  return { results: [] };
1003
1620
  }
1004
1621
  estimateGas(args = {}) {
1622
+ assertResolverNotHaltedForDataRead(this);
1005
1623
  const { typeUrl = "" } = args;
1006
1624
  if (!typeUrl || !maxGasOps[typeUrl]) throw new CustomError("INVALID_REQUEST", "Unknown tx typeUrl");
1007
1625
  const { txGas, maxTxSize } = this.config.transaction;
@@ -1011,15 +1629,25 @@ var OCAPResolver = class {
1011
1629
  totalGas = totalGas.add(new BN(txGas.price).mul(new BN(txGas.updateState)).mul(new BN(estimate.update)));
1012
1630
  return { estimate: { max: totalGas.toString(10) } };
1013
1631
  }
1014
- async shutdown() {
1015
- if (this.queue) {
1016
- this.queue.autostart = false;
1017
- if (this.queue.length > 0) await new Promise((resolve) => {
1018
- this.queue.on("end", resolve);
1632
+ shutdown() {
1633
+ this.isShuttingDown = true;
1634
+ if (!this.shutdownPromise) this.shutdownPromise = (async () => {
1635
+ if (this.inFlightPreFlights > 0) await new Promise((resolve) => {
1636
+ if (this.inFlightPreFlights === 0) resolve();
1637
+ else this.preFlightDrainWaiters.push(resolve);
1019
1638
  });
1020
- }
1639
+ if (this.queue) {
1640
+ this.queue.autostart = false;
1641
+ if (this.queue.length > 0) await new Promise((resolve) => {
1642
+ this.queue.once("end", () => resolve());
1643
+ });
1644
+ }
1645
+ await this.flushIndexWrites();
1646
+ })();
1647
+ return this.shutdownPromise;
1021
1648
  }
1022
1649
  listBlocks() {
1650
+ assertResolverNotHaltedForDataRead(this);
1023
1651
  return { blocks: [] };
1024
1652
  }
1025
1653
  validateTokenConfig() {
@@ -1039,17 +1667,91 @@ var OCAPResolver = class {
1039
1667
  async getToken(id) {
1040
1668
  return this.statedb.token.get(id);
1041
1669
  }
1042
- async initializeStateDB() {
1670
+ async initializeStateDB(options = {}) {
1671
+ if (this.skipInitializeStateDB || this.nodeRuntime && this.nodeRuntime.role !== "validator") return;
1043
1672
  const { accounts, token } = this.config;
1044
1673
  const { account: accountDB, chain: chainDB, token: tokenDB } = this.statedb;
1045
1674
  const { account: accountState, chain: chainState, token: tokenState } = states;
1675
+ const rawTime = options.txTime ?? this.config.genesisTime ?? (process.env.CHAIN_GENESIS_TIME || "").trim();
1676
+ const parsedMs = rawTime === void 0 || rawTime === null || rawTime === "" ? NaN : new Date(rawTime).getTime();
1677
+ const isHotStuffBootstrap = this.explicitConsensusMode === "hotstuff" || !this.explicitConsensusMode && getNormalizedEnvLower("CONSENSUS_MODE") === "hotstuff" || Boolean(this.nodeRuntime?.getConsensusCommitter?.());
1046
1678
  const context = {
1047
- txTime: (/* @__PURE__ */ new Date()).toISOString(),
1679
+ txTime: Number.isFinite(parsedMs) ? new Date(parsedMs).toISOString() : typeof rawTime === "string" && rawTime.trim() ? rawTime.trim() : isHotStuffBootstrap ? "1970-01-01T00:00:00.000Z" : new Date(typeof this.now === "function" ? this.now() : Date.now()).toISOString(),
1048
1680
  txHash: ""
1049
1681
  };
1050
- await this.runAsLambda(async (txn) => {
1682
+ const config = omit(this.config, ["reservedSymbols"]);
1683
+ const role = String(this.config.role || process.env.CHAIN_ROLE || "").trim().toLowerCase();
1684
+ const normalizedMode = getNormalizedEnvLower("CHAIN_MODE");
1685
+ const isReadOnlyMode = options.readonly === true || normalizedMode === "readonly" || role === "follower" || role === "standby";
1686
+ const commitGetter = this.statedb.getCommitHash;
1687
+ const hasCommitTracking = typeof commitGetter === "function";
1688
+ if (isReadOnlyMode) {
1689
+ const existingChain$1 = await this.statedb.chain.get(CHAIN_ADDR);
1690
+ if (!existingChain$1) {
1691
+ if (hasCommitTracking) throw new CustomError("FORBIDDEN", "Read-only/follower StateDB is uninitialized (missing chain state)");
1692
+ return;
1693
+ }
1694
+ if (hasCommitTracking) {
1695
+ const roCommit = await commitGetter.call(this.statedb);
1696
+ const roSeq = Number(roCommit?.seq || 0);
1697
+ if (this.tokenItx) {
1698
+ if (!await this.statedb.token.get(this.tokenItx.address) || roCommit?.msg === "initialize chain") throw new CustomError("FORBIDDEN", "Read-only/follower StateDB has incomplete genesis (missing official token state)");
1699
+ if (accounts.length > 0 && roSeq <= 2 && roCommit?.msg === "initialize token" && !await accountDB.get(accounts[0].address)) throw new CustomError("FORBIDDEN", "Read-only/follower StateDB has incomplete genesis (missing initial accounts)");
1700
+ }
1701
+ }
1702
+ chainState.update(existingChain$1, {
1703
+ ...config,
1704
+ context
1705
+ });
1706
+ return;
1707
+ }
1708
+ let stateCommitSeq = 0;
1709
+ let stateCommitMsg = "";
1710
+ let stateCommitCurrentHash = "GENESIS";
1711
+ if (hasCommitTracking) {
1712
+ const commitInfo = await commitGetter.call(this.statedb);
1713
+ stateCommitSeq = Number(commitInfo?.seq || 0);
1714
+ stateCommitMsg = String(commitInfo?.msg || "");
1715
+ stateCommitCurrentHash = String(commitInfo?.currentHash || "GENESIS");
1716
+ }
1717
+ const isLedgerAnchoredRestart = hasCommitTracking && (stateCommitSeq > 0 || Boolean(stateCommitCurrentHash) && stateCommitCurrentHash !== "GENESIS");
1718
+ if (isLedgerAnchoredRestart && this.tokenItx) {
1719
+ if (stateCommitMsg === "initialize chain") throw new CustomError("INTERNAL", "Incomplete genesis StateDB: crashed after chain initialization before official token state was committed");
1720
+ if (accounts.length > 0 && stateCommitSeq <= 2 && stateCommitMsg === "initialize token" && !await accountDB.get(accounts[0].address)) throw new CustomError("INTERNAL", "Incomplete genesis StateDB: crashed after official token initialization before initial accounts were committed");
1721
+ }
1722
+ const existingChain = await this.statedb.chain.get(CHAIN_ADDR);
1723
+ const normalizeComparable = (val) => {
1724
+ if (val === void 0 || val === null) return null;
1725
+ if (Array.isArray(val)) return val.map(normalizeComparable);
1726
+ if (typeof val === "object") {
1727
+ const out = {};
1728
+ for (const [k, v$1] of Object.entries(val)) if (v$1 !== void 0) out[k] = normalizeComparable(v$1);
1729
+ return out;
1730
+ }
1731
+ return val;
1732
+ };
1733
+ const persistedChainKeys = [
1734
+ "chainId",
1735
+ "version",
1736
+ "transaction",
1737
+ "moderator",
1738
+ "accounts",
1739
+ "token",
1740
+ "vaults"
1741
+ ];
1742
+ const expectedConfig = normalizeComparable(pick(this.config, persistedChainKeys));
1743
+ const needsChainWrite = !existingChain || isEqual(normalizeComparable(pick(existingChain, persistedChainKeys)), expectedConfig) === false;
1744
+ if (isLedgerAnchoredRestart) {
1745
+ if (!existingChain) throw new CustomError("INTERNAL", "Incomplete genesis StateDB: missing chain state while _state_commit.seq > 0");
1746
+ if (needsChainWrite) {
1747
+ chainState.update(existingChain, {
1748
+ ...config,
1749
+ context
1750
+ });
1751
+ this.logger.info("skipping out-of-band chain state update on ledger-anchored restart to preserve _state_commit parity", { stateCommitSeq });
1752
+ }
1753
+ } else if (needsChainWrite) await this.runAsLambda(async (txn) => {
1051
1754
  const info = await this.statedb.chain.get(CHAIN_ADDR, { txn });
1052
- const config = omit(this.config, ["reservedSymbols"]);
1053
1755
  if (!info) {
1054
1756
  const state = chainState.create({
1055
1757
  ...config,
@@ -1058,7 +1760,7 @@ var OCAPResolver = class {
1058
1760
  });
1059
1761
  const result = await chainDB.create(CHAIN_ADDR, state, { txn });
1060
1762
  this.logger.debug("create chain state", { result });
1061
- } else if (isEqual(pick(info, Object.keys(config)), config) === false) {
1763
+ } else if (isEqual(normalizeComparable(pick(info, persistedChainKeys)), normalizeComparable(pick(config, persistedChainKeys))) === false) {
1062
1764
  const state = chainState.update(info, {
1063
1765
  ...config,
1064
1766
  context
@@ -1068,50 +1770,73 @@ var OCAPResolver = class {
1068
1770
  }
1069
1771
  }, { commitMessage: "initialize chain" });
1070
1772
  if (this.tokenItx) {
1071
- await this.runAsLambda(async (txn) => {
1773
+ const changedKeys = [
1774
+ "icon",
1775
+ "website",
1776
+ "metadata"
1777
+ ];
1778
+ const normalizeTokenMutable = (obj) => ({
1779
+ icon: obj?.icon ? String(obj.icon) : "",
1780
+ website: obj?.website ? String(obj.website) : "",
1781
+ metadata: obj?.metadata === void 0 || obj?.metadata === null ? null : normalizeComparable(obj.metadata)
1782
+ });
1783
+ const expectedTokenShape = tokenState.create(this.tokenItx, context);
1784
+ const preExistToken = await this.statedb.token.get(this.tokenItx.address);
1785
+ const needsTokenWrite = !preExistToken || !isEqual(normalizeTokenMutable(preExistToken), normalizeTokenMutable(expectedTokenShape));
1786
+ if (isLedgerAnchoredRestart) {
1787
+ if (!preExistToken) throw new CustomError("INTERNAL", `Incomplete genesis StateDB: missing official token state (${this.tokenItx.address}) while _state_commit.seq > 0`);
1788
+ if (needsTokenWrite) {
1789
+ tokenState.update(preExistToken, pick(this.tokenItx, changedKeys));
1790
+ this.logger.info("skipping out-of-band token metadata update on ledger-anchored restart to preserve _state_commit parity", {
1791
+ address: this.tokenItx.address,
1792
+ stateCommitSeq
1793
+ });
1794
+ }
1795
+ } else if (needsTokenWrite) await this.runAsLambda(async (txn) => {
1072
1796
  const existToken = await this.statedb.token.get(this.tokenItx.address, { txn });
1073
1797
  if (!existToken) {
1074
1798
  const state = tokenState.create(this.tokenItx, context);
1075
1799
  const result = await tokenDB.create(this.tokenItx.address, state, { txn });
1076
1800
  tokenDB.emit("create", result, { txn });
1077
1801
  this.logger.debug("create token state", { address: result?.address });
1078
- } else {
1079
- const changedKeys = [
1080
- "icon",
1081
- "website",
1082
- "metadata"
1083
- ];
1084
- const pickStateToken = pick(existToken, changedKeys);
1085
- const pickConfigToken = pick(this.tokenItx, changedKeys);
1086
- if (!isEqual(pickStateToken, pickConfigToken)) {
1087
- const state = tokenState.update(existToken, pickConfigToken);
1088
- const result = await tokenDB.update(this.tokenItx.address, state, { txn });
1089
- tokenDB.emit("update", result, { txn });
1090
- this.logger.info("update token state", { result });
1091
- }
1802
+ } else if (!isEqual(normalizeTokenMutable(existToken), normalizeTokenMutable(expectedTokenShape))) {
1803
+ const state = tokenState.update(existToken, pick(this.tokenItx, changedKeys));
1804
+ const result = await tokenDB.update(this.tokenItx.address, state, { txn });
1805
+ tokenDB.emit("update", result, { txn });
1806
+ this.logger.info("update token state", { result });
1092
1807
  }
1093
1808
  }, { commitMessage: "initialize token" });
1094
- await this.runAsLambda(async (txn) => {
1095
- for (let i = 0; i < accounts.length; i++) {
1096
- const { address, balance, moniker, pk } = accounts[i];
1097
- try {
1098
- if (!await accountDB.get(address, { txn })) {
1099
- const balanceStr = fromTokenToUnit(balance ?? 0, token.decimal ?? 18).toString(10);
1100
- const state = accountState.create({
1101
- address,
1102
- tokens: { [this.tokenItx.address]: balanceStr },
1103
- moniker: moniker || "token-holder",
1104
- pk
1105
- }, context);
1106
- const result = await accountDB.create(address, state, { txn });
1107
- accountDB.emit("create", result, { txn });
1108
- this.logger.info("create account done", { address });
1809
+ if (!isLedgerAnchoredRestart) {
1810
+ let needsAccountsWrite = false;
1811
+ if (accounts.length > 0) {
1812
+ for (let i = 0; i < accounts.length; i++) if (!await accountDB.get(accounts[i].address)) {
1813
+ needsAccountsWrite = true;
1814
+ break;
1815
+ }
1816
+ } else if (!existingChain) needsAccountsWrite = true;
1817
+ if (needsAccountsWrite) await this.runAsLambda(async (txn) => {
1818
+ for (let i = 0; i < accounts.length; i++) {
1819
+ const { address, balance, moniker, pk } = accounts[i];
1820
+ try {
1821
+ if (!await accountDB.get(address, { txn })) {
1822
+ const balanceStr = fromTokenToUnit(balance ?? 0, token.decimal ?? 18).toString(10);
1823
+ const state = accountState.create({
1824
+ address,
1825
+ tokens: { [this.tokenItx.address]: balanceStr },
1826
+ moniker: moniker || "token-holder",
1827
+ pk
1828
+ }, context);
1829
+ const result = await accountDB.create(address, state, { txn });
1830
+ accountDB.emit("create", result, { txn });
1831
+ this.logger.info("create account done", { address });
1832
+ }
1833
+ } catch (err) {
1834
+ this.logger.error("Failed to initialize initial token holders", err);
1835
+ if (hasCommitTracking) throw err;
1109
1836
  }
1110
- } catch (err) {
1111
- this.logger.error("Failed to initialize initial token holders", err);
1112
1837
  }
1113
- }
1114
- }, { commitMessage: "initialize accounts" });
1838
+ }, { commitMessage: "initialize accounts" });
1839
+ }
1115
1840
  }
1116
1841
  }
1117
1842
  /**
@@ -1152,59 +1877,65 @@ var OCAPResolver = class {
1152
1877
  }
1153
1878
  connectIndexDB() {
1154
1879
  const getToken = this.getToken.bind(this);
1155
- this.statedb.tx.on("create", async (x, ctx) => {
1880
+ this.statedb.tx.on("create", (x, ctx) => {
1156
1881
  if (!ctx) return;
1157
- try {
1158
- const tx = await createIndexedTransaction(x, ctx, this.indexdb);
1159
- await this.indexdb.tx.insert(tx);
1160
- if (typeof onCreateTx === "function") await onCreateTx(tx, ctx, this);
1161
- } catch (error) {
1162
- this.logger.error("create tx index failed", {
1163
- account: x,
1164
- error
1165
- });
1166
- await this.recordIndexFailure({
1167
- table: "tx",
1168
- event: "create",
1169
- entityId: x?.hash,
1170
- payload: x,
1171
- error
1172
- });
1173
- }
1882
+ this.trackIndexWrite((async () => {
1883
+ try {
1884
+ const tx = await createIndexedTransaction(x, ctx, this.indexdb);
1885
+ await this.indexdb.tx.insert(tx);
1886
+ if (typeof onCreateTx === "function") await onCreateTx(tx, ctx, this);
1887
+ } catch (error) {
1888
+ this.logger.error("create tx index failed", {
1889
+ account: x,
1890
+ error
1891
+ });
1892
+ await this.recordIndexFailure({
1893
+ table: "tx",
1894
+ event: "create",
1895
+ entityId: x?.hash,
1896
+ payload: x,
1897
+ error
1898
+ });
1899
+ }
1900
+ })());
1174
1901
  });
1175
- this.statedb.account.on("create", async (x) => {
1176
- try {
1177
- await this.indexdb.account.insert(await createIndexedAccount(x, getToken));
1178
- } catch (error) {
1179
- this.logger.error("create account index failed", {
1180
- account: x,
1181
- error
1182
- });
1183
- await this.recordIndexFailure({
1184
- table: "account",
1185
- event: "create",
1186
- entityId: x?.address,
1187
- payload: x,
1188
- error
1189
- });
1190
- }
1902
+ this.statedb.account.on("create", (x) => {
1903
+ this.trackIndexWrite((async () => {
1904
+ try {
1905
+ await this.indexdb.account.insert(await createIndexedAccount(x, getToken));
1906
+ } catch (error) {
1907
+ this.logger.error("create account index failed", {
1908
+ account: x,
1909
+ error
1910
+ });
1911
+ await this.recordIndexFailure({
1912
+ table: "account",
1913
+ event: "create",
1914
+ entityId: x?.address,
1915
+ payload: x,
1916
+ error
1917
+ });
1918
+ }
1919
+ })());
1191
1920
  });
1192
- this.statedb.account.on("update", async (x) => {
1193
- try {
1194
- await this.indexdb.account.update(x.address, await createIndexedAccount(x, getToken));
1195
- } catch (error) {
1196
- this.logger.error("update account index failed", {
1197
- account: x,
1198
- error
1199
- });
1200
- await this.recordIndexFailure({
1201
- table: "account",
1202
- event: "update",
1203
- entityId: x?.address,
1204
- payload: x,
1205
- error
1206
- });
1207
- }
1921
+ this.statedb.account.on("update", (x) => {
1922
+ this.trackIndexWrite((async () => {
1923
+ try {
1924
+ await this.indexdb.account.update(x.address, await createIndexedAccount(x, getToken));
1925
+ } catch (error) {
1926
+ this.logger.error("update account index failed", {
1927
+ account: x,
1928
+ error
1929
+ });
1930
+ await this.recordIndexFailure({
1931
+ table: "account",
1932
+ event: "update",
1933
+ entityId: x?.address,
1934
+ payload: x,
1935
+ error
1936
+ });
1937
+ }
1938
+ })());
1208
1939
  });
1209
1940
  const mapping = {
1210
1941
  asset: [
@@ -1258,45 +1989,49 @@ var OCAPResolver = class {
1258
1989
  };
1259
1990
  Object.keys(mapping).forEach((table) => {
1260
1991
  const [fn, key, onCreate, onUpdate] = mapping[table];
1261
- this.statedb[table].on("create", async (x, _ctx) => {
1262
- try {
1263
- const ctx = this.enrichIndexContext(_ctx);
1264
- const doc = await fn(x, ctx, this.indexdb);
1265
- await this.indexdb[table].insert(doc);
1266
- if (typeof onCreate === "function") await onCreate(doc, ctx, this.indexdb, this);
1267
- } catch (error) {
1268
- this.logger.error(`create ${table} index failed`, {
1269
- [table]: x,
1270
- error
1271
- });
1272
- await this.recordIndexFailure({
1273
- table,
1274
- event: "create",
1275
- entityId: x?.[key],
1276
- payload: x,
1277
- error
1278
- });
1279
- }
1992
+ this.statedb[table].on("create", (x, _ctx) => {
1993
+ this.trackIndexWrite((async () => {
1994
+ try {
1995
+ const ctx = this.enrichIndexContext(_ctx);
1996
+ const doc = await fn(x, ctx, this.indexdb);
1997
+ await this.indexdb[table].insert(doc);
1998
+ if (typeof onCreate === "function") await onCreate(doc, ctx, this.indexdb, this);
1999
+ } catch (error) {
2000
+ this.logger.error(`create ${table} index failed`, {
2001
+ [table]: x,
2002
+ error
2003
+ });
2004
+ await this.recordIndexFailure({
2005
+ table,
2006
+ event: "create",
2007
+ entityId: x?.[key],
2008
+ payload: x,
2009
+ error
2010
+ });
2011
+ }
2012
+ })());
1280
2013
  });
1281
- this.statedb[table].on("update", async (x, _ctx) => {
1282
- try {
1283
- const ctx = this.enrichIndexContext(_ctx);
1284
- const doc = await fn(x, ctx, this.indexdb);
1285
- await this.indexdb[table].update(doc[key], doc);
1286
- if (typeof onUpdate === "function") onUpdate(doc, ctx, this.indexdb, this);
1287
- } catch (error) {
1288
- this.logger.error(`update ${table} index failed`, {
1289
- [table]: x,
1290
- error
1291
- });
1292
- await this.recordIndexFailure({
1293
- table,
1294
- event: "update",
1295
- entityId: x?.[key],
1296
- payload: x,
1297
- error
1298
- });
1299
- }
2014
+ this.statedb[table].on("update", (x, _ctx) => {
2015
+ this.trackIndexWrite((async () => {
2016
+ try {
2017
+ const ctx = this.enrichIndexContext(_ctx);
2018
+ const doc = await fn(x, ctx, this.indexdb);
2019
+ await this.indexdb[table].update(doc[key], doc);
2020
+ if (typeof onUpdate === "function") await onUpdate(doc, ctx, this.indexdb, this);
2021
+ } catch (error) {
2022
+ this.logger.error(`update ${table} index failed`, {
2023
+ [table]: x,
2024
+ error
2025
+ });
2026
+ await this.recordIndexFailure({
2027
+ table,
2028
+ event: "update",
2029
+ entityId: x?.[key],
2030
+ payload: x,
2031
+ error
2032
+ });
2033
+ }
2034
+ })());
1300
2035
  });
1301
2036
  });
1302
2037
  }
@@ -1341,7 +2076,8 @@ var OCAPResolver = class {
1341
2076
  async getReplayTxRollupContext(state) {
1342
2077
  const type = typeof state?.type === "string" ? state.type : "";
1343
2078
  const txType = type ? `fg:t:${type}` : "";
1344
- const address = state?.tx?.itxJson?.rollup;
2079
+ const itxJson = state?.tx?.itxJson;
2080
+ const address = itxJson?.rollup || (type === "create_rollup" ? itxJson?.address : void 0);
1345
2081
  if (typeof address !== "string" || !address) return txType ? { txType } : {};
1346
2082
  const row = await this.statedb.rollup.get(address);
1347
2083
  if (!row) return txType ? { txType } : {};
@@ -1385,9 +2121,9 @@ var OCAPResolver = class {
1385
2121
  };
1386
2122
  const doc$1 = state?.tx && state?.hash && typeof state?.Valid !== "undefined" ? state : await createIndexedTransaction(state, ctx$1, this.indexdb);
1387
2123
  const existing$1 = await this.indexdb.tx.get(doc$1.hash);
1388
- if (event === "update" && existing$1) await this.indexdb.tx.update(doc$1.hash, doc$1);
2124
+ if (event === "update" && existing$1) await this.indexdb.tx.update(doc$1.hash, formatTxBeforeInsert(doc$1));
1389
2125
  else if (!existing$1) await this.indexdb.tx.insert(doc$1);
1390
- else await this.indexdb.tx.update(doc$1.hash, doc$1);
2126
+ else await this.indexdb.tx.update(doc$1.hash, formatTxBeforeInsert(doc$1));
1391
2127
  if (event === "create" && !existing$1 && typeof onCreateTx === "function") await onCreateTx(doc$1, ctx$1, this);
1392
2128
  return;
1393
2129
  }
@@ -1829,6 +2565,7 @@ var OCAPResolver = class {
1829
2565
  return await this.tokenDistribution.updateByToken(tokenAddress, force);
1830
2566
  }
1831
2567
  async getTokenDistribution(args = {}) {
2568
+ assertResolverNotHaltedForDataRead(this);
1832
2569
  const { tokenAddress = this.config.token.address } = args;
1833
2570
  return await this.tokenDistribution.getDistribution(tokenAddress);
1834
2571
  }
@@ -1916,4 +2653,4 @@ var OCAPResolver = class {
1916
2653
  };
1917
2654
 
1918
2655
  //#endregion
1919
- export { GRAPHQL_INDEXED_TX_COLUMNS, OCAPResolver as default, formatData, formatDelegationOps };
2656
+ export { ConsensusAbortError, DEFAULT_FOLLOWER_MAX_SYNC_LAG, DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS, DEFAULT_FOLLOWER_POLL_INTERVAL_MS, FUTURE_LEDGER_ENTRY_TIMESTAMP, FollowerSyncService, GRAPHQL_INDEXED_TX_COLUMNS, HotStuffNodeRuntime, LedgerEntryReplayer, MAX_BLOCKED_ACCOUNTS, MAX_CONFIG_BODY_BYTES, MAX_MEMO_LENGTH, MAX_PEER_URLS, MAX_RESERVED_SYMBOLS, MAX_TRUSTED_ACCOUNTS, NodePreferencesError, NodePreferencesManager, UNIFIED_CONSOLE_APP_JS, applyBootRuntimePreferences, buildUnifiedConsoleHtml, collectLedgerHealthSummary, createAdminAuthGuard, createExplorerMiddleware, createFollowerPeerFetchGuard, createNodeDashboardRouter, createNodeMaintenanceController, createUnifiedConsoleMiddleware, OCAPResolver as default, formatData, formatDelegationOps, isDashboardEnabled, isExplorerEnabled, isPrivateOrReservedIpAddress, isTransientSqliteLockError, isValidAccountAddressCandidate, loadNodePreferences, normalizeBlockedAccountKey, timingSafeTokenEqual, validateFollowerPeerUrls };