@ocap/resolver 1.31.9 → 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 +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 +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 +945 -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 +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
package/lib/index.cjs CHANGED
@@ -1,32 +1,39 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
3
+ const require_node_preferences = require('./node-preferences.cjs');
4
+ const require_dashboard = require('./dashboard.cjs');
5
+ const require_explorer = require('./explorer.cjs');
6
+ const require_replayer = require('./replayer.cjs');
7
+ const require_follower = require('./follower.cjs');
3
8
  const require_package = require('./package.cjs');
4
9
  const require_hooks = require('./hooks.cjs');
10
+ const require_hotstuff_runtime = require('./hotstuff-runtime.cjs');
5
11
  const require_migration_chain = require('./migration-chain.cjs');
6
12
  const require_token_cache = require('./token-cache.cjs');
7
13
  const require_token_distribution = require('./token-distribution.cjs');
8
14
  const require_token_flow = require('./token-flow.cjs');
9
- let _arcblock_did_util = require("@arcblock/did-util");
15
+ let _arcblock_ledger_core = require("@arcblock/ledger-core");
16
+ let _ocap_mcrypto = require("@ocap/mcrypto");
17
+ let _ocap_tx_protocols = require("@ocap/tx-protocols");
18
+ let node_crypto = require("node:crypto");
19
+ let _arcblock_did = require("@arcblock/did");
10
20
  let _ocap_util = require("@ocap/util");
21
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
22
+ let _ocap_state = require("@ocap/state");
23
+ _ocap_state = require_rolldown_runtime.__toESM(_ocap_state);
24
+ let _arcblock_did_util = require("@arcblock/did-util");
11
25
  let debug = require("debug");
12
26
  debug = require_rolldown_runtime.__toESM(debug);
13
27
  let lodash_pick = require("lodash/pick");
14
28
  lodash_pick = require_rolldown_runtime.__toESM(lodash_pick);
15
- let node_crypto = require("node:crypto");
16
- let _arcblock_did = require("@arcblock/did");
17
29
  let _arcblock_validator = require("@arcblock/validator");
18
30
  let _ocap_config = require("@ocap/config");
19
31
  _ocap_config = require_rolldown_runtime.__toESM(_ocap_config);
20
32
  let _ocap_indexdb = require("@ocap/indexdb");
21
- let _ocap_mcrypto = require("@ocap/mcrypto");
22
33
  let _ocap_message = require("@ocap/message");
23
- let _ocap_state = require("@ocap/state");
24
- _ocap_state = require_rolldown_runtime.__toESM(_ocap_state);
25
- let _ocap_tx_protocols = require("@ocap/tx-protocols");
26
34
  let _ocap_tx_protocols_lib_util = require("@ocap/tx-protocols/lib/util");
27
35
  let _ocap_util_lib_constant = require("@ocap/util/lib/constant");
28
36
  let _ocap_util_lib_deposit_v2_bridge_fields = require("@ocap/util/lib/deposit-v2-bridge-fields");
29
- let _ocap_util_lib_error = require("@ocap/util/lib/error");
30
37
  let _ocap_util_lib_md5 = require("@ocap/util/lib/md5");
31
38
  let lodash_cloneDeep = require("lodash/cloneDeep");
32
39
  lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
@@ -53,6 +60,9 @@ let _ocap_state_lib_states_tx = require("@ocap/state/lib/states/tx");
53
60
  const debug$1 = (0, debug.default)(require_package.name);
54
61
  const noop = (x) => x;
55
62
  const CHAIN_ADDR = (0, _ocap_util_lib_md5.md5)("OCAP_CHAIN_ADDR");
63
+ function getNormalizedEnvLower(key) {
64
+ return String(process.env[key] ?? "").trim().toLowerCase();
65
+ }
56
66
  const maxGasOps = {
57
67
  "fg:t:account_migrate": {
58
68
  create: 2,
@@ -282,6 +292,11 @@ const withTxProjection = (args, ctx) => ctx?.graphqlTxProjection === true ? {
282
292
  ...args,
283
293
  columns: GRAPHQL_INDEXED_TX_COLUMNS
284
294
  } : args;
295
+ const assertResolverNotHaltedForDataRead = (self) => {
296
+ const runtime = self?.nodeRuntime;
297
+ if (runtime?.isHalted?.() === true) throw new _ocap_util_lib_error.CustomError("NODE_HALTED", "Chain node is halted fail-closed");
298
+ if (runtime?.isReconciling?.() === true) throw new _ocap_util_lib_error.CustomError("FOLLOWER_RECONCILING", "Follower is reconciling local statedb with imported ledger segment");
299
+ };
285
300
  var OCAPResolver = class {
286
301
  /**
287
302
  * Creates an instance of OCAPResolver.
@@ -293,24 +308,44 @@ var OCAPResolver = class {
293
308
  * @param params.filter bloom filter to do anti-replay check
294
309
  * @param params.validateTokenConfig should we validate token supply and token-holder balance, should be disabled when starting an existing chain
295
310
  */
296
- constructor({ statedb, indexdb, ledger, config, filter, validateTokenConfig = true, logger }) {
311
+ constructor({ statedb, indexdb, ledger, config, filter, admissionBlockedCheck, admissionReservedSymbolCheck, validateTokenConfig = true, skipInitializeStateDB = false, deferInitialize = false, consensusMode, txQueueConfig, now, nodeRuntime, logger }) {
297
312
  this.inFlightPreFlights = 0;
313
+ this.initializationPromise = null;
314
+ this.shutdownPromise = null;
315
+ this.isShuttingDown = false;
316
+ this.preFlightDrainWaiters = [];
317
+ this.pendingIndexWrites = /* @__PURE__ */ new Set();
318
+ this.txAcceptedTotal = 0;
319
+ this.txPersistedFailedTotal = 0;
320
+ this.txPreFlightRejectedTotal = 0;
321
+ this.txForwardedTotal = 0;
322
+ this.txBucketsSec = new Int32Array(60);
323
+ this.txBucketCounts = new Int32Array(60);
298
324
  if (!statedb) throw new Error("OCAP Resolver requires a valid statedb implementation to work");
299
325
  if (!indexdb) throw new Error("OCAP Resolver requires a valid indexdb implementation to work");
300
326
  if (!ledger) throw new Error("OCAP Resolver requires a valid ledger implementation to work");
301
327
  this.logger = logger || console;
328
+ this.now = typeof now === "function" ? now : () => Date.now();
329
+ this.deferInitialize = Boolean(deferInitialize);
330
+ this.explicitConsensusMode = consensusMode;
302
331
  this.statedb = statedb;
303
332
  this.indexdb = indexdb;
304
333
  this.ledger = ledger;
305
334
  this.filter = filter;
335
+ this.admissionBlockedCheck = admissionBlockedCheck;
336
+ this.admissionReservedSymbolCheck = admissionReservedSymbolCheck;
337
+ this.skipInitializeStateDB = Boolean(skipInitializeStateDB);
338
+ this.nodeRuntime = nodeRuntime;
306
339
  this.config = Object.freeze(_ocap_config.validate(config));
307
340
  this.chainAddr = (0, _ocap_util_lib_md5.md5)(config.chainId);
308
341
  this.tokenItx = _ocap_config.genTokenItx(this.config);
309
342
  this.consensus = `${statedb.name} v${statedb.version}`;
343
+ const isHotStuffMode = consensusMode === "hotstuff" || !consensusMode && getNormalizedEnvLower("CONSENSUS_MODE") === "hotstuff" || Boolean(nodeRuntime?.getConsensusCommitter?.());
344
+ if (txQueueConfig?.maxRequest !== void 0) this.setMaxTxRequest(txQueueConfig.maxRequest);
310
345
  this.queue = new queue.default({
311
346
  autostart: true,
312
- concurrency: txRequestConfig.concurrent,
313
- timeout: txRequestConfig.timeout
347
+ concurrency: isHotStuffMode ? 1 : txQueueConfig?.concurrent ?? txRequestConfig.concurrent,
348
+ timeout: txQueueConfig?.timeoutMs ?? txRequestConfig.timeout
314
349
  });
315
350
  if (indexdb) {
316
351
  this.tokenCache = require_token_cache.getInstance(indexdb.token);
@@ -325,28 +360,387 @@ var OCAPResolver = class {
325
360
  runAsLambda: typeof statedb.runAsLambda === "function" ? statedb.runAsLambda.bind(statedb) : void 0
326
361
  });
327
362
  this.formatTx = this._formatTx.bind(this);
328
- if (validateTokenConfig) this.validateTokenConfig();
363
+ const normalizedRole = getNormalizedEnvLower("CHAIN_ROLE");
364
+ const normalizedMode = getNormalizedEnvLower("CHAIN_MODE");
365
+ const isReadonlyStartRole = Boolean(skipInitializeStateDB) || nodeRuntime && nodeRuntime.role !== "validator" || normalizedRole === "follower" || normalizedRole === "standby" || normalizedMode === "readonly";
366
+ if (validateTokenConfig && !isReadonlyStartRole) this.validateTokenConfig();
329
367
  this.connectIndexDB();
330
- this.initializationPromise = this.initializeStateDB().catch((err) => {
368
+ if (!this.deferInitialize) this.initializationPromise = this.initializeStateDB().catch((err) => {
331
369
  this.logger.error("Failed to initialize statedb:", err.message);
332
370
  process.exit(1);
333
371
  });
334
372
  }
373
+ initialize() {
374
+ if (!this.initializationPromise) this.initializationPromise = this.initializeStateDB();
375
+ return this.initializationPromise;
376
+ }
377
+ setNodeRuntime(runtime) {
378
+ this.nodeRuntime = runtime;
379
+ if (runtime?.getConsensusCommitter?.()) this.queue.concurrency = 1;
380
+ }
381
+ getNodeRuntime() {
382
+ return this.nodeRuntime;
383
+ }
384
+ setAdmissionBlockedCheck(fn) {
385
+ this.admissionBlockedCheck = fn;
386
+ }
387
+ setAdmissionReservedSymbolCheck(fn) {
388
+ this.admissionReservedSymbolCheck = fn;
389
+ }
390
+ getMaxTxRequest() {
391
+ if (this.maxTxRequestOverride !== void 0) return this.maxTxRequestOverride;
392
+ return Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
393
+ }
394
+ setMaxTxRequest(maxRequest) {
395
+ if (maxRequest === void 0) {
396
+ this.maxTxRequestOverride = void 0;
397
+ return;
398
+ }
399
+ if (!Number.isSafeInteger(maxRequest) || maxRequest < 1 || maxRequest > 1e4) throw new _ocap_util_lib_error.CustomError("INVALID_CONFIG", "txMaxRequest must be an integer between 1 and 10000");
400
+ this.maxTxRequestOverride = maxRequest;
401
+ }
402
+ recordCommittedTxSample(nowMs = Date.now()) {
403
+ const sec = Math.floor(nowMs / 1e3);
404
+ const slot = (sec % 60 + 60) % 60;
405
+ if (this.txBucketsSec[slot] !== sec) {
406
+ this.txBucketsSec[slot] = sec;
407
+ this.txBucketCounts[slot] = 1;
408
+ } else this.txBucketCounts[slot] += 1;
409
+ }
410
+ getPipelineTelemetry(nowMs = Date.now()) {
411
+ const nowSec = Math.floor(nowMs / 1e3);
412
+ let sum10 = 0;
413
+ let sum60 = 0;
414
+ for (let i = 0; i < 60; i++) {
415
+ const bucketSec = this.txBucketsSec[i];
416
+ if (bucketSec <= 0) continue;
417
+ const age = nowSec - bucketSec;
418
+ if (age >= 0 && age < 60) {
419
+ sum60 += this.txBucketCounts[i];
420
+ if (age < 10) sum10 += this.txBucketCounts[i];
421
+ }
422
+ }
423
+ return {
424
+ queueDepth: this.queue.length,
425
+ inFlightPreFlights: this.inFlightPreFlights,
426
+ maxTxRequest: this.getMaxTxRequest(),
427
+ concurrency: this.queue.concurrency,
428
+ acceptedTotal: this.txAcceptedTotal,
429
+ persistedFailedTotal: this.txPersistedFailedTotal,
430
+ preFlightRejectedTotal: this.txPreFlightRejectedTotal,
431
+ forwardedTotal: this.txForwardedTotal,
432
+ tps10s: Number((sum10 / 10).toFixed(2)),
433
+ tps60s: Number((sum60 / 60).toFixed(2))
434
+ };
435
+ }
436
+ async assertNotBlockedAtAdmission(context) {
437
+ const hasBlockedCheck = typeof this.admissionBlockedCheck === "function";
438
+ const hasReservedCheck = typeof this.admissionReservedSymbolCheck === "function";
439
+ if (!hasBlockedCheck && !hasReservedCheck) return;
440
+ const txObj = context.tx && typeof context.tx === "object" ? context.tx : {};
441
+ const itxObj = context.itxJson && typeof context.itxJson === "object" ? context.itxJson : context.itx && typeof context.itx === "object" ? context.itx : {};
442
+ const txType = String(context.txType || txObj.itx?.type || "");
443
+ if (hasReservedCheck) {
444
+ if (txType === "fg:t:create_token_factory" || txType === "CreateTokenFactoryTx" || txType === "fg:t:create_token" || txType === "CreateTokenTx") {
445
+ const tokenNested = itxObj.token && typeof itxObj.token === "object" ? itxObj.token : null;
446
+ const normalizedSym = (typeof tokenNested?.symbol === "string" ? tokenNested.symbol : typeof itxObj.symbol === "string" ? itxObj.symbol : "").trim().toUpperCase();
447
+ if (normalizedSym && await Promise.resolve(this.admissionReservedSymbolCheck(normalizedSym))) {
448
+ const symErr = new _ocap_util_lib_error.CustomError("INVALID_SYMBOL", `Token symbol "${normalizedSym}" is reserved by node admission policy`);
449
+ symErr._strikeRecorded = true;
450
+ throw symErr;
451
+ }
452
+ }
453
+ }
454
+ if (!hasBlockedCheck) return;
455
+ const sigs = Array.isArray(txObj.signaturesList) ? txObj.signaturesList : Array.isArray(txObj.signatures) ? txObj.signatures : [];
456
+ const inputs = Array.isArray(itxObj.inputs) ? itxObj.inputs : Array.isArray(itxObj.inputsList) ? itxObj.inputsList : [];
457
+ const outputs = Array.isArray(itxObj.outputs) ? itxObj.outputs : Array.isArray(itxObj.outputsList) ? itxObj.outputsList : [];
458
+ const trustedIssuers = Array.isArray(itxObj.trustedIssuers) ? itxObj.trustedIssuers : Array.isArray(itxObj.trustedIssuersList) ? itxObj.trustedIssuersList : [];
459
+ const issuerField = itxObj.issuer;
460
+ const issuerCandidates = typeof issuerField === "string" ? [issuerField] : issuerField && typeof issuerField === "object" ? [issuerField.id, issuerField.address] : [];
461
+ const candidateActors = /* @__PURE__ */ new Set();
462
+ const addCandidate = (raw) => {
463
+ if (typeof raw === "string") {
464
+ const trimmed = raw.trim();
465
+ if (trimmed) candidateActors.add(trimmed);
466
+ }
467
+ };
468
+ const isRevokeDelegate = txType === "fg:t:revoke_delegate" || txType === "RevokeDelegateTx";
469
+ for (const candidate of [
470
+ txObj.from,
471
+ txObj.delegator,
472
+ ...isRevokeDelegate ? [] : [itxObj.to],
473
+ itxObj.receiver,
474
+ itxObj.owner,
475
+ itxObj.delegatee,
476
+ ...txType === "fg:t:account_migrate" || txType === "AccountMigrateTx" ? [itxObj.address] : [],
477
+ ...issuerCandidates,
478
+ ...trustedIssuers,
479
+ ...sigs.flatMap((s) => [s?.signer, s?.delegator]),
480
+ ...inputs.flatMap((inp) => [inp?.owner, inp?.address]),
481
+ ...outputs.flatMap((out) => [out?.owner, out?.address])
482
+ ]) addCandidate(candidate);
483
+ if (this.statedb) {
484
+ if (txType === "fg:t:claim_stake" || txType === "ClaimStakeTx") {
485
+ const stakeAddr = typeof itxObj.address === "string" ? itxObj.address.trim() : "";
486
+ if (stakeAddr && typeof this.statedb.stake?.get === "function") addCandidate((await this.statedb.stake.get(stakeAddr).catch(() => null))?.sender);
487
+ const evidenceHash = itxObj.evidence && typeof itxObj.evidence === "object" ? itxObj.evidence.hash : void 0;
488
+ if (typeof evidenceHash === "string" && evidenceHash.trim() && typeof this.statedb.tx?.get === "function") {
489
+ const evTxState = await this.statedb.tx.get(evidenceHash.trim()).catch(() => null);
490
+ const evItx = evTxState?.tx?.itxJson && typeof evTxState.tx.itxJson === "object" ? evTxState.tx.itxJson : (evTxState?.tx)?.itx && typeof (evTxState?.tx).itx === "object" ? (evTxState?.tx).itx : {};
491
+ const evOutputs = Array.isArray(evItx.outputs) ? evItx.outputs : Array.isArray(evItx.outputsList) ? evItx.outputsList : [];
492
+ for (const out of evOutputs) {
493
+ addCandidate(out?.owner);
494
+ addCandidate(out?.address);
495
+ }
496
+ }
497
+ } else if (txType === "fg:t:revoke_stake" || txType === "RevokeStakeTx") {
498
+ const stakeAddr = typeof itxObj.address === "string" ? itxObj.address.trim() : "";
499
+ if (stakeAddr && typeof this.statedb.stake?.get === "function") addCandidate((await this.statedb.stake.get(stakeAddr).catch(() => null))?.sender);
500
+ }
501
+ const isAcquireAsset = txType === "fg:t:acquire_asset_v2" || txType === "AcquireAssetV2Tx" || txType === "fg:t:acquire_asset_v3" || txType === "AcquireAssetV3Tx";
502
+ if (isAcquireAsset || txType === "fg:t:mint_asset" || txType === "MintAssetTx") {
503
+ const factoryAddr = typeof itxObj.factory === "string" ? itxObj.factory.trim() : "";
504
+ if (factoryAddr && typeof this.statedb.factory?.get === "function") {
505
+ const factoryState = await this.statedb.factory.get(factoryAddr).catch(() => null);
506
+ addCandidate(factoryState?.owner);
507
+ if (Array.isArray(factoryState?.trustedIssuers)) for (const ti of factoryState.trustedIssuers) addCandidate(ti);
508
+ if (isAcquireAsset && factoryState?.settlement === "instant" && Array.isArray(factoryState?.hooks)) {
509
+ 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);
510
+ }
511
+ }
512
+ }
513
+ if (txType === "fg:t:update_asset" || txType === "UpdateAssetTx" || txType === "fg:t:consume_asset" || txType === "ConsumeAssetTx") {
514
+ const assetAddr = typeof itxObj.address === "string" ? itxObj.address.trim() : "";
515
+ if (assetAddr && typeof this.statedb.asset?.get === "function") {
516
+ const assetState = await this.statedb.asset.get(assetAddr).catch(() => null);
517
+ addCandidate(assetState?.issuer);
518
+ if (txType === "fg:t:consume_asset" || txType === "ConsumeAssetTx") addCandidate(assetState?.owner);
519
+ }
520
+ }
521
+ }
522
+ const findBlockedInLineage = async (seedActor) => {
523
+ const visited = /* @__PURE__ */ new Set();
524
+ const queue$1 = [seedActor];
525
+ const MAX_LINEAGE_EXPAND = 32;
526
+ while (queue$1.length > 0 && visited.size < MAX_LINEAGE_EXPAND) {
527
+ const rawCurr = queue$1.shift();
528
+ if (!rawCurr) continue;
529
+ const bareCurr = (0, _ocap_util.toAddress)(rawCurr).trim();
530
+ const keyCurr = bareCurr || rawCurr;
531
+ if (visited.has(keyCurr)) continue;
532
+ visited.add(keyCurr);
533
+ if (await Promise.resolve(this.admissionBlockedCheck(rawCurr))) return rawCurr;
534
+ if (bareCurr && bareCurr !== rawCurr && await Promise.resolve(this.admissionBlockedCheck(bareCurr))) return bareCurr;
535
+ if ((0, _arcblock_did.isValid)(keyCurr) && typeof this.statedb?.account?.get === "function") {
536
+ const accState = await this.statedb.account.get(keyCurr, { traceMigration: false }).catch(() => null);
537
+ if (accState) {
538
+ if (typeof accState.address === "string" && accState.address.trim()) {
539
+ const nextKey = (0, _ocap_util.toAddress)(accState.address.trim()).trim();
540
+ if (nextKey && !visited.has(nextKey)) queue$1.push(nextKey);
541
+ }
542
+ if (Array.isArray(accState.migratedFrom)) {
543
+ for (const prev of accState.migratedFrom) if (typeof prev === "string" && prev.trim()) {
544
+ const prevKey = (0, _ocap_util.toAddress)(prev.trim()).trim();
545
+ if (prevKey && !visited.has(prevKey)) queue$1.push(prevKey);
546
+ }
547
+ }
548
+ if (Array.isArray(accState.migratedTo)) {
549
+ for (const nextAddr of accState.migratedTo) if (typeof nextAddr === "string" && nextAddr.trim()) {
550
+ const toKey = (0, _ocap_util.toAddress)(nextAddr.trim()).trim();
551
+ if (toKey && !visited.has(toKey)) queue$1.push(toKey);
552
+ }
553
+ }
554
+ }
555
+ }
556
+ }
557
+ return null;
558
+ };
559
+ for (const actor of candidateActors) {
560
+ const blockedMatch = await findBlockedInLineage(actor);
561
+ if (blockedMatch) {
562
+ const blockErr = new _ocap_util_lib_error.CustomError("FORBIDDEN", `Account ${blockedMatch} is blocked by node admission policy`);
563
+ blockErr._strikeRecorded = true;
564
+ throw blockErr;
565
+ }
566
+ }
567
+ const extraObj = context.extra && typeof context.extra === "object" ? context.extra : {};
568
+ const rawTxExtra = extraObj.txExtra && typeof extraObj.txExtra === "object" ? extraObj.txExtra : void 0;
569
+ for (const candidateHeaders of [extraObj.gasStakeHeaders, rawTxExtra?.gasStakeHeaders]) {
570
+ const gasHeaders = candidateHeaders;
571
+ if (typeof gasHeaders?.token === "string" && gasHeaders.token.includes(".")) try {
572
+ const parts = gasHeaders.token.split(".");
573
+ if (parts.length === 3 && parts[1].length <= 16384) {
574
+ const payloadJson = Buffer.from(parts[1], "base64url").toString("utf8");
575
+ const decoded = JSON.parse(payloadJson);
576
+ if (typeof decoded?.iss === "string" && decoded.iss.trim()) {
577
+ const blockedSponsor = await findBlockedInLineage(decoded.iss.trim());
578
+ if (blockedSponsor) {
579
+ const sponsorErr = new _ocap_util_lib_error.CustomError("FORBIDDEN", `Gas sponsor ${blockedSponsor} is blocked by node admission policy`);
580
+ sponsorErr._unauthenticatedExtraFailure = true;
581
+ sponsorErr._strikeRecorded = true;
582
+ throw sponsorErr;
583
+ }
584
+ }
585
+ }
586
+ } catch (err) {
587
+ if (err?.code === "FORBIDDEN") throw err;
588
+ }
589
+ }
590
+ for (const candidatePass of [extraObj.gasPass, rawTxExtra?.gasPass]) {
591
+ const gasPass = candidatePass;
592
+ if (typeof gasPass?.stakeId === "string" && gasPass.stakeId.trim() && typeof this.statedb?.stake?.get === "function") {
593
+ const stakeState = await this.statedb.stake.get(gasPass.stakeId.trim()).catch(() => null);
594
+ for (const passActor of [stakeState?.sender, stakeState?.owner]) if (typeof passActor === "string" && passActor.trim()) {
595
+ const blockedPassActor = await findBlockedInLineage(passActor.trim());
596
+ if (blockedPassActor) {
597
+ const passErr = new _ocap_util_lib_error.CustomError("FORBIDDEN", `Gas pass sponsor ${blockedPassActor} is blocked by node admission policy`);
598
+ passErr._unauthenticatedExtraFailure = true;
599
+ passErr._strikeRecorded = true;
600
+ throw passErr;
601
+ }
602
+ }
603
+ }
604
+ }
605
+ }
606
+ async getFollowerStatus() {
607
+ if (this.nodeRuntime && typeof this.nodeRuntime.getFollowerStatus === "function") return this.nodeRuntime.getFollowerStatus();
608
+ return null;
609
+ }
610
+ async signForwardedSendTxReceipt(txHash) {
611
+ if (this.readonly || this.nodeRuntime && this.nodeRuntime.role !== "validator") return null;
612
+ const normalizedTxHash = txHash ? txHash.replace(/^0x/i, "").toUpperCase() : "";
613
+ const localEntry = txHash && typeof this.ledger?.get === "function" ? await this.ledger.get(txHash) || (normalizedTxHash && normalizedTxHash !== txHash ? await this.ledger.get(normalizedTxHash) : null) : null;
614
+ if (typeof this.nodeRuntime?.shouldHandleWriteLocally === "function" && !this.nodeRuntime.shouldHandleWriteLocally() && !localEntry) return null;
615
+ const proposer = this.ledger?.getProposer?.() || null;
616
+ if (!proposer || typeof this.ledger?.signConsensusDigest !== "function") return null;
617
+ const digest = (0, _arcblock_ledger_core.computeForwardReceiptDigest)({
618
+ chainId: this.config?.chainId || this.ledger.chainId,
619
+ txHash,
620
+ proposer
621
+ });
622
+ const signature = await this.ledger.signConsensusDigest(digest);
623
+ if (!signature) return null;
624
+ let commitProof;
625
+ if (localEntry && typeof this.ledger?.getCheckpointForSequence === "function" && typeof this.ledger?.getMerkleProof === "function") {
626
+ const [checkpoint, merkleProof] = await Promise.all([this.ledger.getCheckpointForSequence(localEntry.sequence).catch(() => null), this.ledger.getMerkleProof(localEntry.sequence).catch(() => null)]);
627
+ if (checkpoint?.qc && merkleProof) commitProof = Buffer.from(JSON.stringify({
628
+ sequence: localEntry.sequence,
629
+ entryHash: localEntry.entryHash,
630
+ stateCommitHash: localEntry.stateCommitHash ?? "",
631
+ proof: merkleProof,
632
+ checkpoint
633
+ }), "utf8").toString("base64");
634
+ }
635
+ return {
636
+ proposer,
637
+ signature,
638
+ ...commitProof ? { commitProof } : {}
639
+ };
640
+ }
641
+ trackIndexWrite(promise) {
642
+ const settled = promise.then(() => void 0, () => void 0);
643
+ this.pendingIndexWrites.add(settled);
644
+ settled.finally(() => {
645
+ this.pendingIndexWrites.delete(settled);
646
+ });
647
+ }
648
+ async flushIndexWrites() {
649
+ while (this.pendingIndexWrites.size > 0) await Promise.allSettled([...this.pendingIndexWrites]);
650
+ }
335
651
  sendTx({ tx: txBase64, extra }, ctx = {}) {
336
652
  debug$1("sendTx", {
337
653
  txBase64,
338
654
  request: ctx.request
339
655
  });
340
- if (process.env.CHAIN_MODE === "readonly") throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "This chain node is running in readonly mode");
341
- const maxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
342
- if (this.queue.length + this.inFlightPreFlights >= maxRequest) throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "Chain is busy");
656
+ if (this.isShuttingDown) throw new _ocap_util_lib_error.CustomError("SERVICE_UNAVAILABLE", "Resolver is shutting down");
657
+ const runtime = this.nodeRuntime;
658
+ if (runtime?.isHalted?.()) throw new _ocap_util_lib_error.CustomError("NODE_HALTED", "Chain node is halted fail-closed");
659
+ if (runtime ? runtime.role !== "validator" : (() => {
660
+ const normalizedRole = getNormalizedEnvLower("CHAIN_ROLE");
661
+ const normalizedMode = getNormalizedEnvLower("CHAIN_MODE");
662
+ return normalizedRole === "follower" || normalizedRole === "standby" || normalizedMode === "readonly";
663
+ })()) {
664
+ if ((runtime ? runtime.writePolicy : getNormalizedEnvLower("CHAIN_WRITE_POLICY") === "forward" ? "forward" : "reject") !== "forward" || typeof runtime?.forwardSendTx !== "function") throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "This chain node is running in readonly mode (FOLLOWER_READ_ONLY)");
665
+ (0, _ocap_tx_protocols.assertRawWireEnvelope)(txBase64, this.config);
666
+ if (ctx.forwardedHop !== void 0) throw new _ocap_util_lib_error.CustomError("FORWARD_LOOP_DETECTED", "Refusing to forward sendTx: request already carries X-Ocap-Forwarded-Hop header");
667
+ const pinnedTxTime$1 = ctx.txTime !== void 0 ? ctx.txTime : typeof this.now === "function" ? this.now() : Date.now();
668
+ return (async () => {
669
+ await this.initialize();
670
+ if (runtime?.isHalted?.()) throw new _ocap_util_lib_error.CustomError("NODE_HALTED", "Chain node is halted fail-closed");
671
+ const forwardContext = {
672
+ txBase64,
673
+ statedb: this.statedb,
674
+ indexdb: this.indexdb,
675
+ ledger: this.ledger,
676
+ config: this.config,
677
+ filter: this.filter,
678
+ logger: this.logger,
679
+ extra: {
680
+ ...ctx,
681
+ txTime: pinnedTxTime$1,
682
+ txExtra: extra
683
+ }
684
+ };
685
+ await (0, _ocap_tx_protocols.inspectTransactionPreFlight)(forwardContext);
686
+ await (0, _ocap_tx_protocols.assertStatelessTxRules)(forwardContext);
687
+ await this.assertNotBlockedAtAdmission(forwardContext);
688
+ const forwarded = await runtime.forwardSendTx({
689
+ tx: txBase64,
690
+ extra
691
+ }, ctx);
692
+ this.txForwardedTotal += 1;
693
+ if (forwarded?.hash && forwarded?.warning !== void 0) (0, _ocap_tx_protocols.setTxSecurityWarningForHash)(forwarded.hash, forwarded.warning, this.statedb);
694
+ return forwarded.hash;
695
+ })();
696
+ }
697
+ if (runtime?.role === "validator" && typeof runtime.shouldHandleWriteLocally === "function" && !runtime.shouldHandleWriteLocally()) {
698
+ if (ctx.forwardedHop !== void 0) throw new _ocap_util_lib_error.CustomError("CONSENSUS_NOT_LEADER", "Validator is not the active view leader for forwarded sendTx");
699
+ if (runtime.writePolicy !== "forward" || typeof runtime.forwardSendTx !== "function") throw new _ocap_util_lib_error.CustomError("CONSENSUS_NOT_LEADER", "Validator is not the active view leader");
700
+ (0, _ocap_tx_protocols.assertRawWireEnvelope)(txBase64, this.config);
701
+ const pinnedTxTime$1 = ctx.txTime !== void 0 ? ctx.txTime : typeof this.now === "function" ? this.now() : Date.now();
702
+ return (async () => {
703
+ await this.initialize();
704
+ if (runtime.isHalted()) throw new _ocap_util_lib_error.CustomError("NODE_HALTED", "Chain node is halted fail-closed");
705
+ const forwardContext = {
706
+ txBase64,
707
+ statedb: this.statedb,
708
+ indexdb: this.indexdb,
709
+ ledger: this.ledger,
710
+ config: this.config,
711
+ filter: this.filter,
712
+ logger: this.logger,
713
+ extra: {
714
+ ...ctx,
715
+ txTime: pinnedTxTime$1,
716
+ txExtra: extra
717
+ }
718
+ };
719
+ await (0, _ocap_tx_protocols.inspectTransactionPreFlight)(forwardContext);
720
+ await (0, _ocap_tx_protocols.assertStatelessTxRules)(forwardContext);
721
+ await this.assertNotBlockedAtAdmission(forwardContext);
722
+ const forwarded = await runtime.forwardSendTx({
723
+ tx: txBase64,
724
+ extra
725
+ }, ctx);
726
+ this.txForwardedTotal += 1;
727
+ if (forwarded?.hash && forwarded?.warning !== void 0) (0, _ocap_tx_protocols.setTxSecurityWarningForHash)(forwarded.hash, forwarded.warning, this.statedb);
728
+ return forwarded.hash;
729
+ })();
730
+ }
731
+ const maxRequest = this.getMaxTxRequest();
732
+ if (this.queue.length + this.inFlightPreFlights >= maxRequest) {
733
+ this.txPreFlightRejectedTotal += 1;
734
+ throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "Chain is busy");
735
+ }
343
736
  (0, _ocap_tx_protocols.assertRawWireEnvelope)(txBase64, this.config);
344
737
  const timer = new _ocap_tx_protocols.TxTimer();
345
738
  timer.setQueueState({
346
739
  waitingAtEnqueue: Math.max(0, this.queue.length - (this.queue.pending ?? 0)),
347
740
  runningAtEnqueue: this.queue.pending ?? 0,
348
- concurrencyConfig: txRequestConfig.concurrent
741
+ concurrencyConfig: this.queue.concurrency ?? txRequestConfig.concurrent
349
742
  });
743
+ const pinnedTxTime = ctx.txTime !== void 0 ? ctx.txTime : typeof this.now === "function" ? this.now() : Date.now();
350
744
  const context = {
351
745
  txBase64,
352
746
  statedb: this.statedb,
@@ -356,8 +750,10 @@ var OCAPResolver = class {
356
750
  filter: this.filter,
357
751
  logger: this.logger,
358
752
  timer,
753
+ ...runtime?.getConsensusCommitter ? { consensusCommitter: runtime.getConsensusCommitter() } : {},
359
754
  extra: {
360
755
  ...ctx,
756
+ txTime: pinnedTxTime,
361
757
  txExtra: extra
362
758
  }
363
759
  };
@@ -368,13 +764,18 @@ var OCAPResolver = class {
368
764
  if (!preFlightSlotReleased) {
369
765
  preFlightSlotReleased = true;
370
766
  this.inFlightPreFlights = Math.max(0, this.inFlightPreFlights - 1);
767
+ if (this.inFlightPreFlights === 0 && this.preFlightDrainWaiters.length > 0) {
768
+ const waiters = this.preFlightDrainWaiters.splice(0, this.preFlightDrainWaiters.length);
769
+ for (const notify of waiters) notify();
770
+ }
371
771
  }
372
772
  };
373
773
  const enqueueAfterPreFlight = async () => {
374
774
  try {
375
- await this.initializationPromise;
775
+ await this.initialize();
376
776
  await (0, _ocap_tx_protocols.inspectTransactionPreFlight)(context);
377
777
  await (0, _ocap_tx_protocols.assertStatelessTxRules)(context);
778
+ await this.assertNotBlockedAtAdmission(context);
378
779
  const preTx = context.tx;
379
780
  const preTxHash = context.txHash;
380
781
  if (preTx) await (0, _ocap_tx_protocols.assertTxAdmission)({
@@ -408,27 +809,54 @@ var OCAPResolver = class {
408
809
  this.logger?.warn?.("Failed to record security strike", { error: strikeErr });
409
810
  }
410
811
  releasePreFlightSlot();
812
+ this.txPreFlightRejectedTotal += 1;
411
813
  reject(preFlightErr);
412
814
  return;
413
815
  }
414
- releasePreFlightSlot();
415
- const currentMaxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
816
+ const currentMaxRequest = this.getMaxTxRequest();
416
817
  if (this.queue.length >= currentMaxRequest) {
818
+ releasePreFlightSlot();
819
+ this.txPreFlightRejectedTotal += 1;
417
820
  reject(new _ocap_util_lib_error.CustomError("FORBIDDEN", "Chain is busy"));
418
821
  return;
419
822
  }
420
823
  const task = async () => {
421
824
  timer.mark("queueWait");
422
825
  try {
423
- const result = await this.executor.execute(context);
826
+ const activeRuntime = this.nodeRuntime;
827
+ if (activeRuntime?.getConsensusCommitter && !("consensusCommitter" in context)) context.consensusCommitter = activeRuntime.getConsensusCommitter();
828
+ const result = typeof activeRuntime?.executeWithConsensusLock === "function" ? await activeRuntime.executeWithConsensusLock(() => this.executor.execute(context)) : await this.executor.execute(context);
424
829
  if (result?.txHash && result?.securityWarning) (0, _ocap_tx_protocols.setTxSecurityWarningForHash)(result.txHash, result.securityWarning, this.statedb);
830
+ this.txAcceptedTotal += 1;
831
+ this.recordCommittedTxSample();
425
832
  resolve(result.txHash);
426
833
  } catch (err) {
834
+ if (err?.isConsensusAbort === true) {
835
+ const activeRuntime = this.nodeRuntime;
836
+ if (ctx.forwardedHop === void 0 && activeRuntime?.writePolicy === "forward" && typeof activeRuntime.forwardSendTx === "function") try {
837
+ const forwarded = await activeRuntime.forwardSendTx({
838
+ tx: txBase64,
839
+ extra
840
+ }, ctx);
841
+ if (forwarded?.hash && forwarded?.warning !== void 0) (0, _ocap_tx_protocols.setTxSecurityWarningForHash)(forwarded.hash, forwarded.warning, this.statedb);
842
+ this.txForwardedTotal += 1;
843
+ resolve(forwarded.hash);
844
+ return;
845
+ } catch (forwardErr) {
846
+ reject(forwardErr);
847
+ return;
848
+ }
849
+ reject(err);
850
+ return;
851
+ }
852
+ if (Number(context.ledgerSequence ?? 0) > 0) this.txPersistedFailedTotal += 1;
853
+ else this.txPreFlightRejectedTotal += 1;
427
854
  await this._indexRejectedLedgerTx(context, err);
428
855
  reject(err);
429
856
  }
430
857
  };
431
858
  this.queue.push(task);
859
+ releasePreFlightSlot();
432
860
  };
433
861
  enqueueAfterPreFlight().catch((err) => {
434
862
  releasePreFlightSlot();
@@ -535,6 +963,7 @@ var OCAPResolver = class {
535
963
  return (0, _ocap_tx_protocols.getTxSecurityWarningByHash)(txHash, this.statedb);
536
964
  }
537
965
  async getTx({ hash }, ctx) {
966
+ assertResolverNotHaltedForDataRead(this);
538
967
  if (_arcblock_validator.patterns.txHash.test(hash)) {
539
968
  const normalizedHash = hash.toUpperCase();
540
969
  const stateTx = await this._getState({
@@ -554,18 +983,60 @@ var OCAPResolver = class {
554
983
  return null;
555
984
  }
556
985
  getBlock() {
986
+ assertResolverNotHaltedForDataRead(this);
557
987
  return null;
558
988
  }
559
989
  getBlocks() {
990
+ assertResolverNotHaltedForDataRead(this);
560
991
  return [];
561
992
  }
562
993
  getUnconfirmedTxs() {
994
+ assertResolverNotHaltedForDataRead(this);
563
995
  return [];
564
996
  }
997
+ async resolveNodeSyncMetadata() {
998
+ if (this.nodeRuntime) {
999
+ const reconciling = Boolean(this.nodeRuntime.isReconciling?.());
1000
+ if (typeof this.nodeRuntime.getFollowerStatus === "function") {
1001
+ const status = await this.nodeRuntime.getFollowerStatus();
1002
+ return {
1003
+ synced: status.synced && !status.halted && !reconciling,
1004
+ nodeRole: status.nodeRole,
1005
+ writePolicy: status.writePolicy,
1006
+ syncLagEntries: status.syncLagEntries,
1007
+ verifiedCheckpointHeight: status.verifiedCheckpointHeight,
1008
+ halted: status.halted
1009
+ };
1010
+ }
1011
+ const [synced, latestCp$1] = await Promise.all([Promise.resolve(this.nodeRuntime.isSynced()), this.ledger?.getCheckpoint ? this.ledger.getCheckpoint().catch(() => null) : Promise.resolve(null)]);
1012
+ const halted = this.nodeRuntime.isHalted();
1013
+ return {
1014
+ synced: synced && !halted && !reconciling,
1015
+ nodeRole: this.nodeRuntime.role,
1016
+ writePolicy: this.nodeRuntime.writePolicy,
1017
+ syncLagEntries: null,
1018
+ verifiedCheckpointHeight: latestCp$1?.height ?? 0,
1019
+ halted
1020
+ };
1021
+ }
1022
+ const latestCp = this.ledger?.getCheckpoint ? await this.ledger.getCheckpoint().catch(() => null) : null;
1023
+ const rawRole = getNormalizedEnvLower("CHAIN_ROLE");
1024
+ const rawMode = getNormalizedEnvLower("CHAIN_MODE");
1025
+ const nodeRole = rawRole === "follower" || rawRole === "standby" ? rawRole : rawMode === "readonly" ? "follower" : "validator";
1026
+ return {
1027
+ synced: true,
1028
+ nodeRole,
1029
+ writePolicy: getNormalizedEnvLower("CHAIN_WRITE_POLICY") === "forward" ? "forward" : "reject",
1030
+ syncLagEntries: nodeRole === "validator" ? 0 : null,
1031
+ verifiedCheckpointHeight: latestCp?.height ?? 0,
1032
+ halted: false
1033
+ };
1034
+ }
565
1035
  async getChainInfo() {
1036
+ const [totalTxs, syncMeta] = await Promise.all([this.indexdb.tx.count(), this.resolveNodeSyncMetadata()]);
566
1037
  return {
567
1038
  id: this.chainAddr,
568
- totalTxs: await this.indexdb.tx.count(),
1039
+ totalTxs,
569
1040
  blockHash: (0, _ocap_util_lib_md5.md5)(""),
570
1041
  blockHeight: 0,
571
1042
  blockTime: "",
@@ -577,12 +1048,18 @@ var OCAPResolver = class {
577
1048
  moniker: this.config.chainId,
578
1049
  network: this.config.chainId,
579
1050
  supportedTxs: this.config.transaction.supportedTxs,
580
- synced: true,
581
- votingPower: "10"
1051
+ synced: syncMeta.synced,
1052
+ nodeRole: syncMeta.nodeRole,
1053
+ writePolicy: syncMeta.writePolicy,
1054
+ syncLagEntries: syncMeta.syncLagEntries,
1055
+ verifiedCheckpointHeight: syncMeta.verifiedCheckpointHeight,
1056
+ halted: syncMeta.halted,
1057
+ votingPower: syncMeta.nodeRole === "validator" ? "10" : "0"
582
1058
  };
583
1059
  }
584
- getNodeInfo() {
585
- return Promise.resolve({
1060
+ async getNodeInfo() {
1061
+ const syncMeta = await this.resolveNodeSyncMetadata();
1062
+ return {
586
1063
  address: this.chainAddr,
587
1064
  appHash: (0, _ocap_util_lib_md5.md5)((/* @__PURE__ */ new Date()).toISOString()),
588
1065
  consensusVersion: this.consensus,
@@ -599,53 +1076,166 @@ var OCAPResolver = class {
599
1076
  network: this.config.chainId,
600
1077
  p2pAddress: "",
601
1078
  supportedTxs: this.config.transaction.supportedTxs,
602
- synced: true,
603
- votingPower: "10"
604
- });
1079
+ synced: syncMeta.synced,
1080
+ nodeRole: syncMeta.nodeRole,
1081
+ writePolicy: syncMeta.writePolicy,
1082
+ syncLagEntries: syncMeta.syncLagEntries,
1083
+ verifiedCheckpointHeight: syncMeta.verifiedCheckpointHeight,
1084
+ halted: syncMeta.halted,
1085
+ votingPower: syncMeta.nodeRole === "validator" ? "10" : "0"
1086
+ };
605
1087
  }
606
- getNetInfo() {
607
- return Promise.resolve({
1088
+ async getNetInfo() {
1089
+ if (!this.nodeRuntime || typeof this.nodeRuntime.getRuntimeDiagnostics !== "function") return {
608
1090
  listeners: [],
609
1091
  listening: true,
610
1092
  nPeers: 0,
611
1093
  peers: []
612
- });
1094
+ };
1095
+ const diag = await Promise.resolve(this.nodeRuntime.getRuntimeDiagnostics({ includePrivateTopology: false }));
1096
+ const listening = !this.nodeRuntime.isHalted();
1097
+ const defaultGeo = {
1098
+ city: "Unknown",
1099
+ country: "Unknown",
1100
+ latitude: 0,
1101
+ longitude: 0
1102
+ };
1103
+ if (diag.mode === "hotstuff" && Array.isArray(diag.validators)) {
1104
+ const peerValidators = diag.validators.filter((v$1) => !v$1.isSelf && v$1.reachable && typeof v$1.did === "string");
1105
+ return {
1106
+ listeners: [],
1107
+ listening,
1108
+ nPeers: peerValidators.length,
1109
+ peers: peerValidators.map((peer) => ({
1110
+ id: peer.did,
1111
+ moniker: peer.did,
1112
+ network: this.config.chainId,
1113
+ consensusVersion: this.consensus,
1114
+ ip: "",
1115
+ geoInfo: defaultGeo
1116
+ }))
1117
+ };
1118
+ }
1119
+ if (diag.mode === "follower") {
1120
+ const leaderRouter = diag.leaderRouter;
1121
+ const candidates = Array.isArray(leaderRouter?.candidates) ? leaderRouter.candidates : [];
1122
+ const activePeers = candidates.length > 0 ? candidates.filter((c) => c.reachable) : Number(diag.peerCount ?? 0) > 0 && Boolean(diag.hasActiveLeader) ? [{
1123
+ id: "upstream-peer-1",
1124
+ reachable: true
1125
+ }] : [];
1126
+ return {
1127
+ listeners: [],
1128
+ listening,
1129
+ nPeers: activePeers.length,
1130
+ peers: activePeers.map((c, idx) => ({
1131
+ id: c.id || `upstream-peer-${idx + 1}`,
1132
+ moniker: c.id || `upstream-peer-${idx + 1}`,
1133
+ network: this.config.chainId,
1134
+ consensusVersion: this.consensus,
1135
+ ip: "",
1136
+ geoInfo: defaultGeo
1137
+ }))
1138
+ };
1139
+ }
1140
+ return {
1141
+ listeners: [],
1142
+ listening,
1143
+ nPeers: 0,
1144
+ peers: []
1145
+ };
613
1146
  }
614
- getValidatorsInfo() {
615
- return Promise.resolve({
1147
+ async getValidatorsInfo() {
1148
+ assertResolverNotHaltedForDataRead(this);
1149
+ const formatPubKey = (rawPk) => {
1150
+ const cleanPkHex = rawPk ? rawPk.replace(/^0x/i, "") : "";
1151
+ if (!cleanPkHex || !/^[0-9a-fA-F]+$/.test(cleanPkHex)) return;
1152
+ return {
1153
+ type: cleanPkHex.length === 64 ? "ed25519" : "secp256k1",
1154
+ data: cleanPkHex
1155
+ };
1156
+ };
1157
+ if (this.nodeRuntime && this.nodeRuntime.getConsensusMode?.() === "hotstuff" && typeof this.nodeRuntime.getRuntimeDiagnostics === "function") {
1158
+ const diag = await Promise.resolve(this.nodeRuntime.getRuntimeDiagnostics({ includePrivateTopology: false }));
1159
+ if (Array.isArray(diag.validators) && diag.validators.length > 0) {
1160
+ const leaderDid = typeof diag.currentLeaderDid === "string" ? diag.currentLeaderDid : "";
1161
+ return {
1162
+ blockHeight: 0,
1163
+ validators: diag.validators.map((v$1) => {
1164
+ const pk$1 = formatPubKey(v$1.publicKey);
1165
+ return {
1166
+ address: v$1.did,
1167
+ ...pk$1 ? { pubKey: pk$1 } : {},
1168
+ name: "",
1169
+ proposerPriority: v$1.isCurrentViewLeader || v$1.did === leaderDid ? "1" : "0",
1170
+ votingPower: "10"
1171
+ };
1172
+ })
1173
+ };
1174
+ }
1175
+ }
1176
+ const activeProposer = this.ledger?.getProposer?.() || this.config?.moderator?.address || (0, _arcblock_did.fromPublicKey)(this.chainAddr);
1177
+ const pk = formatPubKey(this.ledger?.getProposerPublicKey?.());
1178
+ return {
616
1179
  blockHeight: 0,
617
1180
  validators: [{
618
- address: this.config?.moderator?.address || (0, _arcblock_did.fromPublicKey)(this.chainAddr),
1181
+ address: activeProposer,
1182
+ ...pk ? { pubKey: pk } : {},
619
1183
  name: "",
620
1184
  proposerPriority: "0",
621
1185
  votingPower: "10"
622
1186
  }]
623
- });
1187
+ };
1188
+ }
1189
+ async getLedgerInfo() {
1190
+ assertResolverNotHaltedForDataRead(this);
1191
+ if (!this.ledger) return null;
1192
+ const latestSequence = await this.ledger.getLatestSequence();
1193
+ const rawV2From = typeof this.ledger.getEntryHashV2From === "function" ? this.ledger.getEntryHashV2From() : void 0;
1194
+ const entryHashV2From = rawV2From === void 0 ? null : rawV2From === Number.POSITIVE_INFINITY ? "infinity" : String(rawV2From);
1195
+ const proposer = this.ledger.getProposer?.() || this.config?.moderator?.address || null;
1196
+ const proposerPublicKey = this.ledger.getProposerPublicKey?.() || null;
1197
+ const checkpointSigningEnabled = typeof this.ledger.isCheckpointSigningEnabled === "function" ? this.ledger.isCheckpointSigningEnabled() : Boolean(proposerPublicKey);
1198
+ return {
1199
+ chainId: this.config?.chainId || this.ledger.chainId,
1200
+ latestSequence,
1201
+ entryHashV2From,
1202
+ proposer,
1203
+ proposerPublicKey,
1204
+ checkpointSigningEnabled
1205
+ };
624
1206
  }
625
1207
  async getLatestCheckpoint({ height } = {}) {
1208
+ assertResolverNotHaltedForDataRead(this);
626
1209
  if (!this.ledger) return null;
627
1210
  const targetHeight = height !== void 0 && height !== null ? Number(height) : void 0;
628
1211
  return this.ledger.getCheckpoint(targetHeight);
629
1212
  }
630
1213
  async getLedgerEntry({ hash, sequence } = {}) {
1214
+ assertResolverNotHaltedForDataRead(this);
631
1215
  if (!this.ledger) return null;
632
1216
  if (sequence !== void 0 && sequence !== null) return this.ledger.getBySequence(Number(sequence));
633
1217
  if (hash) return this.ledger.get(String(hash));
634
1218
  return null;
635
1219
  }
636
1220
  async getMerkleProof({ sequence }) {
1221
+ assertResolverNotHaltedForDataRead(this);
637
1222
  if (!this.ledger || sequence === void 0 || sequence === null) return null;
638
1223
  const seq = Number(sequence);
639
1224
  const [proof, checkpoint] = await Promise.all([this.ledger.getMerkleProof(seq), this.ledger.getCheckpointForSequence(seq)]);
1225
+ const rawV2From = typeof this.ledger.getEntryHashV2From === "function" ? this.ledger.getEntryHashV2From() : void 0;
1226
+ const entryHashV2From = rawV2From === void 0 ? void 0 : rawV2From === Number.POSITIVE_INFINITY ? "infinity" : String(rawV2From);
640
1227
  return {
641
1228
  proof,
642
- checkpoint
1229
+ checkpoint,
1230
+ ...entryHashV2From !== void 0 ? { entryHashV2From } : {}
643
1231
  };
644
1232
  }
645
1233
  getConfig() {
1234
+ assertResolverNotHaltedForDataRead(this);
646
1235
  return JSON.stringify(this.config);
647
1236
  }
648
1237
  getAccountState({ address, traceMigration = true, expandContext = true }, ctx) {
1238
+ assertResolverNotHaltedForDataRead(this);
649
1239
  return this._getState({
650
1240
  table: "account",
651
1241
  id: address,
@@ -662,6 +1252,7 @@ var OCAPResolver = class {
662
1252
  });
663
1253
  }
664
1254
  getStakeState({ address }, ctx) {
1255
+ assertResolverNotHaltedForDataRead(this);
665
1256
  return this._getState({
666
1257
  table: "stake",
667
1258
  id: address,
@@ -677,6 +1268,7 @@ var OCAPResolver = class {
677
1268
  });
678
1269
  }
679
1270
  async getRollupState({ address }, ctx) {
1271
+ assertResolverNotHaltedForDataRead(this);
680
1272
  const rollup = await this._getState({
681
1273
  table: "rollup",
682
1274
  id: address,
@@ -699,6 +1291,7 @@ var OCAPResolver = class {
699
1291
  return rollup;
700
1292
  }
701
1293
  async getRollupBlock({ hash, height, rollupAddress }, ctx) {
1294
+ assertResolverNotHaltedForDataRead(this);
702
1295
  if (hash) return this._getState({
703
1296
  table: "rollupBlock",
704
1297
  id: hash,
@@ -722,6 +1315,7 @@ var OCAPResolver = class {
722
1315
  throw new Error("Can not get rollup block without hash or height + rollup");
723
1316
  }
724
1317
  getAssetState({ address }, ctx) {
1318
+ assertResolverNotHaltedForDataRead(this);
725
1319
  return this._getState({
726
1320
  table: "asset",
727
1321
  id: address,
@@ -734,6 +1328,7 @@ var OCAPResolver = class {
734
1328
  });
735
1329
  }
736
1330
  getEvidenceState({ hash }, ctx) {
1331
+ assertResolverNotHaltedForDataRead(this);
737
1332
  return this._getState({
738
1333
  table: "evidence",
739
1334
  id: hash,
@@ -742,6 +1337,7 @@ var OCAPResolver = class {
742
1337
  });
743
1338
  }
744
1339
  getFactoryState({ address }, ctx) {
1340
+ assertResolverNotHaltedForDataRead(this);
745
1341
  return this._getState({
746
1342
  table: "factory",
747
1343
  id: address,
@@ -760,6 +1356,7 @@ var OCAPResolver = class {
760
1356
  });
761
1357
  }
762
1358
  async getTokenState({ address }, ctx) {
1359
+ assertResolverNotHaltedForDataRead(this);
763
1360
  const state = await this._getState({
764
1361
  table: "token",
765
1362
  id: address,
@@ -773,6 +1370,7 @@ var OCAPResolver = class {
773
1370
  return state;
774
1371
  }
775
1372
  getTokenFactoryState(args, ctx) {
1373
+ assertResolverNotHaltedForDataRead(this);
776
1374
  return this._getState({
777
1375
  table: "tokenFactory",
778
1376
  id: args.address,
@@ -795,6 +1393,7 @@ var OCAPResolver = class {
795
1393
  });
796
1394
  }
797
1395
  getDelegateState({ address }, ctx) {
1396
+ assertResolverNotHaltedForDataRead(this);
798
1397
  return this._getState({
799
1398
  table: "delegation",
800
1399
  id: address,
@@ -810,6 +1409,7 @@ var OCAPResolver = class {
810
1409
  });
811
1410
  }
812
1411
  async getAccountTokens({ address, token }, ctx) {
1412
+ assertResolverNotHaltedForDataRead(this);
813
1413
  if (!address) return [];
814
1414
  let state = null;
815
1415
  if ((0, _arcblock_did.toTypeInfo)(address).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET) state = await this._getState({
@@ -851,6 +1451,7 @@ var OCAPResolver = class {
851
1451
  }));
852
1452
  }
853
1453
  getForgeState() {
1454
+ assertResolverNotHaltedForDataRead(this);
854
1455
  const { accounts, token, transaction, vaults } = this.config;
855
1456
  return Promise.resolve({
856
1457
  accountConfig: accounts,
@@ -889,6 +1490,7 @@ var OCAPResolver = class {
889
1490
  });
890
1491
  }
891
1492
  async getForgeStats() {
1493
+ assertResolverNotHaltedForDataRead(this);
892
1494
  const [accountCount, assetCount, txCount] = await Promise.all([
893
1495
  this.indexdb.account.count(),
894
1496
  this.indexdb.asset.count(),
@@ -918,12 +1520,15 @@ var OCAPResolver = class {
918
1520
  };
919
1521
  }
920
1522
  async listTransactions(args = {}, ctx) {
1523
+ assertResolverNotHaltedForDataRead(this);
921
1524
  return await this._doPaginatedSearch("listTransactions", withTxProjection(args, ctx), "transactions", "tx.itxJson.data", ctx);
922
1525
  }
923
1526
  listAssets(args = {}, ctx) {
1527
+ assertResolverNotHaltedForDataRead(this);
924
1528
  return this._doPaginatedSearch("listAssets", args, "assets", "data", ctx);
925
1529
  }
926
1530
  listAssetTransactions(args = {}, ctx = {}) {
1531
+ assertResolverNotHaltedForDataRead(this);
927
1532
  if (!args.address) return Promise.resolve({ transactions: [] });
928
1533
  return this._doPaginatedSearch("listTransactions", withTxProjection({
929
1534
  ...args,
@@ -931,6 +1536,7 @@ var OCAPResolver = class {
931
1536
  }, ctx), "transactions", "tx.itxJson.data", ctx);
932
1537
  }
933
1538
  async listFactories(args = {}, ctx) {
1539
+ assertResolverNotHaltedForDataRead(this);
934
1540
  const result = await this._doPaginatedSearch("listFactories", args, "factories", "data", ctx);
935
1541
  result.factories = result.factories.map((x) => {
936
1542
  const output = x.output;
@@ -940,24 +1546,31 @@ var OCAPResolver = class {
940
1546
  return result;
941
1547
  }
942
1548
  listTopAccounts(args = {}) {
1549
+ assertResolverNotHaltedForDataRead(this);
943
1550
  return this._doPaginatedSearch("listTopAccounts", args, "accounts");
944
1551
  }
945
1552
  listTokens(args = {}, ctx) {
1553
+ assertResolverNotHaltedForDataRead(this);
946
1554
  return this._doPaginatedSearch("listTokens", args, "tokens", ["data", "metadata"], ctx);
947
1555
  }
948
1556
  listTokenFactories(args = {}, ctx) {
1557
+ assertResolverNotHaltedForDataRead(this);
949
1558
  return this._doPaginatedSearch("listTokenFactories", args, "tokenFactories", "data", ctx);
950
1559
  }
951
1560
  listStakes(args = {}, ctx) {
1561
+ assertResolverNotHaltedForDataRead(this);
952
1562
  return this._doPaginatedSearch("listStakes", args, "stakes", "data", ctx);
953
1563
  }
954
1564
  listRollups(args = {}, ctx) {
1565
+ assertResolverNotHaltedForDataRead(this);
955
1566
  return this._doPaginatedSearch("listRollups", args, "rollups", "data", ctx);
956
1567
  }
957
1568
  listRollupBlocks(args = {}, ctx) {
1569
+ assertResolverNotHaltedForDataRead(this);
958
1570
  return this._doPaginatedSearch("listRollupBlocks", args, "blocks", "data", ctx);
959
1571
  }
960
1572
  async listRollupValidators(args = {}, ctx) {
1573
+ assertResolverNotHaltedForDataRead(this);
961
1574
  if (!args.rollupAddress) return { validators: [] };
962
1575
  const rollup = await this.statedb.rollup.get(args.rollupAddress);
963
1576
  if (!rollup) return { validators: [] };
@@ -974,9 +1587,11 @@ var OCAPResolver = class {
974
1587
  return result;
975
1588
  }
976
1589
  listDelegations(args = {}, ctx) {
1590
+ assertResolverNotHaltedForDataRead(this);
977
1591
  return this._doPaginatedSearch("listDelegations", args, "delegations", "data", ctx);
978
1592
  }
979
1593
  verifyAccountRisk(args = {}, ctx) {
1594
+ assertResolverNotHaltedForDataRead(this);
980
1595
  if (process.env.TOKEN_FLOW_ENABLED === "true") return require_token_flow.verifyAccountRisk({
981
1596
  ...args,
982
1597
  tokenAddress: (0, _ocap_util.toAddress)(args.tokenAddress || this.config.token.address),
@@ -988,10 +1603,12 @@ var OCAPResolver = class {
988
1603
  return null;
989
1604
  }
990
1605
  listTokenFlows(args = {}, ctx) {
1606
+ assertResolverNotHaltedForDataRead(this);
991
1607
  if (process.env.TOKEN_FLOW_ENABLED === "true") return require_token_flow.listTokenFlows(args, this, ctx);
992
1608
  return [];
993
1609
  }
994
1610
  async search(args) {
1611
+ assertResolverNotHaltedForDataRead(this);
995
1612
  if (!args.keyword) return { results: [] };
996
1613
  const doSearch = async (type, keyword) => {
997
1614
  const result = await this.indexdb[type].get(keyword);
@@ -1017,6 +1634,7 @@ var OCAPResolver = class {
1017
1634
  return { results: [] };
1018
1635
  }
1019
1636
  estimateGas(args = {}) {
1637
+ assertResolverNotHaltedForDataRead(this);
1020
1638
  const { typeUrl = "" } = args;
1021
1639
  if (!typeUrl || !maxGasOps[typeUrl]) throw new _ocap_util_lib_error.CustomError("INVALID_REQUEST", "Unknown tx typeUrl");
1022
1640
  const { txGas, maxTxSize } = this.config.transaction;
@@ -1026,15 +1644,25 @@ var OCAPResolver = class {
1026
1644
  totalGas = totalGas.add(new _ocap_util.BN(txGas.price).mul(new _ocap_util.BN(txGas.updateState)).mul(new _ocap_util.BN(estimate.update)));
1027
1645
  return { estimate: { max: totalGas.toString(10) } };
1028
1646
  }
1029
- async shutdown() {
1030
- if (this.queue) {
1031
- this.queue.autostart = false;
1032
- if (this.queue.length > 0) await new Promise((resolve) => {
1033
- this.queue.on("end", resolve);
1647
+ shutdown() {
1648
+ this.isShuttingDown = true;
1649
+ if (!this.shutdownPromise) this.shutdownPromise = (async () => {
1650
+ if (this.inFlightPreFlights > 0) await new Promise((resolve) => {
1651
+ if (this.inFlightPreFlights === 0) resolve();
1652
+ else this.preFlightDrainWaiters.push(resolve);
1034
1653
  });
1035
- }
1654
+ if (this.queue) {
1655
+ this.queue.autostart = false;
1656
+ if (this.queue.length > 0) await new Promise((resolve) => {
1657
+ this.queue.once("end", () => resolve());
1658
+ });
1659
+ }
1660
+ await this.flushIndexWrites();
1661
+ })();
1662
+ return this.shutdownPromise;
1036
1663
  }
1037
1664
  listBlocks() {
1665
+ assertResolverNotHaltedForDataRead(this);
1038
1666
  return { blocks: [] };
1039
1667
  }
1040
1668
  validateTokenConfig() {
@@ -1054,17 +1682,91 @@ var OCAPResolver = class {
1054
1682
  async getToken(id) {
1055
1683
  return this.statedb.token.get(id);
1056
1684
  }
1057
- async initializeStateDB() {
1685
+ async initializeStateDB(options = {}) {
1686
+ if (this.skipInitializeStateDB || this.nodeRuntime && this.nodeRuntime.role !== "validator") return;
1058
1687
  const { accounts, token } = this.config;
1059
1688
  const { account: accountDB, chain: chainDB, token: tokenDB } = this.statedb;
1060
1689
  const { account: accountState, chain: chainState, token: tokenState } = _ocap_state;
1690
+ const rawTime = options.txTime ?? this.config.genesisTime ?? (process.env.CHAIN_GENESIS_TIME || "").trim();
1691
+ const parsedMs = rawTime === void 0 || rawTime === null || rawTime === "" ? NaN : new Date(rawTime).getTime();
1692
+ const isHotStuffBootstrap = this.explicitConsensusMode === "hotstuff" || !this.explicitConsensusMode && getNormalizedEnvLower("CONSENSUS_MODE") === "hotstuff" || Boolean(this.nodeRuntime?.getConsensusCommitter?.());
1061
1693
  const context = {
1062
- txTime: (/* @__PURE__ */ new Date()).toISOString(),
1694
+ 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(),
1063
1695
  txHash: ""
1064
1696
  };
1065
- await this.runAsLambda(async (txn) => {
1697
+ const config = (0, lodash_omit.default)(this.config, ["reservedSymbols"]);
1698
+ const role = String(this.config.role || process.env.CHAIN_ROLE || "").trim().toLowerCase();
1699
+ const normalizedMode = getNormalizedEnvLower("CHAIN_MODE");
1700
+ const isReadOnlyMode = options.readonly === true || normalizedMode === "readonly" || role === "follower" || role === "standby";
1701
+ const commitGetter = this.statedb.getCommitHash;
1702
+ const hasCommitTracking = typeof commitGetter === "function";
1703
+ if (isReadOnlyMode) {
1704
+ const existingChain$1 = await this.statedb.chain.get(CHAIN_ADDR);
1705
+ if (!existingChain$1) {
1706
+ if (hasCommitTracking) throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "Read-only/follower StateDB is uninitialized (missing chain state)");
1707
+ return;
1708
+ }
1709
+ if (hasCommitTracking) {
1710
+ const roCommit = await commitGetter.call(this.statedb);
1711
+ const roSeq = Number(roCommit?.seq || 0);
1712
+ if (this.tokenItx) {
1713
+ if (!await this.statedb.token.get(this.tokenItx.address) || roCommit?.msg === "initialize chain") throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "Read-only/follower StateDB has incomplete genesis (missing official token state)");
1714
+ if (accounts.length > 0 && roSeq <= 2 && roCommit?.msg === "initialize token" && !await accountDB.get(accounts[0].address)) throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "Read-only/follower StateDB has incomplete genesis (missing initial accounts)");
1715
+ }
1716
+ }
1717
+ chainState.update(existingChain$1, {
1718
+ ...config,
1719
+ context
1720
+ });
1721
+ return;
1722
+ }
1723
+ let stateCommitSeq = 0;
1724
+ let stateCommitMsg = "";
1725
+ let stateCommitCurrentHash = "GENESIS";
1726
+ if (hasCommitTracking) {
1727
+ const commitInfo = await commitGetter.call(this.statedb);
1728
+ stateCommitSeq = Number(commitInfo?.seq || 0);
1729
+ stateCommitMsg = String(commitInfo?.msg || "");
1730
+ stateCommitCurrentHash = String(commitInfo?.currentHash || "GENESIS");
1731
+ }
1732
+ const isLedgerAnchoredRestart = hasCommitTracking && (stateCommitSeq > 0 || Boolean(stateCommitCurrentHash) && stateCommitCurrentHash !== "GENESIS");
1733
+ if (isLedgerAnchoredRestart && this.tokenItx) {
1734
+ if (stateCommitMsg === "initialize chain") throw new _ocap_util_lib_error.CustomError("INTERNAL", "Incomplete genesis StateDB: crashed after chain initialization before official token state was committed");
1735
+ if (accounts.length > 0 && stateCommitSeq <= 2 && stateCommitMsg === "initialize token" && !await accountDB.get(accounts[0].address)) throw new _ocap_util_lib_error.CustomError("INTERNAL", "Incomplete genesis StateDB: crashed after official token initialization before initial accounts were committed");
1736
+ }
1737
+ const existingChain = await this.statedb.chain.get(CHAIN_ADDR);
1738
+ const normalizeComparable = (val) => {
1739
+ if (val === void 0 || val === null) return null;
1740
+ if (Array.isArray(val)) return val.map(normalizeComparable);
1741
+ if (typeof val === "object") {
1742
+ const out = {};
1743
+ for (const [k, v$1] of Object.entries(val)) if (v$1 !== void 0) out[k] = normalizeComparable(v$1);
1744
+ return out;
1745
+ }
1746
+ return val;
1747
+ };
1748
+ const persistedChainKeys = [
1749
+ "chainId",
1750
+ "version",
1751
+ "transaction",
1752
+ "moderator",
1753
+ "accounts",
1754
+ "token",
1755
+ "vaults"
1756
+ ];
1757
+ const expectedConfig = normalizeComparable((0, lodash_pick.default)(this.config, persistedChainKeys));
1758
+ const needsChainWrite = !existingChain || (0, lodash_isEqual.default)(normalizeComparable((0, lodash_pick.default)(existingChain, persistedChainKeys)), expectedConfig) === false;
1759
+ if (isLedgerAnchoredRestart) {
1760
+ if (!existingChain) throw new _ocap_util_lib_error.CustomError("INTERNAL", "Incomplete genesis StateDB: missing chain state while _state_commit.seq > 0");
1761
+ if (needsChainWrite) {
1762
+ chainState.update(existingChain, {
1763
+ ...config,
1764
+ context
1765
+ });
1766
+ this.logger.info("skipping out-of-band chain state update on ledger-anchored restart to preserve _state_commit parity", { stateCommitSeq });
1767
+ }
1768
+ } else if (needsChainWrite) await this.runAsLambda(async (txn) => {
1066
1769
  const info = await this.statedb.chain.get(CHAIN_ADDR, { txn });
1067
- const config = (0, lodash_omit.default)(this.config, ["reservedSymbols"]);
1068
1770
  if (!info) {
1069
1771
  const state = chainState.create({
1070
1772
  ...config,
@@ -1073,7 +1775,7 @@ var OCAPResolver = class {
1073
1775
  });
1074
1776
  const result = await chainDB.create(CHAIN_ADDR, state, { txn });
1075
1777
  this.logger.debug("create chain state", { result });
1076
- } else if ((0, lodash_isEqual.default)((0, lodash_pick.default)(info, Object.keys(config)), config) === false) {
1778
+ } else if ((0, lodash_isEqual.default)(normalizeComparable((0, lodash_pick.default)(info, persistedChainKeys)), normalizeComparable((0, lodash_pick.default)(config, persistedChainKeys))) === false) {
1077
1779
  const state = chainState.update(info, {
1078
1780
  ...config,
1079
1781
  context
@@ -1083,50 +1785,73 @@ var OCAPResolver = class {
1083
1785
  }
1084
1786
  }, { commitMessage: "initialize chain" });
1085
1787
  if (this.tokenItx) {
1086
- await this.runAsLambda(async (txn) => {
1788
+ const changedKeys = [
1789
+ "icon",
1790
+ "website",
1791
+ "metadata"
1792
+ ];
1793
+ const normalizeTokenMutable = (obj) => ({
1794
+ icon: obj?.icon ? String(obj.icon) : "",
1795
+ website: obj?.website ? String(obj.website) : "",
1796
+ metadata: obj?.metadata === void 0 || obj?.metadata === null ? null : normalizeComparable(obj.metadata)
1797
+ });
1798
+ const expectedTokenShape = tokenState.create(this.tokenItx, context);
1799
+ const preExistToken = await this.statedb.token.get(this.tokenItx.address);
1800
+ const needsTokenWrite = !preExistToken || !(0, lodash_isEqual.default)(normalizeTokenMutable(preExistToken), normalizeTokenMutable(expectedTokenShape));
1801
+ if (isLedgerAnchoredRestart) {
1802
+ if (!preExistToken) throw new _ocap_util_lib_error.CustomError("INTERNAL", `Incomplete genesis StateDB: missing official token state (${this.tokenItx.address}) while _state_commit.seq > 0`);
1803
+ if (needsTokenWrite) {
1804
+ tokenState.update(preExistToken, (0, lodash_pick.default)(this.tokenItx, changedKeys));
1805
+ this.logger.info("skipping out-of-band token metadata update on ledger-anchored restart to preserve _state_commit parity", {
1806
+ address: this.tokenItx.address,
1807
+ stateCommitSeq
1808
+ });
1809
+ }
1810
+ } else if (needsTokenWrite) await this.runAsLambda(async (txn) => {
1087
1811
  const existToken = await this.statedb.token.get(this.tokenItx.address, { txn });
1088
1812
  if (!existToken) {
1089
1813
  const state = tokenState.create(this.tokenItx, context);
1090
1814
  const result = await tokenDB.create(this.tokenItx.address, state, { txn });
1091
1815
  tokenDB.emit("create", result, { txn });
1092
1816
  this.logger.debug("create token state", { address: result?.address });
1093
- } else {
1094
- const changedKeys = [
1095
- "icon",
1096
- "website",
1097
- "metadata"
1098
- ];
1099
- const pickStateToken = (0, lodash_pick.default)(existToken, changedKeys);
1100
- const pickConfigToken = (0, lodash_pick.default)(this.tokenItx, changedKeys);
1101
- if (!(0, lodash_isEqual.default)(pickStateToken, pickConfigToken)) {
1102
- const state = tokenState.update(existToken, pickConfigToken);
1103
- const result = await tokenDB.update(this.tokenItx.address, state, { txn });
1104
- tokenDB.emit("update", result, { txn });
1105
- this.logger.info("update token state", { result });
1106
- }
1817
+ } else if (!(0, lodash_isEqual.default)(normalizeTokenMutable(existToken), normalizeTokenMutable(expectedTokenShape))) {
1818
+ const state = tokenState.update(existToken, (0, lodash_pick.default)(this.tokenItx, changedKeys));
1819
+ const result = await tokenDB.update(this.tokenItx.address, state, { txn });
1820
+ tokenDB.emit("update", result, { txn });
1821
+ this.logger.info("update token state", { result });
1107
1822
  }
1108
1823
  }, { commitMessage: "initialize token" });
1109
- await this.runAsLambda(async (txn) => {
1110
- for (let i = 0; i < accounts.length; i++) {
1111
- const { address, balance, moniker, pk } = accounts[i];
1112
- try {
1113
- if (!await accountDB.get(address, { txn })) {
1114
- const balanceStr = (0, _ocap_util.fromTokenToUnit)(balance ?? 0, token.decimal ?? 18).toString(10);
1115
- const state = accountState.create({
1116
- address,
1117
- tokens: { [this.tokenItx.address]: balanceStr },
1118
- moniker: moniker || "token-holder",
1119
- pk
1120
- }, context);
1121
- const result = await accountDB.create(address, state, { txn });
1122
- accountDB.emit("create", result, { txn });
1123
- this.logger.info("create account done", { address });
1824
+ if (!isLedgerAnchoredRestart) {
1825
+ let needsAccountsWrite = false;
1826
+ if (accounts.length > 0) {
1827
+ for (let i = 0; i < accounts.length; i++) if (!await accountDB.get(accounts[i].address)) {
1828
+ needsAccountsWrite = true;
1829
+ break;
1830
+ }
1831
+ } else if (!existingChain) needsAccountsWrite = true;
1832
+ if (needsAccountsWrite) await this.runAsLambda(async (txn) => {
1833
+ for (let i = 0; i < accounts.length; i++) {
1834
+ const { address, balance, moniker, pk } = accounts[i];
1835
+ try {
1836
+ if (!await accountDB.get(address, { txn })) {
1837
+ const balanceStr = (0, _ocap_util.fromTokenToUnit)(balance ?? 0, token.decimal ?? 18).toString(10);
1838
+ const state = accountState.create({
1839
+ address,
1840
+ tokens: { [this.tokenItx.address]: balanceStr },
1841
+ moniker: moniker || "token-holder",
1842
+ pk
1843
+ }, context);
1844
+ const result = await accountDB.create(address, state, { txn });
1845
+ accountDB.emit("create", result, { txn });
1846
+ this.logger.info("create account done", { address });
1847
+ }
1848
+ } catch (err) {
1849
+ this.logger.error("Failed to initialize initial token holders", err);
1850
+ if (hasCommitTracking) throw err;
1124
1851
  }
1125
- } catch (err) {
1126
- this.logger.error("Failed to initialize initial token holders", err);
1127
1852
  }
1128
- }
1129
- }, { commitMessage: "initialize accounts" });
1853
+ }, { commitMessage: "initialize accounts" });
1854
+ }
1130
1855
  }
1131
1856
  }
1132
1857
  /**
@@ -1167,59 +1892,65 @@ var OCAPResolver = class {
1167
1892
  }
1168
1893
  connectIndexDB() {
1169
1894
  const getToken = this.getToken.bind(this);
1170
- this.statedb.tx.on("create", async (x, ctx) => {
1895
+ this.statedb.tx.on("create", (x, ctx) => {
1171
1896
  if (!ctx) return;
1172
- try {
1173
- const tx = await (0, _ocap_indexdb_lib_util.createIndexedTransaction)(x, ctx, this.indexdb);
1174
- await this.indexdb.tx.insert(tx);
1175
- if (typeof require_hooks.onCreateTx === "function") await require_hooks.onCreateTx(tx, ctx, this);
1176
- } catch (error) {
1177
- this.logger.error("create tx index failed", {
1178
- account: x,
1179
- error
1180
- });
1181
- await this.recordIndexFailure({
1182
- table: "tx",
1183
- event: "create",
1184
- entityId: x?.hash,
1185
- payload: x,
1186
- error
1187
- });
1188
- }
1897
+ this.trackIndexWrite((async () => {
1898
+ try {
1899
+ const tx = await (0, _ocap_indexdb_lib_util.createIndexedTransaction)(x, ctx, this.indexdb);
1900
+ await this.indexdb.tx.insert(tx);
1901
+ if (typeof require_hooks.onCreateTx === "function") await require_hooks.onCreateTx(tx, ctx, this);
1902
+ } catch (error) {
1903
+ this.logger.error("create tx index failed", {
1904
+ account: x,
1905
+ error
1906
+ });
1907
+ await this.recordIndexFailure({
1908
+ table: "tx",
1909
+ event: "create",
1910
+ entityId: x?.hash,
1911
+ payload: x,
1912
+ error
1913
+ });
1914
+ }
1915
+ })());
1189
1916
  });
1190
- this.statedb.account.on("create", async (x) => {
1191
- try {
1192
- await this.indexdb.account.insert(await (0, _ocap_indexdb_lib_util.createIndexedAccount)(x, getToken));
1193
- } catch (error) {
1194
- this.logger.error("create account index failed", {
1195
- account: x,
1196
- error
1197
- });
1198
- await this.recordIndexFailure({
1199
- table: "account",
1200
- event: "create",
1201
- entityId: x?.address,
1202
- payload: x,
1203
- error
1204
- });
1205
- }
1917
+ this.statedb.account.on("create", (x) => {
1918
+ this.trackIndexWrite((async () => {
1919
+ try {
1920
+ await this.indexdb.account.insert(await (0, _ocap_indexdb_lib_util.createIndexedAccount)(x, getToken));
1921
+ } catch (error) {
1922
+ this.logger.error("create account index failed", {
1923
+ account: x,
1924
+ error
1925
+ });
1926
+ await this.recordIndexFailure({
1927
+ table: "account",
1928
+ event: "create",
1929
+ entityId: x?.address,
1930
+ payload: x,
1931
+ error
1932
+ });
1933
+ }
1934
+ })());
1206
1935
  });
1207
- this.statedb.account.on("update", async (x) => {
1208
- try {
1209
- await this.indexdb.account.update(x.address, await (0, _ocap_indexdb_lib_util.createIndexedAccount)(x, getToken));
1210
- } catch (error) {
1211
- this.logger.error("update account index failed", {
1212
- account: x,
1213
- error
1214
- });
1215
- await this.recordIndexFailure({
1216
- table: "account",
1217
- event: "update",
1218
- entityId: x?.address,
1219
- payload: x,
1220
- error
1221
- });
1222
- }
1936
+ this.statedb.account.on("update", (x) => {
1937
+ this.trackIndexWrite((async () => {
1938
+ try {
1939
+ await this.indexdb.account.update(x.address, await (0, _ocap_indexdb_lib_util.createIndexedAccount)(x, getToken));
1940
+ } catch (error) {
1941
+ this.logger.error("update account index failed", {
1942
+ account: x,
1943
+ error
1944
+ });
1945
+ await this.recordIndexFailure({
1946
+ table: "account",
1947
+ event: "update",
1948
+ entityId: x?.address,
1949
+ payload: x,
1950
+ error
1951
+ });
1952
+ }
1953
+ })());
1223
1954
  });
1224
1955
  const mapping = {
1225
1956
  asset: [
@@ -1273,45 +2004,49 @@ var OCAPResolver = class {
1273
2004
  };
1274
2005
  Object.keys(mapping).forEach((table) => {
1275
2006
  const [fn, key, onCreate, onUpdate] = mapping[table];
1276
- this.statedb[table].on("create", async (x, _ctx) => {
1277
- try {
1278
- const ctx = this.enrichIndexContext(_ctx);
1279
- const doc = await fn(x, ctx, this.indexdb);
1280
- await this.indexdb[table].insert(doc);
1281
- if (typeof onCreate === "function") await onCreate(doc, ctx, this.indexdb, this);
1282
- } catch (error) {
1283
- this.logger.error(`create ${table} index failed`, {
1284
- [table]: x,
1285
- error
1286
- });
1287
- await this.recordIndexFailure({
1288
- table,
1289
- event: "create",
1290
- entityId: x?.[key],
1291
- payload: x,
1292
- error
1293
- });
1294
- }
2007
+ this.statedb[table].on("create", (x, _ctx) => {
2008
+ this.trackIndexWrite((async () => {
2009
+ try {
2010
+ const ctx = this.enrichIndexContext(_ctx);
2011
+ const doc = await fn(x, ctx, this.indexdb);
2012
+ await this.indexdb[table].insert(doc);
2013
+ if (typeof onCreate === "function") await onCreate(doc, ctx, this.indexdb, this);
2014
+ } catch (error) {
2015
+ this.logger.error(`create ${table} index failed`, {
2016
+ [table]: x,
2017
+ error
2018
+ });
2019
+ await this.recordIndexFailure({
2020
+ table,
2021
+ event: "create",
2022
+ entityId: x?.[key],
2023
+ payload: x,
2024
+ error
2025
+ });
2026
+ }
2027
+ })());
1295
2028
  });
1296
- this.statedb[table].on("update", async (x, _ctx) => {
1297
- try {
1298
- const ctx = this.enrichIndexContext(_ctx);
1299
- const doc = await fn(x, ctx, this.indexdb);
1300
- await this.indexdb[table].update(doc[key], doc);
1301
- if (typeof onUpdate === "function") onUpdate(doc, ctx, this.indexdb, this);
1302
- } catch (error) {
1303
- this.logger.error(`update ${table} index failed`, {
1304
- [table]: x,
1305
- error
1306
- });
1307
- await this.recordIndexFailure({
1308
- table,
1309
- event: "update",
1310
- entityId: x?.[key],
1311
- payload: x,
1312
- error
1313
- });
1314
- }
2029
+ this.statedb[table].on("update", (x, _ctx) => {
2030
+ this.trackIndexWrite((async () => {
2031
+ try {
2032
+ const ctx = this.enrichIndexContext(_ctx);
2033
+ const doc = await fn(x, ctx, this.indexdb);
2034
+ await this.indexdb[table].update(doc[key], doc);
2035
+ if (typeof onUpdate === "function") await onUpdate(doc, ctx, this.indexdb, this);
2036
+ } catch (error) {
2037
+ this.logger.error(`update ${table} index failed`, {
2038
+ [table]: x,
2039
+ error
2040
+ });
2041
+ await this.recordIndexFailure({
2042
+ table,
2043
+ event: "update",
2044
+ entityId: x?.[key],
2045
+ payload: x,
2046
+ error
2047
+ });
2048
+ }
2049
+ })());
1315
2050
  });
1316
2051
  });
1317
2052
  }
@@ -1356,7 +2091,8 @@ var OCAPResolver = class {
1356
2091
  async getReplayTxRollupContext(state) {
1357
2092
  const type = typeof state?.type === "string" ? state.type : "";
1358
2093
  const txType = type ? `fg:t:${type}` : "";
1359
- const address = state?.tx?.itxJson?.rollup;
2094
+ const itxJson = state?.tx?.itxJson;
2095
+ const address = itxJson?.rollup || (type === "create_rollup" ? itxJson?.address : void 0);
1360
2096
  if (typeof address !== "string" || !address) return txType ? { txType } : {};
1361
2097
  const row = await this.statedb.rollup.get(address);
1362
2098
  if (!row) return txType ? { txType } : {};
@@ -1400,9 +2136,9 @@ var OCAPResolver = class {
1400
2136
  };
1401
2137
  const doc$1 = state?.tx && state?.hash && typeof state?.Valid !== "undefined" ? state : await (0, _ocap_indexdb_lib_util.createIndexedTransaction)(state, ctx$1, this.indexdb);
1402
2138
  const existing$1 = await this.indexdb.tx.get(doc$1.hash);
1403
- if (event === "update" && existing$1) await this.indexdb.tx.update(doc$1.hash, doc$1);
2139
+ if (event === "update" && existing$1) await this.indexdb.tx.update(doc$1.hash, (0, _ocap_indexdb_lib_util.formatTxBeforeInsert)(doc$1));
1404
2140
  else if (!existing$1) await this.indexdb.tx.insert(doc$1);
1405
- else await this.indexdb.tx.update(doc$1.hash, doc$1);
2141
+ else await this.indexdb.tx.update(doc$1.hash, (0, _ocap_indexdb_lib_util.formatTxBeforeInsert)(doc$1));
1406
2142
  if (event === "create" && !existing$1 && typeof require_hooks.onCreateTx === "function") await require_hooks.onCreateTx(doc$1, ctx$1, this);
1407
2143
  return;
1408
2144
  }
@@ -1844,6 +2580,7 @@ var OCAPResolver = class {
1844
2580
  return await this.tokenDistribution.updateByToken(tokenAddress, force);
1845
2581
  }
1846
2582
  async getTokenDistribution(args = {}) {
2583
+ assertResolverNotHaltedForDataRead(this);
1847
2584
  const { tokenAddress = this.config.token.address } = args;
1848
2585
  return await this.tokenDistribution.getDistribution(tokenAddress);
1849
2586
  }
@@ -1931,7 +2668,41 @@ var OCAPResolver = class {
1931
2668
  };
1932
2669
 
1933
2670
  //#endregion
2671
+ exports.ConsensusAbortError = require_hotstuff_runtime.ConsensusAbortError;
2672
+ exports.DEFAULT_FOLLOWER_MAX_SYNC_LAG = require_follower.DEFAULT_FOLLOWER_MAX_SYNC_LAG;
2673
+ exports.DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS = require_follower.DEFAULT_FOLLOWER_MAX_UPSTREAM_STALE_MS;
2674
+ exports.DEFAULT_FOLLOWER_POLL_INTERVAL_MS = require_follower.DEFAULT_FOLLOWER_POLL_INTERVAL_MS;
2675
+ exports.FollowerSyncService = require_follower.FollowerSyncService;
1934
2676
  exports.GRAPHQL_INDEXED_TX_COLUMNS = GRAPHQL_INDEXED_TX_COLUMNS;
2677
+ exports.HotStuffNodeRuntime = require_hotstuff_runtime.HotStuffNodeRuntime;
2678
+ exports.LedgerEntryReplayer = require_replayer.LedgerEntryReplayer;
2679
+ exports.MAX_BLOCKED_ACCOUNTS = require_node_preferences.MAX_BLOCKED_ACCOUNTS;
2680
+ exports.MAX_CONFIG_BODY_BYTES = require_node_preferences.MAX_CONFIG_BODY_BYTES;
2681
+ exports.MAX_MEMO_LENGTH = require_node_preferences.MAX_MEMO_LENGTH;
2682
+ exports.MAX_PEER_URLS = require_node_preferences.MAX_PEER_URLS;
2683
+ exports.MAX_RESERVED_SYMBOLS = require_node_preferences.MAX_RESERVED_SYMBOLS;
2684
+ exports.MAX_TRUSTED_ACCOUNTS = require_node_preferences.MAX_TRUSTED_ACCOUNTS;
2685
+ exports.NodePreferencesError = require_node_preferences.NodePreferencesError;
2686
+ exports.NodePreferencesManager = require_node_preferences.NodePreferencesManager;
2687
+ exports.UNIFIED_CONSOLE_APP_JS = require_dashboard.UNIFIED_CONSOLE_APP_JS;
2688
+ exports.applyBootRuntimePreferences = require_node_preferences.applyBootRuntimePreferences;
2689
+ exports.buildUnifiedConsoleHtml = require_dashboard.buildUnifiedConsoleHtml;
2690
+ exports.collectLedgerHealthSummary = require_dashboard.collectLedgerHealthSummary;
2691
+ exports.createAdminAuthGuard = require_node_preferences.createAdminAuthGuard;
2692
+ exports.createExplorerMiddleware = require_explorer.createExplorerMiddleware;
2693
+ exports.createFollowerPeerFetchGuard = require_node_preferences.createFollowerPeerFetchGuard;
2694
+ exports.createNodeDashboardRouter = require_dashboard.createNodeDashboardRouter;
2695
+ exports.createNodeMaintenanceController = require_dashboard.createNodeMaintenanceController;
2696
+ exports.createUnifiedConsoleMiddleware = require_dashboard.createUnifiedConsoleMiddleware;
1935
2697
  exports.default = OCAPResolver;
1936
2698
  exports.formatData = formatData;
1937
- exports.formatDelegationOps = formatDelegationOps;
2699
+ exports.formatDelegationOps = formatDelegationOps;
2700
+ exports.isDashboardEnabled = require_dashboard.isDashboardEnabled;
2701
+ exports.isExplorerEnabled = require_explorer.isExplorerEnabled;
2702
+ exports.isPrivateOrReservedIpAddress = require_node_preferences.isPrivateOrReservedIpAddress;
2703
+ exports.isTransientSqliteLockError = require_follower.isTransientSqliteLockError;
2704
+ exports.isValidAccountAddressCandidate = require_node_preferences.isValidAccountAddressCandidate;
2705
+ exports.loadNodePreferences = require_node_preferences.loadNodePreferences;
2706
+ exports.normalizeBlockedAccountKey = require_node_preferences.normalizeBlockedAccountKey;
2707
+ exports.timingSafeTokenEqual = require_node_preferences.timingSafeTokenEqual;
2708
+ exports.validateFollowerPeerUrls = require_node_preferences.validateFollowerPeerUrls;