const fs = require('fs');
const path = require('path');
const {
  BASE1_ALGORITHM_VERSION,
  evaluateBase1Step,
  generateBase1Step,
  normalizeFragmentGenerationProfile,
} = require('./base1_algorithm');
const {
  deriveNextStepSeedSource,
  finalizeSeedSource,
  genesisStepSeedSource,
  seedSourceCommitment,
} = require('./chain_seed');
const { verifyCandidateStep, verifyOfficialStep, verifierInfo } = require('./expression_tree_verifier');
const { behaviorCommitmentForStep, publicBehaviorCommitment } = require('./behavior_commitment');
const {
  addFragmentRecord,
  computeFragmentRegistryRoots,
  createDefaultFragmentRegistry,
  fragmentDownloadPackage,
  fragmentRecordPackage,
  publicFragmentRegistry,
  quarantineFragment,
  registerFragment,
  selectFragmentsForStep,
  upgradeFragment,
} = require('./fragment_registry');
const { sha256 } = require('./hash');
const {
  appendBlock,
  chainSummary,
  compareChainHeads,
  computeStateRoot,
  createTransaction,
  getBlocks,
  initializeChain,
  upgradeChainWorkScores,
  verifyBlock,
  verifyLocalChain,
} = require('./chain');
const {
  loadLatestFromShardedStorage,
  shardedStorageStatus,
  writeShardedChainState,
} = require('./sharded_chain_storage');
const {
  hydrateBase1PrivateVaultState,
  privateVaultStatus,
  sanitizeBase1PublicState,
  writeBase1PrivateVaultState,
} = require('./private_vault');
const {
  envOrConfigBool,
  envOrConfigList,
  envOrConfigNumber,
  envOrConfigString,
  getChainConfig,
  getGenesisConfig,
  getInitialAccounts,
  getNetworkConfig,
  getRuntimeConfigSnapshot,
  getSecurityConfig,
} = require('./config');

const ROOT = path.resolve(__dirname, '..', '..');
const CHAIN_CONFIG = getChainConfig().chain || {};
const CHAIN_FEES = getChainConfig().fees || {};
const CHAIN_REWARDS = getChainConfig().rewards || {};
const GENESIS_CONFIG = getGenesisConfig().genesis || {};
const INITIAL_ACCOUNTS_CONFIG = getInitialAccounts();
const NETWORK_CONFIG = getNetworkConfig().network || {};
const NETWORK_LIMITS = getNetworkConfig().limits || {};
const SECURITY_LIMITS = getSecurityConfig().payload_limits || {};
const BASE1_DATA_DIR = path.resolve(process.env.MAZEX_DATA_DIR || path.join(ROOT, 'data'));
const BASE1_DATA_PATH = path.resolve(
  process.env.MAZEX_BASE1_STATE_PATH || path.join(BASE1_DATA_DIR, 'mazex_base1_state.json'),
);
const BASE1_STATE_VERSION = 'mazexchain-base1-local-1.0';
const DEFAULT_CHAIN_ID = envOrConfigString(
  'MAZEX_CHAIN_ID',
  CHAIN_CONFIG.chain_id || GENESIS_CONFIG.chain_id,
  'mazexchain-base1-local',
);
const DEFAULT_SEASON_SEED = 'mazex-base1-local-season';
const DEFAULT_GENESIS_CREATED_AT = envOrConfigString(
  'MAZEX_GENESIS_CREATED_AT',
  GENESIS_CONFIG.genesis_time_utc,
  '2026-05-01T00:00:00.000Z',
);
const DEFAULT_INITIAL_LAYER = envOrConfigNumber('MAZEX_INITIAL_LAYER', CHAIN_CONFIG.initial_layer, 1, {
  min: 1,
  integer: true,
});
const DEFAULT_INITIAL_STEP = envOrConfigNumber('MAZEX_INITIAL_STEP', CHAIN_CONFIG.initial_step, 1, {
  min: 1,
  integer: true,
});
const DEFAULT_TRANSFER_FEE = envOrConfigNumber('MAZEX_TRANSFER_FEE', CHAIN_FEES.transfer_fee, 1, {
  min: 0,
  integer: true,
});
const DEFAULT_SAMPLE_FEE = envOrConfigNumber('MAZEX_SAMPLE_FEE', CHAIN_FEES.sample_fee ?? CHAIN_CONFIG.sampling_fee, 0, {
  min: 0,
  integer: true,
});
const DEFAULT_SUBMIT_FEE = Math.max(
  1,
  envOrConfigNumber('MAZEX_SUBMIT_FEE', CHAIN_FEES.submit_fee_min, 10, { min: 1, integer: true }),
);
const DEFAULT_INVALID_SUBMIT_FEE = Math.max(
  0,
  envOrConfigNumber('MAZEX_INVALID_SUBMIT_FEE', CHAIN_FEES.invalid_submit_fee, 0, { min: 0, integer: true }),
);
const BASE1_REWARD_FLOOR = Math.max(
  1,
  envOrConfigNumber('MAZEX_REWARD_FLOOR', CHAIN_REWARDS.floor, 250, { min: 1, integer: true }),
);
const BASE1_REWARD_CAP = Math.max(
  BASE1_REWARD_FLOOR,
  envOrConfigNumber('MAZEX_REWARD_CAP', CHAIN_REWARDS.cap, 50000, { min: BASE1_REWARD_FLOOR, integer: true }),
);
const BASE1_REWARD_CURVE_SCORE = Math.max(
  1,
  envOrConfigNumber('MAZEX_REWARD_CURVE_SCORE', CHAIN_REWARDS.curve_score, 30_000_000, { min: 1 }),
);
const BASE1_SUBMIT_FEE_MIN_RATE = Math.max(
  0,
  envOrConfigNumber('MAZEX_SUBMIT_FEE_MIN_RATE', CHAIN_FEES.submit_fee_min_rate, 0.05, { min: 0 }),
);
const BASE1_SUBMIT_FEE_MAX_RATE = Math.max(
  BASE1_SUBMIT_FEE_MIN_RATE,
  envOrConfigNumber('MAZEX_SUBMIT_FEE_MAX_RATE', CHAIN_FEES.submit_fee_max_rate, 0.12, {
    min: BASE1_SUBMIT_FEE_MIN_RATE,
  }),
);
const BASE1_SUBMIT_FEE_LAYER_SCALE = Math.max(
  1,
  envOrConfigNumber('MAZEX_SUBMIT_FEE_LAYER_SCALE', CHAIN_FEES.submit_fee_layer_scale, 3000, { min: 1 }),
);
const BASE1_MAX_CANDIDATE_PACKAGE_BYTES = Math.max(
  4096,
  envOrConfigNumber('MAZEX_MAX_CANDIDATE_PACKAGE_BYTES', SECURITY_LIMITS.max_candidate_bytes, 256 * 1024, {
    min: 4096,
    integer: true,
  }),
);
const BASE1_PEER_CANDIDATE_ERROR_COOLDOWN_THRESHOLD = Math.max(
  1,
  envOrConfigNumber(
    'MAZEX_PEER_CANDIDATE_ERROR_COOLDOWN_THRESHOLD',
    NETWORK_LIMITS.peer_candidate_error_cooldown_threshold,
    5,
    { min: 1, integer: true },
  ),
);
const BASE1_PEER_CANDIDATE_ERROR_COOLDOWN_MS = Math.max(
  1000,
  envOrConfigNumber(
    'MAZEX_PEER_CANDIDATE_ERROR_COOLDOWN_MS',
    NETWORK_LIMITS.peer_candidate_error_cooldown_ms,
    60_000,
    { min: 1000, integer: true },
  ),
);
const BASE1_SEEN_ANSWER_HASH_LIMIT = Math.max(100, Math.trunc(Number(process.env.MAZEX_SEEN_ANSWER_HASH_LIMIT || 5000)));
const DEFAULT_TIME_BUCKET_SECONDS = Math.max(1, Math.trunc(Number(process.env.MAZEX_TIME_BUCKET_SECONDS || 10)));
const DEFAULT_SOLVE_CONFIRM_WINDOW_MS = Math.max(
  1000,
  envOrConfigNumber('MAZEX_SOLVE_CONFIRM_WINDOW_MS', NETWORK_CONFIG.candidate_confirmation_window_ms, 10000, {
    min: 1000,
    integer: true,
  }),
);
const DEFAULT_HEAD_QUERY_TTL = envOrConfigNumber('MAZEX_HEAD_QUERY_TTL', NETWORK_CONFIG.head_query_ttl, 2, {
  min: 0,
  integer: true,
});
const DEFAULT_HEAD_QUERY_MAX_PEERS = envOrConfigNumber(
  'MAZEX_HEAD_QUERY_MAX_PEERS',
  NETWORK_CONFIG.head_query_max_peers,
  24,
  { min: 0, integer: true },
);
const PRIORITY_RELAYS = envOrConfigList('MAZEX_PRIORITY_RELAYS', NETWORK_CONFIG.priority_relays, []);
const SHARDED_STORAGE_ENABLED = envOrConfigBool('MAZEX_SHARDED_STORAGE', undefined, true);
const SHARDED_STORAGE_READ_ENABLED = envOrConfigBool('MAZEX_SHARDED_STORAGE_READ', undefined, true);
const JSON_STATE_BACKUP_ENABLED = envOrConfigBool('MAZEX_JSON_STATE_BACKUP', undefined, false);
const REWARD_CONFIRMATION_RULES = [
  { tier: 'bottom', min_layer: 1, confirmations: 3, work_multiplier: 0 },
  { tier: 'middle', min_layer: 101, confirmations: 8, work_multiplier: 1 },
  { tier: 'high', min_layer: 1001, confirmations: 20, work_multiplier: 2 },
  { tier: 'top', min_layer: 5001, confirmations: 50, work_multiplier: 3 },
];

function nowIso() {
  return new Date().toISOString();
}

function initialAccountsFromConfig() {
  const accounts = {};
  for (const entry of INITIAL_ACCOUNTS_CONFIG.accounts || []) {
    const address = String(entry.address || '').trim();
    if (!address) continue;
    accounts[address] = {
      address,
      confirmed_balance: Math.max(0, Math.trunc(Number(entry.confirmed_balance ?? entry.balance ?? 0))),
      pending_balance: Math.max(0, Math.trunc(Number(entry.pending_balance || 0))),
      total_mined_pending: 0,
      total_mined_confirmed: 0,
      total_received: Math.max(0, Math.trunc(Number(entry.confirmed_balance ?? entry.balance ?? 0))),
      total_sent: 0,
      total_submit_fees_burned: 0,
      total_reward_fees_burned: 0,
      nonce: Math.max(0, Math.trunc(Number(entry.nonce || 0))),
      updated_at: nowIso(),
    };
  }
  return accounts;
}

function ensureDataDir() {
  fs.mkdirSync(path.dirname(BASE1_DATA_PATH), { recursive: true });
}

function stepKey(layerNo, stepNo) {
  return `${Number(layerNo)}:${Number(stepNo)}`;
}

function behaviorOptionsForStep(step) {
  return {
    mode: step.grid_size * step.grid_size <= 2500 ? 'full_domain' : 'sample',
  };
}

function makeStepCommitment(step, seedSource, fragmentRegistryRoot = null, fragmentSelection = null) {
  const seedCommitment = seedSourceCommitment(seedSource);
  const fragmentGenerationProfile = fragmentSelection?.generation_profile || step.fragment_generation_profile || null;
  const behaviorCommitment = behaviorCommitmentForStep(step, behaviorOptionsForStep(step));
  const payload = {
    type: 'mazex.base1.step_commitment',
    algorithm: step.algorithm,
    layer_no: step.layer_no,
    step_no: step.step_no,
    grid_size: step.grid_size,
    step_count: step.step_count,
    growth_tier: step.growth_tier,
    formula_hash: step.formula_hash,
    fragment_registry_root: fragmentRegistryRoot,
    fragment_selection_hash: fragmentSelection?.selection_hash || null,
    fragment_selection_root: fragmentSelection?.selection_root || null,
    fragment_composition_plan_hash: fragmentSelection?.composition_plan_hash || null,
    fragment_generation_profile_hash: fragmentGenerationProfile?.profile_hash || null,
    seed_source_hash: seedCommitment.source_hash,
    step_seed_hash: seedCommitment.step_seed_hash,
    score: step.scores?.final_score || null,
  };
  return {
    ...payload,
    seed_commitment: seedCommitment,
    behavior_commitment: publicBehaviorCommitment(behaviorCommitment),
    behavior_root: behaviorCommitment.behavior_root,
    behavior_commitment_hash: behaviorCommitment.commitment_hash,
    fragment_registry_root: fragmentRegistryRoot,
    fragment_selection: fragmentSelection
      ? {
          selection_hash: fragmentSelection.selection_hash,
          selection_root: fragmentSelection.selection_root,
          composition_plan_hash: fragmentSelection.composition_plan_hash,
          generation_profile_hash: fragmentGenerationProfile?.profile_hash || null,
          selected_count: fragmentSelection.selected_count,
          selected: fragmentSelection.selected,
        }
      : null,
    step_commit: sha256(payload),
  };
}

function publicStep(step, seedSource, commitment) {
  const behaviorCommitment =
    commitment?.behavior_commitment || publicBehaviorCommitment(behaviorCommitmentForStep(step, behaviorOptionsForStep(step)));
  const info = verifierInfo(step, behaviorOptionsForStep(step));
  const rewardAmount = rewardForStep(step);
  const submitCost = submitFeeForStep(step);
  return {
    algorithm: step.algorithm,
    layer_no: step.layer_no,
    step_no: step.step_no,
    step_count: step.step_count,
    progress: `${step.step_no}/${step.step_count}`,
    grid_size: step.grid_size,
    growth_tier: step.growth_tier,
    growth_units: step.growth_units,
    randomness_mode: step.randomness_mode,
    seed_source_hash: seedSource.source_hash,
    formula_hash: step.formula_hash,
    fragment_registry_root: commitment.fragment_registry_root || null,
    fragment_selection_hash: commitment.fragment_selection?.selection_hash || null,
    fragment_selection_root: commitment.fragment_selection?.selection_root || null,
    fragment_composition_plan_hash: commitment.fragment_selection?.composition_plan_hash || null,
    fragment_generation_profile_hash:
      commitment.fragment_selection?.generation_profile_hash ||
      commitment.fragment_selection?.generation_profile?.profile_hash ||
      step.fragment_generation_profile_hash ||
      null,
    fragment_selected_count: commitment.fragment_selection?.selected_count || 0,
    step_commit: commitment.step_commit,
    behavior_root: behaviorCommitment.behavior_root,
    behavior_commitment_hash: behaviorCommitment.commitment_hash,
    behavior_commitment: behaviorCommitment,
    score: step.scores.final_score,
    score_components: {
      grid_score: step.scores.grid_score,
      layer_score: step.scores.layer_score,
      parameter_score: step.scores.parameter_score,
      operator_score: step.scores.operator_score,
    },
    counts: step.counts,
    reward_amount: rewardAmount,
    reward_policy: {
      type: 'capped_exponential_curve',
      floor: BASE1_REWARD_FLOOR,
      cap: BASE1_REWARD_CAP,
      curve_score: BASE1_REWARD_CURVE_SCORE,
    },
    sample_cost: DEFAULT_SAMPLE_FEE,
    submit_cost: submitCost,
    invalid_submit_cost: invalidSubmitFeeForStep(step),
    submit_fee_rate: submitFeeRateForStep(step),
    submit_fee_rate_bps: Math.round(submitFeeRateForStep(step) * 10000),
    verifier: {
      version: info.verifier_version,
      point_mode: info.point_set.mode,
      point_count: info.point_set.total,
      point_set_hash: info.point_set.hash,
      context_set_hash: info.context_set.hash,
      stages: info.stages,
    },
  };
}

function fragmentSelectionForStep(registry, step, seedSource, currentHeight) {
  return selectFragmentsForStep(registry || null, {
    currentHeight,
    step,
    seed: seedSource?.step_seed || seedSource?.source_hash || step?.seed || '',
    maxCount: Math.min(12, Math.max(4, Math.ceil(Number(step?.counts?.operator_unit_count || 4) / 2))),
  });
}

function bindSeedSourceToFragments(seedSource, fragmentSelection, fragmentGenerationProfile = null) {
  const normalizedProfile = normalizeFragmentGenerationProfile(
    fragmentGenerationProfile || fragmentSelection?.generation_profile || null,
  );
  const binding = {
    type: 'mazex.base1.fragment_seed_binding',
    algorithm: BASE1_ALGORITHM_VERSION,
    layer_no: seedSource.layer_no,
    step_no: seedSource.step_no,
    pre_fragment_source_hash: seedSource.source_hash,
    pre_fragment_step_seed_hash: sha256(seedSource.step_seed || ''),
    fragment_registry_root: fragmentSelection?.active_root || null,
    fragment_selection_hash: fragmentSelection?.selection_hash || null,
    fragment_selection_root: fragmentSelection?.selection_root || null,
    fragment_composition_plan_hash: fragmentSelection?.composition_plan_hash || null,
    fragment_generation_profile_hash: normalizedProfile?.profile_hash || null,
  };
  return finalizeSeedSource({
    ...seedSource,
    type: 'FRAGMENT_BOUND_STEP_SEED',
    pre_fragment_source_hash: seedSource.source_hash,
    pre_fragment_step_seed_hash: sha256(seedSource.step_seed || ''),
    fragment_binding_hash: sha256(binding),
    fragment_registry_root: fragmentSelection?.active_root || null,
    fragment_selection_hash: fragmentSelection?.selection_hash || null,
    fragment_selection_root: fragmentSelection?.selection_root || null,
    fragment_composition_plan_hash: fragmentSelection?.composition_plan_hash || null,
    fragment_generation_profile_hash: normalizedProfile?.profile_hash || null,
  });
}

function generateFragmentBoundStep({ layerNo, stepNo, seedSource, fragmentRegistry, currentHeight = 0 }) {
  const draftStep = generateBase1Step({ layerNo, stepNo, seedSource });
  const fragmentSelection = fragmentSelectionForStep(fragmentRegistry, draftStep, seedSource, currentHeight);
  const fragmentGenerationProfile = normalizeFragmentGenerationProfile(fragmentSelection?.generation_profile || null);
  const boundSeedSource = bindSeedSourceToFragments(seedSource, fragmentSelection, fragmentGenerationProfile);
  const step = generateBase1Step({
    layerNo,
    stepNo,
    seedSource: boundSeedSource,
    fragmentProfile: fragmentGenerationProfile,
  });
  return { step, seedSource: boundSeedSource, fragmentSelection, fragmentGenerationProfile, draftStep };
}

function makeGenesisStep({
  chainId,
  seasonSeed,
  createdAt,
  fragmentRegistry = null,
  layerNo = DEFAULT_INITIAL_LAYER,
  stepNo = DEFAULT_INITIAL_STEP,
} = {}) {
  const genesisHash = sha256({
    type: 'mazex.base1.genesis',
    chain_id: chainId,
    season_seed: seasonSeed,
    created_at: createdAt,
  });
  const baseSeedSource = genesisStepSeedSource({
    chainId,
    seasonSeed,
    algorithm: BASE1_ALGORITHM_VERSION,
    layerNo,
    stepNo,
    genesisHash,
  });
  const generated = generateFragmentBoundStep({
    layerNo,
    stepNo,
    seedSource: baseSeedSource,
    fragmentRegistry,
    currentHeight: 0,
  });
  const { step, seedSource, fragmentSelection } = generated;
  const roots = computeFragmentRegistryRoots(fragmentRegistry || null, { currentHeight: 0 });
  const commitment = makeStepCommitment(step, seedSource, roots.active_root, fragmentSelection);
  return { genesisHash, seedSource, step, commitment };
}

function buildFreshBase1State({
  chainId = DEFAULT_CHAIN_ID,
  seasonSeed = DEFAULT_SEASON_SEED,
  genesisCreatedAt = DEFAULT_GENESIS_CREATED_AT,
  initialLayer = DEFAULT_INITIAL_LAYER,
  initialStep = DEFAULT_INITIAL_STEP,
} = {}) {
  const createdAt = nowIso();
  const fragmentRegistry = createDefaultFragmentRegistry();
  const { genesisHash, seedSource, step, commitment } = makeGenesisStep({
    chainId,
    seasonSeed,
    createdAt: genesisCreatedAt,
    fragmentRegistry,
    layerNo: initialLayer,
    stepNo: initialStep,
  });
  const key = stepKey(step.layer_no, step.step_no);
  const state = {
    version: BASE1_STATE_VERSION,
    chainId,
    seasonSeed,
    genesisHash,
    genesisCreatedAt,
    createdAt,
    currentLayer: step.layer_no,
    currentStep: step.step_no,
    gridSize: step.grid_size,
    currentStepKey: key,
    currentFormulaHash: step.formula_hash,
    currentSeedSourceHash: seedSource.source_hash,
    currentStepCommitment: commitment,
    fragmentRegistry,
    officialStepsByKey: {
      [key]: step,
    },
    seedSourcesByKey: {
      [key]: seedSource,
    },
    commitmentsByKey: {
      [key]: commitment,
    },
    generatedStepKeys: [key],
    solvedSteps: [],
    samples: [],
    submissions: [],
    accounts: initialAccountsFromConfig(),
    rewardLedger: [],
    transfers: [],
    burnedFees: 0,
    blockSyncInbox: [],
    seenAnswerHashes: [],
    peers: [],
    networkMessages: [],
    timeSync: null,
    solveReceipts: [],
    stepLocks: {},
    events: [
      {
        type: 'BASE1_GENESIS_STEP_COMMITTED',
        created_at: createdAt,
        layer_no: step.layer_no,
        step_no: step.step_no,
        seed_source_hash: seedSource.source_hash,
        formula_hash: step.formula_hash,
        fragment_registry_root: commitment.fragment_registry_root,
        behavior_root: commitment.behavior_root,
        behavior_commitment_hash: commitment.behavior_commitment_hash,
        step_commit: commitment.step_commit,
      },
    ],
    leaderboard: {},
  };
  state.chain = initializeChain(state, genesisCreatedAt);
  return state;
}

function loadBase1State() {
  ensureDataDir();
  if (SHARDED_STORAGE_READ_ENABLED) {
    const sharded = loadLatestFromShardedStorage({ hydrateBlocks: true });
    if (sharded) return normalizeBase1State(hydrateBase1PrivateVaultState(sharded));
  }
  if (!fs.existsSync(BASE1_DATA_PATH)) {
    const state = buildFreshBase1State();
    saveBase1State(state);
    return state;
  }
  return normalizeBase1State(JSON.parse(fs.readFileSync(BASE1_DATA_PATH, 'utf8')));
}

function saveBase1State(state) {
  ensureDataDir();
  writeBase1PrivateVaultState(state);
  if (SHARDED_STORAGE_ENABLED) {
    writeShardedChainState(state);
  }
  if (JSON_STATE_BACKUP_ENABLED || !SHARDED_STORAGE_ENABLED) {
    fs.writeFileSync(BASE1_DATA_PATH, JSON.stringify(state, null, 2), 'utf8');
  }
}

function resetBase1State(options = {}) {
  const state = buildFreshBase1State(options);
  saveBase1State(state);
  return state;
}

function normalizeBase1State(state) {
  state.generatedStepKeys ||= [];
  state.solvedSteps ||= [];
  state.samples ||= [];
  state.submissions ||= [];
  state.events ||= [];
  state.leaderboard ||= {};
  state.accounts ||= {};
  state.rewardLedger ||= [];
  state.transfers ||= [];
  state.burnedFees = Number(state.burnedFees || 0);
  state.blockSyncInbox ||= [];
  state.seenAnswerHashes ||= [];
  state.peers ||= [];
  state.peerReputation ||= {};
  state.witnesses ||= [];
  state.networkMessages ||= [];
  state.timeSync ||= null;
  state.solveReceipts ||= [];
  state.stepLocks ||= {};
  state.peers = state.peers.map((peer) => normalizeBase1Peer(peer, state));
  if (!state.chain) {
    state.chain = initializeChain(state, state.createdAt || nowIso());
  } else {
    upgradeChainWorkScores(state.chain);
  }
  if (state.fragmentRegistry) {
    state.fragmentRegistry = {
      ...state.fragmentRegistry,
      ...computeFragmentRegistryRoots(state.fragmentRegistry, { currentHeight: state.chain?.height || 0 }),
    };
  }
  return state;
}

function peerIdForUrl(url) {
  return sha256({ type: 'mazex.base1.peer', url: String(url || '').trim().replace(/\/+$/, '') }).slice(0, 24);
}

function defaultPeerReputation() {
  return {
    valid_head_count: 0,
    invalid_head_count: 0,
    valid_block_count: 0,
    invalid_block_count: 0,
    valid_candidate_count: 0,
    invalid_candidate_count: 0,
    valid_failure_report_count: 0,
    false_failure_report_count: 0,
    candidate_error_streak: 0,
    trust_score: 1,
    can_query: true,
    can_broadcast: true,
    cooldown_until: null,
    cooldown_reason: null,
    updated_at: null,
  };
}

function scorePeerReputation(rep = {}) {
  const valid =
    Number(rep.valid_head_count || 0) +
    Number(rep.valid_block_count || 0) +
    Number(rep.valid_candidate_count || 0) +
    Number(rep.valid_failure_report_count || 0);
  const invalid =
    Number(rep.invalid_head_count || 0) +
    Number(rep.invalid_block_count || 0) +
    Number(rep.invalid_candidate_count || 0) +
    Number(rep.false_failure_report_count || 0);
  const trustScore = valid + invalid === 0 ? 1 : valid / Math.max(1, valid + invalid);
  const cooldownUntil = rep.cooldown_until ? Date.parse(rep.cooldown_until) : 0;
  const inCooldown = Number.isFinite(cooldownUntil) && cooldownUntil > Date.now();
  return {
    ...rep,
    trust_score: Number(trustScore.toFixed(4)),
    in_cooldown: inCooldown,
    can_query: trustScore >= 0.5 && !inCooldown,
    can_broadcast: trustScore >= 0.8 && !inCooldown,
  };
}

function normalizeBase1Peer(peer = {}, state = null) {
  const url = String(peer.url || '').trim().replace(/\/+$/, '');
  const id = peer.id || peerIdForUrl(url);
  const priorityRelay = Boolean(
    peer.priority_relay ?? peer.priorityRelay ?? peer.priority ?? peer.role === 'priority_relay',
  );
  const rep = scorePeerReputation({
    ...defaultPeerReputation(),
    ...(state?.peerReputation?.[id] || {}),
    ...(peer.reputation || {}),
  });
  if (state) state.peerReputation[id] = rep;
  return {
    ...peer,
    id,
    url,
    role: priorityRelay ? 'priority_relay' : peer.role || 'peer',
    priority_relay: priorityRelay,
    relay_tier: peer.relay_tier || peer.relayTier || (priorityRelay ? 'priority' : 'normal'),
    reputation: rep,
  };
}

function peerPropagationScore(peer = {}) {
  const reputation = peer.reputation || {};
  const relayBonus = peer.priority_relay ? 1000000 : 0;
  const trustScore = Math.round(Number(reputation.trust_score || 0) * 10000);
  const validScore =
    Number(reputation.valid_head_count || 0) * 10 +
    Number(reputation.valid_block_count || 0) * 20 +
    Number(reputation.valid_candidate_count || 0) * 15;
  const invalidPenalty =
    Number(reputation.invalid_head_count || 0) * 50 +
    Number(reputation.invalid_block_count || 0) * 80 +
    Number(reputation.invalid_candidate_count || 0) * 60 +
    Number(reputation.false_failure_report_count || 0) * 100;
  return relayBonus + trustScore + validScore - invalidPenalty;
}

function sortBase1PeersForPropagation(peers = []) {
  return peers
    .slice()
    .sort(
      (left, right) =>
        peerPropagationScore(right) - peerPropagationScore(left) ||
        String(left.url || '').localeCompare(String(right.url || '')),
    );
}

function updateBase1PeerReputation(state, { peerUrl = '', peerId = '', kind = 'head', valid = true, detail = {} } = {}) {
  const normalizedUrl = String(peerUrl || '').trim().replace(/\/+$/, '');
  const id = peerId || peerIdForUrl(normalizedUrl);
  state.peerReputation ||= {};
  const current = {
    ...defaultPeerReputation(),
    ...(state.peerReputation[id] || {}),
  };
  if (kind === 'block') {
    if (valid) current.valid_block_count += 1;
    else current.invalid_block_count += 1;
  } else if (kind === 'candidate') {
    if (valid) {
      current.valid_candidate_count += 1;
      current.candidate_error_streak = 0;
      current.cooldown_until = null;
      current.cooldown_reason = null;
    } else {
      current.invalid_candidate_count += 1;
      current.candidate_error_streak = Number(current.candidate_error_streak || 0) + 1;
      if (current.candidate_error_streak >= BASE1_PEER_CANDIDATE_ERROR_COOLDOWN_THRESHOLD) {
        current.cooldown_until = new Date(Date.now() + BASE1_PEER_CANDIDATE_ERROR_COOLDOWN_MS).toISOString();
        current.cooldown_reason = detail.code || detail.status || 'candidate_error_streak';
      }
    }
  } else if (kind === 'false_failure_report') {
    current.false_failure_report_count += 1;
  } else {
    if (valid) current.valid_head_count += 1;
    else current.invalid_head_count += 1;
  }
  current.updated_at = nowIso();
  current.last_detail = detail;
  const scored = scorePeerReputation(current);
  state.peerReputation[id] = scored;
  state.peers = (state.peers || []).map((peer) => {
    if (peer.id === id || peer.url === normalizedUrl) return normalizeBase1Peer({ ...peer, reputation: scored }, state);
    return peer;
  });
  return scored;
}

function compareBase1ProgressValues(left = {}, right = {}) {
  const leftLayer = Number(left.currentLayer ?? left.current_layer ?? left.layer_no ?? 0);
  const rightLayer = Number(right.currentLayer ?? right.current_layer ?? right.layer_no ?? 0);
  if (leftLayer !== rightLayer) return leftLayer > rightLayer ? 1 : -1;
  const leftStep = Number(left.currentStep ?? left.current_step ?? left.step_no ?? 0);
  const rightStep = Number(right.currentStep ?? right.current_step ?? right.step_no ?? 0);
  if (leftStep !== rightStep) return leftStep > rightStep ? 1 : -1;
  return 0;
}

function compareBase1StateHeads(leftState, rightState) {
  const progress = compareBase1ProgressValues(leftState, rightState);
  if (progress !== 0) return progress;
  return compareChainHeads(leftState?.chain, rightState?.chain);
}

function compareBase1HeadProofs(left = {}, right = {}) {
  const progress = compareBase1ProgressValues(left, right);
  if (progress !== 0) return progress;
  const leftWork = Number(left.cumulative_work_score || left.chain?.cumulative_work_score || 0);
  const rightWork = Number(right.cumulative_work_score || right.chain?.cumulative_work_score || 0);
  if (leftWork !== rightWork) return leftWork > rightWork ? 1 : -1;
  const leftHeight = Number(left.height || left.chain?.height || 0);
  const rightHeight = Number(right.height || right.chain?.height || 0);
  if (leftHeight !== rightHeight) return leftHeight > rightHeight ? 1 : -1;
  const leftHash = String(left.head_hash || left.chain?.head_hash || '');
  const rightHash = String(right.head_hash || right.chain?.head_hash || '');
  if (leftHash === rightHash) return 0;
  return leftHash < rightHash ? 1 : -1;
}

function rewardConfirmationRule(stepOrLayer) {
  const layerNo = Number(typeof stepOrLayer === 'object' ? stepOrLayer.layer_no : stepOrLayer) || 1;
  return REWARD_CONFIRMATION_RULES.reduce(
    (selected, rule) => (layerNo >= rule.min_layer ? rule : selected),
    REWARD_CONFIRMATION_RULES[0],
  );
}

function ensureAccount(state, address) {
  const key = String(address || 'unknown').trim() || 'unknown';
  state.accounts ||= {};
  if (!state.accounts[key]) {
    state.accounts[key] = {
      address: key,
      confirmed_balance: 0,
      pending_balance: 0,
      total_mined_pending: 0,
      total_mined_confirmed: 0,
      total_received: 0,
      total_sent: 0,
      total_submit_fees_burned: 0,
      total_reward_fees_burned: 0,
      nonce: 0,
      updated_at: nowIso(),
    };
  }
  return state.accounts[key];
}

function rewardWorkRequired(step, rule) {
  return Math.max(0, Math.round((step.scores?.final_score || 0) * (rule.work_multiplier || 0)));
}

function createPendingReward({ state, step, solver, rewardAmount, rewardTxHash, blockHeight, parentCumulativeWork, createdAt }) {
  const rule = rewardConfirmationRule(step);
  const reward = {
    id: sha256({
      type: 'mazex.base1.reward',
      chain_id: state.chainId,
      layer_no: step.layer_no,
      step_no: step.step_no,
      recipient: solver,
      reward_tx_hash: rewardTxHash,
      created_at: createdAt,
    }),
    type: 'solve_reward',
    status: 'pending',
    tier: rule.tier,
    recipient: solver,
    amount: rewardAmount,
    layer_no: step.layer_no,
    step_no: step.step_no,
    block_height: blockHeight,
    block_hash: null,
    reward_tx_hash: rewardTxHash,
    work_score: step.scores?.final_score || 0,
    confirmations: 0,
    confirmations_required: rule.confirmations,
    work_at_block: parentCumulativeWork + (step.scores?.final_score || 0),
    work_after: 0,
    work_required_after: rewardWorkRequired(step, rule),
    created_at: createdAt,
    confirmed_at: null,
  };
  state.rewardLedger.push(reward);
  const account = ensureAccount(state, solver);
  account.pending_balance += rewardAmount;
  account.total_mined_pending += rewardAmount;
  account.updated_at = createdAt;
  return reward;
}

function settleBase1Rewards(state, { targetHeight, targetCumulativeWork, createdAt = nowIso() } = {}) {
  const head = chainSummary(state.chain);
  const height = Number.isFinite(Number(targetHeight)) ? Number(targetHeight) : Number(head.height || 0);
  const cumulativeWork = Number.isFinite(Number(targetCumulativeWork))
    ? Number(targetCumulativeWork)
    : Number(head.cumulative_work_score || 0);
  const confirmed = [];
  for (const reward of state.rewardLedger || []) {
    if (reward.status !== 'pending') continue;
    reward.confirmations = Math.max(0, height - Number(reward.block_height || 0));
    reward.work_after = Math.max(0, cumulativeWork - Number(reward.work_at_block || 0));
    if (
      reward.confirmations >= Number(reward.confirmations_required || 0) &&
      reward.work_after >= Number(reward.work_required_after || 0)
    ) {
      reward.status = 'confirmed';
      reward.confirmed_at = createdAt;
      const account = ensureAccount(state, reward.recipient);
      account.pending_balance = Math.max(0, account.pending_balance - reward.amount);
      account.confirmed_balance += reward.amount;
      account.total_mined_pending = Math.max(0, account.total_mined_pending - reward.amount);
      account.total_mined_confirmed += reward.amount;
      account.updated_at = createdAt;
      confirmed.push(reward);
    }
  }
  return {
    confirmed,
    pending_count: (state.rewardLedger || []).filter((reward) => reward.status === 'pending').length,
    confirmed_count: (state.rewardLedger || []).filter((reward) => reward.status === 'confirmed').length,
  };
}

function publicAccount(state, address) {
  const account = ensureAccount(state, address);
  return {
    ...account,
    rewards: (state.rewardLedger || [])
      .filter((reward) => reward.recipient === account.address)
      .slice()
      .reverse(),
  };
}

function cloneJson(value) {
  return JSON.parse(JSON.stringify(value));
}

function snapshotBase1State(state = loadBase1State(), { includePrivate = true } = {}) {
  const normalized = normalizeBase1State(cloneJson(state));
  const snapshotState = includePrivate ? normalized : sanitizeBase1PublicState(normalized);
  return {
    exported_at: nowIso(),
    summary: chainSummary(normalized.chain),
    state: snapshotState,
    public_sanitized: !includePrivate,
  };
}

function prepareBase1SnapshotState(sourceState, { compactChain = false } = {}) {
  const snapshotState = cloneJson(sourceState);
  const blocks = snapshotState.chain?.blocks || [];
  const anchorBlock = blocks[blocks.length - 1] || null;
  if (!anchorBlock) throw new Error('Cannot create snapshot without an anchor block');
  if (compactChain) {
    snapshotState.chain = {
      ...(snapshotState.chain || {}),
      height: anchorBlock.height,
      head_hash: anchorBlock.block_hash,
      blocks: [cloneJson(anchorBlock)],
    };
  }
  return { snapshotState, anchorBlock };
}

function createBase1StateSnapshot({ state = loadBase1State(), height = null, compactChain = false } = {}) {
  const source = normalizeBase1State(cloneJson(state));
  const blocks = source.chain?.blocks || [];
  if (!blocks.length) throw new Error('Cannot snapshot an empty chain');
  let snapshotSource = source;
  if (height !== null && height !== undefined) {
    const targetHeight = Math.trunc(Number(height));
    const targetIndex = blocks.findIndex((block) => Number(block.height) === targetHeight);
    if (targetIndex < 0) throw new Error(`Cannot find snapshot height ${targetHeight}`);
    const replay = replayBase1Chain({
      state: {
        ...source,
        chain: {
          ...(source.chain || {}),
          blocks: blocks.slice(0, targetIndex + 1),
          height: blocks[targetIndex].height,
          head_hash: blocks[targetIndex].block_hash,
        },
      },
      includeState: true,
    });
    if (!replay.ok) throw new Error(`Cannot create snapshot at height ${targetHeight}: ${replay.code || replay.message}`);
    snapshotSource = replay.replay_state;
  }
  const { snapshotState, anchorBlock } = prepareBase1SnapshotState(snapshotSource, { compactChain });
  const stateRoot = computeStateRoot(snapshotState);
  const stateAfter = replayBlockStateAfter(snapshotState);
  const fullStateHash = sha256({
    type: 'mazex.base1.snapshot.full_state',
    state: snapshotState,
  });
  const anchor = {
    height: anchorBlock.height,
    block_hash: anchorBlock.block_hash,
    state_root: anchorBlock.state_root,
    state_after: anchorBlock.state_after,
    tx_root: anchorBlock.tx_root,
    work_score: anchorBlock.work_score,
    cumulative_work_score: anchorBlock.cumulative_work_score,
    previous_block_hash: anchorBlock.previous_block_hash,
  };
  const payload = {
    type: 'mazex.base1.state_snapshot',
    version: 'mazexchain-base1-snapshot-1.0',
    chain_id: snapshotState.chainId || DEFAULT_CHAIN_ID,
    genesis_hash: snapshotState.chain?.genesis_hash || snapshotState.genesisHash,
    anchor,
    state_root: stateRoot,
    state_after: stateAfter,
    full_state_hash: fullStateHash,
  };
  return {
    ...payload,
    created_at: nowIso(),
    state: snapshotState,
    snapshot_hash: sha256(payload),
  };
}

function genesisUnixMs(state = loadBase1State()) {
  const parsed = Date.parse(state.genesisCreatedAt || DEFAULT_GENESIS_CREATED_AT);
  return Number.isFinite(parsed) ? parsed : Date.parse(DEFAULT_GENESIS_CREATED_AT);
}

function makeBase1TimeProof(state = loadBase1State(), { observedUnixMs = Date.now(), source = 'local' } = {}) {
  const summary = chainSummary(state.chain);
  const genesisMs = genesisUnixMs(state);
  const observedMs = Math.max(genesisMs, Math.trunc(Number(observedUnixMs || Date.now())));
  const elapsedMs = Math.max(0, observedMs - genesisMs);
  const payload = {
    type: 'BASE1_TIME_PROOF',
    chain_id: state.chainId || DEFAULT_CHAIN_ID,
    genesis_hash: state.chain?.genesis_hash || state.genesisHash,
    genesis_utc: new Date(genesisMs).toISOString(),
    genesis_unix_ms: genesisMs,
    observed_utc: new Date(observedMs).toISOString(),
    observed_unix_ms: observedMs,
    mazex_elapsed_ms: elapsedMs,
    mazex_elapsed_seconds: Math.floor(elapsedMs / 1000),
    time_bucket_seconds: DEFAULT_TIME_BUCKET_SECONDS,
    time_bucket: Math.floor(elapsedMs / (DEFAULT_TIME_BUCKET_SECONDS * 1000)),
    latest_head_hash: summary.head_hash,
    latest_height: summary.height,
    current_layer: state.currentLayer,
    current_step: state.currentStep,
    source,
  };
  return {
    ...payload,
    proof_hash: sha256(payload),
  };
}

function getBase1TimeProof() {
  return makeBase1TimeProof(loadBase1State(), { source: 'local' });
}

function validateBase1TimeProofShape(proof, localState) {
  if (!proof || typeof proof !== 'object') return { ok: false, code: 'TIME_PROOF_REQUIRED' };
  if (proof.type !== 'BASE1_TIME_PROOF') return { ok: false, code: 'INVALID_TIME_PROOF_TYPE' };
  if (proof.chain_id !== (localState.chainId || DEFAULT_CHAIN_ID)) return { ok: false, code: 'TIME_CHAIN_ID_MISMATCH' };
  if (proof.genesis_hash !== localState.chain?.genesis_hash) return { ok: false, code: 'TIME_GENESIS_MISMATCH' };
  const expectedHash = sha256({
    type: proof.type,
    chain_id: proof.chain_id,
    genesis_hash: proof.genesis_hash,
    genesis_utc: proof.genesis_utc,
    genesis_unix_ms: proof.genesis_unix_ms,
    observed_utc: proof.observed_utc,
    observed_unix_ms: proof.observed_unix_ms,
    mazex_elapsed_ms: proof.mazex_elapsed_ms,
    mazex_elapsed_seconds: proof.mazex_elapsed_seconds,
    time_bucket_seconds: proof.time_bucket_seconds,
    time_bucket: proof.time_bucket,
    latest_head_hash: proof.latest_head_hash,
    latest_height: proof.latest_height,
    current_layer: proof.current_layer,
    current_step: proof.current_step,
    source: proof.source,
  });
  if (proof.proof_hash !== expectedHash) return { ok: false, code: 'TIME_PROOF_HASH_MISMATCH' };
  return { ok: true };
}

async function fetchBase1PeerTime(peer, { timeoutMs = 3000 } = {}) {
  const startedAtMs = Date.now();
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), Math.max(500, Number(timeoutMs || 3000)));
  try {
    const response = await fetch(`${peer.url}/api/base1/node/time`, {
      method: 'GET',
      signal: controller.signal,
      headers: { 'Content-Type': 'application/json' },
    });
    const endedAtMs = Date.now();
    const body = await response.json().catch(() => ({}));
    if (!response.ok || body.error) {
      return {
        ok: false,
        peer,
        code: 'PEER_TIME_FETCH_FAILED',
        status: response.status,
        response: body,
      };
    }
    return {
      ok: true,
      peer,
      proof: body.time || body,
      round_trip_ms: endedAtMs - startedAtMs,
      local_midpoint_ms: Math.floor((startedAtMs + endedAtMs) / 2),
    };
  } catch (error) {
    return {
      ok: false,
      peer,
      code: error.name === 'AbortError' ? 'PEER_TIME_TIMEOUT' : 'PEER_TIME_UNREACHABLE',
      message: error.message || 'peer time fetch failed',
    };
  } finally {
    clearTimeout(timer);
  }
}

function medianNumber(values) {
  const sorted = values.filter((value) => Number.isFinite(Number(value))).map(Number).sort((a, b) => a - b);
  if (!sorted.length) return 0;
  const middle = Math.floor(sorted.length / 2);
  if (sorted.length % 2) return sorted[middle];
  return Math.round((sorted[middle - 1] + sorted[middle]) / 2);
}

async function syncBase1NetworkTime({ maxPeers = DEFAULT_HEAD_QUERY_MAX_PEERS, timeoutMs = 3000 } = {}) {
  const state = loadBase1State();
  const localNow = Date.now();
  const peers = sortBase1PeersForPropagation(state.peers || [])
    .filter((peer) => peer.url && peer.status !== 'removed' && peer.reputation?.can_query !== false)
    .slice(0, Math.max(0, Math.min(64, Math.trunc(Number(maxPeers || DEFAULT_HEAD_QUERY_MAX_PEERS)))));
  const responses = await Promise.all(peers.map((peer) => fetchBase1PeerTime(peer, { timeoutMs })));
  const samples = [
    {
      source: 'local',
      ok: true,
      observed_unix_ms: localNow,
      offset_ms: 0,
      round_trip_ms: 0,
      time_bucket: makeBase1TimeProof(state, { observedUnixMs: localNow }).time_bucket,
    },
  ];
  const stateForUpdate = loadBase1State();
  for (const response of responses) {
    if (!response.ok) {
      pushBase1NetworkMessage(stateForUpdate, {
        direction: 'outbound',
        peer: response.peer.url,
        type: 'TIME_SYNC',
        status: response.code,
        detail: { round_trip_ms: response.round_trip_ms || null },
      });
      continue;
    }
    const validation = validateBase1TimeProofShape(response.proof, stateForUpdate);
    updateBase1PeerReputation(stateForUpdate, {
      peerUrl: response.peer.url,
      kind: 'head',
      valid: validation.ok,
      detail: { code: validation.code || 'TIME_OK' },
    });
    pushBase1NetworkMessage(stateForUpdate, {
      direction: 'outbound',
      peer: response.peer.url,
      type: 'TIME_SYNC',
      status: validation.ok ? 'valid_time' : validation.code,
      detail: {
        round_trip_ms: response.round_trip_ms || null,
        peer_time_bucket: response.proof?.time_bucket,
      },
    });
    if (!validation.ok) continue;
    const offsetMs = Number(response.proof.observed_unix_ms) - Number(response.local_midpoint_ms);
    samples.push({
      source: response.peer.url,
      ok: true,
      observed_unix_ms: response.proof.observed_unix_ms,
      offset_ms: offsetMs,
      round_trip_ms: response.round_trip_ms,
      time_bucket: response.proof.time_bucket,
    });
  }
  const calibratedOffsetMs = medianNumber(samples.map((sample) => sample.offset_ms));
  const calibratedUnixMs = Date.now() + calibratedOffsetMs;
  const timeProof = makeBase1TimeProof(stateForUpdate, {
    observedUnixMs: calibratedUnixMs,
    source: samples.length > 1 ? 'network_median_utc' : 'local_utc',
  });
  const syncRecord = {
    ok: true,
    mode: samples.length > 1 ? 'network_median_utc' : 'local_utc',
    calibrated_offset_ms: calibratedOffsetMs,
    sample_count: samples.length,
    peer_sample_count: Math.max(0, samples.length - 1),
    samples,
    time_proof: timeProof,
    synced_at: nowIso(),
  };
  stateForUpdate.timeSync = syncRecord;
  saveBase1State(stateForUpdate);
  return syncRecord;
}

function base1NodeInfo(state = loadBase1State()) {
  const summary = chainSummary(state.chain);
  const time = makeBase1TimeProof(state);
  return {
    node_id: sha256({
      type: 'mazex.base1.node',
      chain_id: state.chainId,
      genesis_hash: state.genesisHash,
    }),
    chain_id: state.chainId || DEFAULT_CHAIN_ID,
    version: state.version || BASE1_STATE_VERSION,
    algorithm: BASE1_ALGORITHM_VERSION,
    head_hash: summary.head_hash,
    height: summary.height,
    cumulative_work_score: summary.cumulative_work_score,
    current_layer: state.currentLayer,
    current_step: state.currentStep,
    mazex_time_bucket: time.time_bucket,
    observed_utc: time.observed_utc,
    peer_count: (state.peers || []).length,
  };
}

function registerBase1Peer({
  url,
  name = '',
  nodeId = '',
  priorityRelay = false,
  priority_relay = false,
  relayTier = '',
  relay_tier = '',
} = {}) {
  const state = loadBase1State();
  const normalizedUrl = String(url || '').trim().replace(/\/+$/, '');
  if (!normalizedUrl) return { ok: false, code: 'PEER_URL_REQUIRED', message: 'peer url is required' };
  const now = nowIso();
  const peerId = nodeId || peerIdForUrl(normalizedUrl);
  const isPriorityRelay = Boolean(priorityRelay || priority_relay);
  const peer = normalizeBase1Peer({
    id: peerId,
    name: String(name || normalizedUrl),
    url: normalizedUrl,
    role: isPriorityRelay ? 'priority_relay' : 'peer',
    priority_relay: isPriorityRelay,
    relay_tier: relayTier || relay_tier || (isPriorityRelay ? 'priority' : 'normal'),
    status: 'active',
    added_at: now,
    last_seen_at: now,
  }, state);
  const existingIndex = (state.peers || []).findIndex((item) => item.url === normalizedUrl || item.id === peer.id);
  if (existingIndex >= 0) state.peers[existingIndex] = { ...state.peers[existingIndex], ...peer, added_at: state.peers[existingIndex].added_at };
  else state.peers.push(peer);
  saveBase1State(state);
  return {
    ok: true,
    peer,
    peers: state.peers,
  };
}

function removeBase1Peer({ url, id } = {}) {
  const state = loadBase1State();
  const before = state.peers.length;
  state.peers = state.peers.filter((peer) => peer.url !== url && peer.id !== id);
  saveBase1State(state);
  return {
    ok: true,
    removed: before - state.peers.length,
    peers: state.peers,
  };
}

function pushBase1NetworkMessage(state, { direction, peer = null, type, status, detail = {} } = {}) {
  state.networkMessages ||= [];
  const createdAt = nowIso();
  const message = {
    id: sha256({
      type: 'mazex.base1.network_message',
      direction,
      peer,
      message_type: type,
      status,
      created_at: createdAt,
      detail,
    }),
    direction,
    peer,
    type,
    status,
    detail,
    created_at: createdAt,
  };
  state.networkMessages.push(message);
  if (state.networkMessages.length > 200) state.networkMessages = state.networkMessages.slice(-200);
  return message;
}

function recordBase1Witness(
  state,
  {
    witnessType = 'success',
    source = 'local',
    blockHash = '',
    headHash = '',
    layerNo = null,
    stepNo = null,
    stateRoot = '',
    reason = 'verified_head',
    detail = {},
  } = {},
) {
  state.witnesses ||= [];
  const validator = base1NodeInfo(state);
  const createdAt = nowIso();
  const payload = {
    type: 'BASE1_WITNESS',
    witness_type: witnessType,
    source,
    validator_node_id: validator.node_id,
    block_hash: blockHash || headHash,
    head_hash: headHash || blockHash,
    layer_no: layerNo,
    step_no: stepNo,
    state_root: stateRoot,
    reason,
  };
  const witness = {
    ...payload,
    detail,
    created_at: createdAt,
    witness_hash: sha256({
      ...payload,
      created_at: createdAt,
    }),
  };
  const duplicate = state.witnesses.find(
    (item) =>
      item.witness_type === witness.witness_type &&
      item.validator_node_id === witness.validator_node_id &&
      item.block_hash === witness.block_hash &&
      item.source === witness.source,
  );
  if (duplicate) return duplicate;
  state.witnesses.push(witness);
  if (state.witnesses.length > 2000) state.witnesses = state.witnesses.slice(-2000);
  return witness;
}

function getBase1WitnessStats({ limit = 100 } = {}) {
  const state = loadBase1State();
  const witnesses = (state.witnesses || []).slice(-Math.max(1, Math.trunc(Number(limit) || 100))).reverse();
  const byHead = {};
  const byValidator = {};
  for (const witness of state.witnesses || []) {
    const head = witness.head_hash || witness.block_hash || 'unknown';
    byHead[head] ||= {
      head_hash: head,
      success_count: 0,
      failure_count: 0,
      validators: new Set(),
    };
    if (witness.witness_type === 'success') byHead[head].success_count += 1;
    else byHead[head].failure_count += 1;
    byHead[head].validators.add(witness.validator_node_id);

    byValidator[witness.validator_node_id] ||= {
      validator_node_id: witness.validator_node_id,
      success_count: 0,
      failure_count: 0,
    };
    if (witness.witness_type === 'success') byValidator[witness.validator_node_id].success_count += 1;
    else byValidator[witness.validator_node_id].failure_count += 1;
  }
  return {
    witnesses,
    by_head: Object.values(byHead).map((item) => ({
      ...item,
      validators: Array.from(item.validators),
      validator_count: item.validators.size,
    })),
    by_validator: Object.values(byValidator),
  };
}

function recordBase1NetworkMessage({ direction, peer = null, type, status, detail = {} } = {}) {
  const state = loadBase1State();
  const message = pushBase1NetworkMessage(state, { direction, peer, type, status, detail });
  saveBase1State(state);
  return message;
}

function jsonByteLength(value) {
  return Buffer.byteLength(JSON.stringify(value || {}), 'utf8');
}

function solveCandidatePackageForSize({
  solver = 'network-solver',
  candidateStep = null,
  expectedHead = null,
  verifierOptions = {},
  networkTimeProof = null,
  signedPayloadHash = null,
  answerHash = null,
} = {}) {
  return {
    type: 'BASE1_SOLVE_CANDIDATE_PACKAGE',
    solver,
    candidateStep,
    expectedHead,
    verifierOptions,
    networkTimeProof,
    signedPayloadHash,
    answer_hash: answerHash,
  };
}

function answerSeenKey({ headHash = '', layerNo = null, stepNo = null, answerHash = '' } = {}) {
  if (!answerHash) return '';
  return [headHash || 'unknown-head', layerNo ?? 'unknown-layer', stepNo ?? 'unknown-step', answerHash].join(':');
}

function findSeenAnswerHash(state, key) {
  if (!key) return null;
  return (state.seenAnswerHashes || []).find((item) => item.key === key) || null;
}

function rememberSeenAnswerHash(state, entry = {}) {
  const key = entry.key || answerSeenKey(entry);
  if (!key) return null;
  state.seenAnswerHashes ||= [];
  const existing = findSeenAnswerHash(state, key);
  if (existing) {
    existing.seen_count = Number(existing.seen_count || 1) + 1;
    existing.last_seen_at = nowIso();
    return existing;
  }
  const row = {
    key,
    head_hash: entry.headHash || entry.head_hash || null,
    layer_no: entry.layerNo ?? entry.layer_no ?? null,
    step_no: entry.stepNo ?? entry.step_no ?? null,
    answer_hash: entry.answerHash || entry.answer_hash || null,
    behavior_hash: entry.behaviorHash || entry.behavior_hash || null,
    validation_id: entry.validationId || entry.validation_id || null,
    source: entry.source || 'unknown',
    seen_count: 1,
    first_seen_at: nowIso(),
    last_seen_at: nowIso(),
  };
  state.seenAnswerHashes.push(row);
  if (state.seenAnswerHashes.length > BASE1_SEEN_ANSWER_HASH_LIMIT) {
    state.seenAnswerHashes = state.seenAnswerHashes.slice(-BASE1_SEEN_ANSWER_HASH_LIMIT);
  }
  return row;
}

function getBase1NetworkStatus() {
  const state = loadBase1State();
  const peers = sortBase1PeersForPropagation(state.peers || []);
  return {
    node: base1NodeInfo(state),
    propagation: {
      priority_relay_enabled: true,
      priority_relay_count: peers.filter((peer) => peer.priority_relay).length,
      peer_count: peers.length,
      policy: 'priority_relays_first_then_reputation',
    },
    peers,
    reputation: state.peerReputation || {},
    messages: (state.networkMessages || []).slice(-50).reverse(),
  };
}

function getBase1FragmentRegistry(state = loadBase1State(), { limit = 50 } = {}) {
  return publicFragmentRegistry(state.fragmentRegistry || null, {
    currentHeight: state.chain?.height || 0,
    limit,
  });
}

function getBase1FragmentDownload(state = loadBase1State(), { limit = 1000, includePayload = true } = {}) {
  return fragmentDownloadPackage(state.fragmentRegistry || null, {
    currentHeight: state.chain?.height || 0,
    limit,
    includePayload,
  });
}

function getBase1FragmentRecord(state = loadBase1State(), { fragmentId = '', fragment_id = '' } = {}) {
  return fragmentRecordPackage(state.fragmentRegistry || null, {
    currentHeight: state.chain?.height || 0,
    fragmentId: fragment_id || fragmentId,
  });
}

function registerBase1Fragment({ fragment = {}, author = '', activationDelay = 10 } = {}) {
  const state = loadBase1State();
  if (!state.fragmentRegistry) state.fragmentRegistry = createDefaultFragmentRegistry();
  const currentHeight = chainSummary(state.chain).height;
  const createdAt = nowIso();
  const result = registerFragment(
    state.fragmentRegistry,
    {
      ...fragment,
      author: author || fragment.author || fragment.owner || 'fragment-author',
    },
    {
      currentHeight,
      activationDelay,
      createdAt,
    },
  );
  if (!result.ok) return result;
  state.fragmentRegistry = result.registry;
  const roots = computeFragmentRegistryRoots(state.fragmentRegistry, { currentHeight });
  const registerTx = createTransaction({
    type: 'BASE1_FRAGMENT_REGISTERED',
    nonce: 0,
    createdAt,
    payload: {
      fragment: result.record,
      fragment_id: result.record.fragment_id,
      content_hash: result.record.content_hash,
      activation_height: result.record.activation_height,
      registry_root: roots.registry_root,
      active_root: roots.active_root,
    },
  });
  const block = appendBlock(state, {
    producer: result.record.author || 'fragment-registrar',
    createdAt,
    transactions: [registerTx],
  });
  state.events.push({
    type: 'BASE1_FRAGMENT_REGISTERED',
    created_at: createdAt,
    fragment_id: result.record.fragment_id,
    content_hash: result.record.content_hash,
    kind: result.record.kind,
    name: result.record.name,
    activation_height: result.record.activation_height,
    registry_root: roots.registry_root,
    active_root: roots.active_root,
    block_hash: block.block_hash,
  });
  saveBase1State(state);
  return {
    ok: true,
    fragment: result.record,
    block,
    registry: getBase1FragmentRegistry(state),
  };
}

function upgradeBase1Fragment({ previousFragmentId = '', previous_fragment_id = '', fragment = {}, author = '', activationDelay = 10 } = {}) {
  const state = loadBase1State();
  if (!state.fragmentRegistry) state.fragmentRegistry = createDefaultFragmentRegistry();
  const currentHeight = chainSummary(state.chain).height;
  const createdAt = nowIso();
  const result = upgradeFragment(
    state.fragmentRegistry,
    {
      ...fragment,
      author: author || fragment.author || fragment.owner || 'fragment-author',
    },
    {
      previousFragmentId: previous_fragment_id || previousFragmentId,
      currentHeight,
      activationDelay,
      createdAt,
    },
  );
  if (!result.ok) return result;
  state.fragmentRegistry = result.registry;
  const roots = computeFragmentRegistryRoots(state.fragmentRegistry, { currentHeight });
  const upgradeTx = createTransaction({
    type: 'BASE1_FRAGMENT_UPGRADED',
    nonce: 0,
    createdAt,
    payload: {
      previous_fragment_id: result.previous.fragment_id,
      fragment: result.record,
      fragment_id: result.record.fragment_id,
      content_hash: result.record.content_hash,
      activation_height: result.record.activation_height,
      registry_root: roots.registry_root,
      active_root: roots.active_root,
    },
  });
  const block = appendBlock(state, {
    producer: result.record.author || 'fragment-upgrader',
    createdAt,
    transactions: [upgradeTx],
  });
  state.events.push({
    type: 'BASE1_FRAGMENT_UPGRADED',
    created_at: createdAt,
    previous_fragment_id: result.previous.fragment_id,
    fragment_id: result.record.fragment_id,
    content_hash: result.record.content_hash,
    kind: result.record.kind,
    name: result.record.name,
    version: result.record.version,
    activation_height: result.record.activation_height,
    registry_root: roots.registry_root,
    active_root: roots.active_root,
    block_hash: block.block_hash,
  });
  saveBase1State(state);
  return {
    ok: true,
    previous: result.previous,
    fragment: result.record,
    block,
    registry: getBase1FragmentRegistry(state),
  };
}

function quarantineBase1Fragment({ fragmentId = '', fragment_id = '', challenger = '', reasonCode = '', reason_code = '', evidence = {} } = {}) {
  const state = loadBase1State();
  if (!state.fragmentRegistry) state.fragmentRegistry = createDefaultFragmentRegistry();
  const currentHeight = chainSummary(state.chain).height;
  const createdAt = nowIso();
  const result = quarantineFragment(
    state.fragmentRegistry,
    {
      fragment_id: fragment_id || fragmentId,
      challenger: challenger || 'fragment-challenger',
      reason_code: reason_code || reasonCode,
      evidence,
      created_at: createdAt,
    },
    {
      currentHeight,
      createdAt,
    },
  );
  if (!result.ok) return result;
  state.fragmentRegistry = result.registry;
  const roots = computeFragmentRegistryRoots(state.fragmentRegistry, { currentHeight });
  const quarantineTx = createTransaction({
    type: 'BASE1_FRAGMENT_QUARANTINED',
    nonce: 0,
    createdAt,
    payload: {
      fragment_id: result.record.fragment_id,
      content_hash: result.record.content_hash,
      quarantine: result.quarantine,
      registry_root: roots.registry_root,
      active_root: roots.active_root,
    },
  });
  const block = appendBlock(state, {
    producer: result.quarantine.challenger || 'fragment-challenger',
    createdAt,
    transactions: [quarantineTx],
  });
  state.events.push({
    type: 'BASE1_FRAGMENT_QUARANTINED',
    created_at: createdAt,
    fragment_id: result.record.fragment_id,
    content_hash: result.record.content_hash,
    reason_code: result.quarantine.reason_code,
    proof_hash: result.quarantine.proof_hash,
    challenger: result.quarantine.challenger,
    registry_root: roots.registry_root,
    active_root: roots.active_root,
    block_hash: block.block_hash,
  });
  saveBase1State(state);
  return {
    ok: true,
    fragment: result.record,
    quarantine: result.quarantine,
    block,
    registry: getBase1FragmentRegistry(state),
  };
}

function getBase1HeadProof(state = loadBase1State()) {
  const normalized = normalizeBase1State(cloneJson(state));
  const summary = chainSummary(normalized.chain);
  const replay = replayBase1Chain({ state: normalized });
  const proof = {
    type: 'BASE1_HEAD_PROOF',
    chain_id: normalized.chainId || DEFAULT_CHAIN_ID,
    genesis_hash: normalized.chain?.genesis_hash || normalized.genesisHash,
    node: base1NodeInfo(normalized),
    head_hash: summary.head_hash,
    height: summary.height,
    cumulative_work_score: summary.cumulative_work_score,
    current_layer: normalized.currentLayer,
    current_step: normalized.currentStep,
    current_step_commit: normalized.currentStepCommitment?.step_commit || null,
    current_formula_hash: normalized.currentFormulaHash || null,
    current_fragment_registry_root: currentFragmentRegistryRoot(normalized),
    current_behavior_root: normalized.currentStepCommitment?.behavior_root || null,
    current_behavior_commitment_hash: normalized.currentStepCommitment?.behavior_commitment_hash || null,
    current_seed_source_hash: normalized.currentSeedSourceHash || null,
    state_root: summary.head_state_root,
    replay: {
      ok: replay.ok,
      checked_blocks: replay.checked_blocks || 0,
      current_layer: replay.current_layer || normalized.currentLayer,
      current_step: replay.current_step || normalized.currentStep,
      code: replay.code || null,
    },
    created_at: nowIso(),
  };
  return {
    ...proof,
    proof_hash: sha256(proof),
  };
}

function parseBase1SeedPeers(seedText = envOrConfigList('MAZEX_SEED_PEERS', NETWORK_CONFIG.seed_peers, [])) {
  const seeds = Array.isArray(seedText) ? seedText : String(seedText || '').split(',');
  return seeds
    .map((item) => item.trim().replace(/\/+$/, ''))
    .filter(Boolean)
    .map((url, index) => ({
      url,
      name: `seed-${index + 1}`,
    }));
}

function parseBase1PriorityRelays(relayText = PRIORITY_RELAYS) {
  const relays = Array.isArray(relayText) ? relayText : String(relayText || '').split(',');
  return relays
    .map((item) => item.trim().replace(/\/+$/, ''))
    .filter(Boolean)
    .map((url, index) => ({
      url,
      name: `priority-relay-${index + 1}`,
      priority_relay: true,
      relay_tier: 'priority',
    }));
}

function bootstrapBase1SeedPeers({ seeds = null } = {}) {
  const entries = Array.isArray(seeds) ? seeds : parseBase1SeedPeers(seeds);
  const added = [];
  for (const entry of entries) {
    const result = registerBase1Peer({
      url: typeof entry === 'string' ? entry : entry.url,
      name: typeof entry === 'string' ? '' : entry.name,
      nodeId: typeof entry === 'string' ? '' : entry.node_id || entry.nodeId || '',
      priorityRelay: typeof entry === 'string' ? false : Boolean(entry.priority_relay || entry.priorityRelay || entry.priority),
      relayTier: typeof entry === 'string' ? '' : entry.relay_tier || entry.relayTier || '',
    });
    if (result.ok) added.push(result.peer);
  }
  return {
    ok: true,
    added_count: added.length,
    peers: loadBase1State().peers || [],
  };
}

function bootstrapBase1PriorityRelays({ relays = null } = {}) {
  const entries = Array.isArray(relays) ? relays : parseBase1PriorityRelays(relays);
  const added = [];
  for (const entry of entries) {
    const result = registerBase1Peer({
      url: typeof entry === 'string' ? entry : entry.url,
      name: typeof entry === 'string' ? '' : entry.name,
      nodeId: typeof entry === 'string' ? '' : entry.node_id || entry.nodeId || '',
      priorityRelay: true,
      relayTier: typeof entry === 'string' ? 'priority' : entry.relay_tier || entry.relayTier || 'priority',
    });
    if (result.ok) added.push(result.peer);
  }
  const peers = loadBase1State().peers || [];
  return {
    ok: true,
    added_count: added.length,
    relays: peers.filter((peer) => peer.priority_relay),
    peers,
  };
}

function bootstrapBase1DefaultNetwork() {
  const seeds = bootstrapBase1SeedPeers();
  const priorityRelays = bootstrapBase1PriorityRelays();
  return {
    ok: true,
    seeds,
    priority_relays: priorityRelays,
  };
}

async function fetchBase1PeerHead(peer, { timeoutMs = 3000 } = {}) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), Math.max(500, Number(timeoutMs || 3000)));
  try {
    const response = await fetch(`${peer.url}/api/base1/node/head`, {
      method: 'GET',
      signal: controller.signal,
      headers: { 'Content-Type': 'application/json' },
    });
    const body = await response.json().catch(() => ({}));
    if (!response.ok || body.error) {
      return {
        ok: false,
        peer,
        code: 'PEER_HEAD_FETCH_FAILED',
        status: response.status,
        response: body,
      };
    }
    return {
      ok: true,
      peer,
      proof: body.head || body,
      sync_url: peer.url,
    };
  } catch (error) {
    return {
      ok: false,
      peer,
      code: error.name === 'AbortError' ? 'PEER_HEAD_TIMEOUT' : 'PEER_HEAD_UNREACHABLE',
      message: error.message || 'peer head fetch failed',
    };
  } finally {
    clearTimeout(timer);
  }
}

async function fetchBase1PeerHeadQuery(peer, { ttl = 0, maxPeers = 24, timeoutMs = 3000, queryId = '', visited = [] } = {}) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), Math.max(500, Number(timeoutMs || 3000)));
  try {
    const response = await fetch(`${peer.url}/api/base1/node/head-query`, {
      method: 'POST',
      signal: controller.signal,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ttl: Math.max(0, Math.trunc(Number(ttl || 0))),
        maxPeers,
        timeoutMs,
        queryId,
        visited: [...visited, peer.url],
      }),
    });
    const body = await response.json().catch(() => ({}));
    if (!response.ok || body.error) {
      return {
        ok: false,
        peer,
        code: 'PEER_HEAD_QUERY_FAILED',
        status: response.status,
        response: body,
      };
    }
    return {
      ok: true,
      peer,
      discovery: body,
      sync_url: body.best?.sync_url || peer.url,
    };
  } catch (error) {
    return {
      ok: false,
      peer,
      code: error.name === 'AbortError' ? 'PEER_HEAD_QUERY_TIMEOUT' : 'PEER_HEAD_QUERY_UNREACHABLE',
      message: error.message || 'peer head query failed',
    };
  } finally {
    clearTimeout(timer);
  }
}

function validateBase1HeadProofShape(proof, localState) {
  if (!proof || typeof proof !== 'object') return { ok: false, code: 'HEAD_PROOF_REQUIRED' };
  if (proof.type !== 'BASE1_HEAD_PROOF') return { ok: false, code: 'INVALID_HEAD_PROOF_TYPE' };
  if (proof.chain_id !== (localState.chainId || DEFAULT_CHAIN_ID)) return { ok: false, code: 'HEAD_CHAIN_ID_MISMATCH' };
  if (proof.genesis_hash !== localState.chain?.genesis_hash) return { ok: false, code: 'HEAD_GENESIS_MISMATCH' };
  if (!proof.head_hash || !proof.state_root) return { ok: false, code: 'HEAD_PROOF_INCOMPLETE' };
  if (!proof.replay?.ok) return { ok: false, code: proof.replay?.code || 'HEAD_REPLAY_NOT_OK' };
  return { ok: true };
}

async function discoverBase1Heads({
  ttl = DEFAULT_HEAD_QUERY_TTL,
  maxPeers = DEFAULT_HEAD_QUERY_MAX_PEERS,
  timeoutMs = 3000,
  queryId = '',
  visited = [],
} = {}) {
  const state = loadBase1State();
  const localHead = getBase1HeadProof(state);
  const seenUrls = new Set((Array.isArray(visited) ? visited : []).map((item) => String(item || '').trim().replace(/\/+$/, '')).filter(Boolean));
  const eligiblePeers = (state.peers || [])
    .map((peer) => normalizeBase1Peer(peer, state))
    .filter((peer) => peer.url && !seenUrls.has(peer.url) && peer.status !== 'removed' && peer.reputation?.can_query !== false)
    .sort((left, right) => peerPropagationScore(right) - peerPropagationScore(left))
    .slice(0, Math.max(1, Math.min(200, Math.trunc(Number(maxPeers || DEFAULT_HEAD_QUERY_MAX_PEERS)))));
  const createdAt = nowIso();
  const query = {
    type: 'BASE1_HEAD_QUERY',
    query_id:
      queryId ||
      sha256({
        type: 'mazex.base1.head_query',
        node_id: localHead.node.node_id,
        head_hash: localHead.head_hash,
        created_at: createdAt,
      }),
    requester_node_id: localHead.node.node_id,
    requester_head_hash: localHead.head_hash,
    requester_height: localHead.height,
    requester_layer: localHead.current_layer,
    requester_step: localHead.current_step,
    ttl: Math.max(0, Math.trunc(Number(ttl || 0))),
  };
  const responses = await Promise.all(
    eligiblePeers.map((peer) =>
      query.ttl > 0
        ? fetchBase1PeerHeadQuery(peer, {
            ttl: query.ttl - 1,
            maxPeers,
            timeoutMs,
            queryId: query.query_id,
            visited: [...seenUrls],
          })
        : fetchBase1PeerHead(peer, { timeoutMs }),
    ),
  );
  const stateForUpdate = loadBase1State();
  const candidates = [
    {
      source: 'local',
      peer: null,
      ok: true,
      valid: true,
      head: localHead,
    },
  ];
  for (const response of responses) {
    if (!response.ok) {
      pushBase1NetworkMessage(stateForUpdate, {
        direction: 'outbound',
        peer: response.peer.url,
        type: 'HEAD_QUERY',
        status: response.code,
        detail: { query_id: query.query_id },
      });
      continue;
    }
    const proofs = response.discovery
      ? (response.discovery.candidates || [])
          .filter((candidate) => candidate?.head)
          .map((candidate) => ({
            source: candidate.source === 'local' ? response.peer.url : `${response.peer.url} -> ${candidate.source}`,
            head: candidate.head,
            sync_url: candidate.sync_url || (candidate.source === 'local' ? response.peer.url : response.peer.url),
          }))
      : [{ source: response.peer.url, head: response.proof, sync_url: response.sync_url || response.peer.url }];
    const validProofs = proofs.filter((item) => validateBase1HeadProofShape(item.head, stateForUpdate).ok);
    const validation = validProofs.length
      ? { ok: true }
      : validateBase1HeadProofShape(proofs[0]?.head || null, stateForUpdate);
    updateBase1PeerReputation(stateForUpdate, {
      peerUrl: response.peer.url,
      kind: 'head',
      valid: validation.ok,
      detail: { query_id: query.query_id, code: validation.code || 'OK' },
    });
    pushBase1NetworkMessage(stateForUpdate, {
      direction: 'outbound',
      peer: response.peer.url,
      type: 'HEAD_QUERY',
      status: validation.ok ? 'valid_head' : validation.code,
      detail: {
        query_id: query.query_id,
        returned_candidates: proofs.length,
        valid_candidates: validProofs.length,
      },
    });
    for (const item of proofs) {
      const proofValidation = validateBase1HeadProofShape(item.head, stateForUpdate);
      candidates.push({
        source: item.source,
        peer: response.peer,
        ok: response.ok,
        valid: proofValidation.ok,
        validation: proofValidation,
        head: item.head,
        sync_url: item.sync_url,
      });
    }
  }
  saveBase1State(stateForUpdate);
  const validCandidates = candidates.filter((candidate) => candidate.valid);
  const best = validCandidates.reduce(
    (selected, candidate) => (compareBase1HeadProofs(candidate.head, selected.head) > 0 ? candidate : selected),
    candidates[0],
  );
  const stronger_than_local = compareBase1HeadProofs(best.head, localHead) > 0;
  return {
    ok: true,
    query,
    local: localHead,
    best,
    stronger_than_local,
    candidate_count: candidates.length,
    valid_candidate_count: validCandidates.length,
    candidates: candidates.sort((a, b) => compareBase1HeadProofs(b.head, a.head)),
    propagation: {
      policy: 'priority_relays_first_then_reputation',
      queried_peers: eligiblePeers.map((peer) => ({
        url: peer.url,
        name: peer.name,
        priority_relay: peer.priority_relay,
        trust_score: peer.reputation?.trust_score,
      })),
    },
  };
}

function normalizePositiveInteger(value, fallback = 0) {
  const numeric = Math.trunc(Number(value));
  return Number.isFinite(numeric) && numeric > 0 ? numeric : fallback;
}

function getBase1FeeSchedule() {
  return {
    currency: 'MAZEX',
    sample_fee: DEFAULT_SAMPLE_FEE,
    submit_fee: DEFAULT_SUBMIT_FEE,
    invalid_submit_fee: 0,
    submit_fee_min: DEFAULT_SUBMIT_FEE,
    invalid_submit_fee_min: 0,
    invalid_submit_fee_policy: 'not_charged_rejected_before_chain',
    transfer_fee: DEFAULT_TRANSFER_FEE,
    submit_fee_policy: 'dynamic_by_step_reward_deducted_from_success_reward',
    submit_fee_rate_min: BASE1_SUBMIT_FEE_MIN_RATE,
    submit_fee_rate_max: BASE1_SUBMIT_FEE_MAX_RATE,
    submit_fee_layer_scale: BASE1_SUBMIT_FEE_LAYER_SCALE,
    reward_policy: {
      type: 'capped_exponential_curve',
      floor: BASE1_REWARD_FLOOR,
      cap: BASE1_REWARD_CAP,
      curve_score: BASE1_REWARD_CURVE_SCORE,
    },
    transfer_fee_policy: 'burned_on_transfer',
  };
}

function submitFeeAmountForResult({ accepted = false, amount = null, step = null } = {}) {
  const fallback = accepted ? submitFeeForStep(step) : invalidSubmitFeeForStep(step);
  return Math.max(fallback, normalizePositiveInteger(amount, fallback));
}

function ensureSubmitFeeBalance(state, { address, amount }) {
  const account = ensureAccount(state, address);
  if (account.confirmed_balance < amount) {
    return {
      ok: false,
      code: 'INSUFFICIENT_CONFIRMED_BALANCE',
      message: 'Confirmed MAZEX balance is required before an answer can be uploaded',
      confirmed_balance: account.confirmed_balance,
      required: amount,
      account: publicAccount(state, address),
    };
  }
  return { ok: true, account };
}

function burnBase1SubmitFee({
  state,
  solver,
  amount,
  reason,
  feeSource = 'confirmed_balance',
  grossRewardAmount = null,
  netRewardAmount = null,
  createdAt,
  txNonce = 0,
  referenceTxHash = null,
  signedPayloadHash = null,
  layerNo = null,
  stepNo = null,
  validationId = null,
  answerHash = null,
  behaviorHash = null,
  parentBlockHash = null,
  parentHeight = null,
} = {}) {
  const feeAmount = Math.max(0, normalizePositiveInteger(amount, DEFAULT_SUBMIT_FEE));
  const account = ensureAccount(state, solver);
  if (feeSource !== 'solve_reward') {
    const balance = ensureSubmitFeeBalance(state, { address: solver, amount: feeAmount });
    if (!balance.ok) return balance;
  }
  const accountNonce = account.nonce + 1;
  const feeTx = createTransaction({
    type: 'BASE1_SUBMIT_FEE_BURNED',
    nonce: txNonce,
    createdAt,
    payload: {
      from: solver,
      amount: feeAmount,
      currency: 'MAZEX',
      reason,
      fee_source: feeSource,
      gross_reward_amount: grossRewardAmount,
      net_reward_amount: netRewardAmount,
      account_nonce: accountNonce,
      signed_payload_hash: signedPayloadHash,
      reference_tx_hash: referenceTxHash,
      layer_no: layerNo,
      step_no: stepNo,
      validation_id: validationId,
      answer_hash: answerHash,
      behavior_hash: behaviorHash,
      parent_block_hash: parentBlockHash,
      parent_height: parentHeight,
    },
  });

  if (feeSource !== 'solve_reward') account.confirmed_balance -= feeAmount;
  account.total_sent += feeAmount;
  account.total_submit_fees_burned = Number(account.total_submit_fees_burned || 0) + feeAmount;
  if (feeSource === 'solve_reward') {
    account.total_reward_fees_burned = Number(account.total_reward_fees_burned || 0) + feeAmount;
  }
  account.nonce = accountNonce;
  account.updated_at = createdAt;
  state.burnedFees += feeAmount;

  return {
    ok: true,
    amount: feeAmount,
    account_nonce: accountNonce,
    fee_tx: feeTx,
    account,
  };
}

function submitBase1Transfer({
  from,
  to,
  amount,
  fee = DEFAULT_TRANSFER_FEE,
  nonce,
  expectedHead = null,
  signedPayloadHash = null,
} = {}) {
  const state = loadBase1State();
  const headGuard = verifyBase1LatestHead(state, expectedHead);
  if (!headGuard.ok) {
    return {
      ok: false,
      code: headGuard.code,
      message: headGuard.message,
      mismatches: headGuard.mismatches,
      expected_head: headGuard.expected,
      latest_head: headGuard.latest,
    };
  }

  const senderAddress = String(from || '').trim();
  const receiverAddress = String(to || '').trim();
  const transferAmount = normalizePositiveInteger(amount);
  const transferFee = Math.max(0, normalizePositiveInteger(fee, DEFAULT_TRANSFER_FEE));
  const transferNonce = Math.trunc(Number(nonce || 0));
  if (!senderAddress || !receiverAddress) {
    return { ok: false, code: 'TRANSFER_ADDRESSES_REQUIRED', message: 'from and to are required' };
  }
  if (senderAddress === receiverAddress) {
    return { ok: false, code: 'SELF_TRANSFER_REJECTED', message: 'from and to must be different' };
  }
  if (transferAmount <= 0) {
    return { ok: false, code: 'INVALID_TRANSFER_AMOUNT', message: 'amount must be a positive integer' };
  }

  const sender = ensureAccount(state, senderAddress);
  const receiver = ensureAccount(state, receiverAddress);
  const expectedNonce = sender.nonce + 1;
  if (transferNonce !== expectedNonce) {
    return {
      ok: false,
      code: 'TRANSFER_NONCE_MISMATCH',
      message: 'Transfer nonce does not match account state',
      expected_nonce: expectedNonce,
      actual_nonce: transferNonce,
    };
  }

  const totalDebit = transferAmount + transferFee;
  if (sender.confirmed_balance < totalDebit) {
    return {
      ok: false,
      code: 'INSUFFICIENT_CONFIRMED_BALANCE',
      message: 'Only confirmed balance can be transferred',
      confirmed_balance: sender.confirmed_balance,
      required: totalDebit,
    };
  }

  const createdAt = nowIso();
  const transferTx = createTransaction({
    type: 'BASE1_TRANSFER',
    nonce: 0,
    createdAt,
    payload: {
      from: senderAddress,
      to: receiverAddress,
      amount: transferAmount,
      fee: transferFee,
      account_nonce: transferNonce,
      signed_payload_hash: signedPayloadHash,
      parent_block_hash: headGuard.latest.head_hash,
      parent_height: headGuard.latest.height,
    },
  });
  const feeTx = createTransaction({
    type: 'BASE1_FEE_BURNED',
    nonce: 1,
    createdAt,
    payload: {
      from: senderAddress,
      amount: transferFee,
      reason: 'transfer_fee',
      transfer_tx_hash: transferTx.tx_hash,
    },
  });

  sender.confirmed_balance -= totalDebit;
  sender.total_sent += totalDebit;
  sender.nonce = transferNonce;
  sender.updated_at = createdAt;
  receiver.confirmed_balance += transferAmount;
  receiver.total_received += transferAmount;
  receiver.updated_at = createdAt;
  state.burnedFees += transferFee;

  const transfer = {
    id: sha256({
      type: 'mazex.base1.transfer',
      tx_hash: transferTx.tx_hash,
      from: senderAddress,
      to: receiverAddress,
      amount: transferAmount,
      fee: transferFee,
      nonce: transferNonce,
    }),
    from: senderAddress,
    to: receiverAddress,
    amount: transferAmount,
    fee: transferFee,
    nonce: transferNonce,
    tx_hash: transferTx.tx_hash,
    signed_payload_hash: signedPayloadHash,
    block_height: Number(headGuard.latest.height || 0) + 1,
    block_hash: null,
    created_at: createdAt,
  };
  state.transfers.push(transfer);
  if (state.transfers.length > 1000) state.transfers = state.transfers.slice(-1000);

  const block = appendBlock(state, {
    producer: senderAddress,
    createdAt,
    transactions: [transferTx, feeTx],
  });
  transfer.block_hash = block.block_hash;
  state.events.push({
    type: 'BASE1_TRANSFER',
    created_at: createdAt,
    from: senderAddress,
    to: receiverAddress,
    amount: transferAmount,
    fee: transferFee,
    block_hash: block.block_hash,
  });
  saveBase1State(state);
  return {
    ok: true,
    transfer,
    block,
    from_account: publicAccount(state, senderAddress),
    to_account: publicAccount(state, receiverAddress),
    chain: chainSummary(state.chain),
  };
}

function getCurrentOfficialStep(state) {
  return state.officialStepsByKey?.[state.currentStepKey] || null;
}

function getCurrentSeedSource(state) {
  return state.seedSourcesByKey?.[state.currentStepKey] || null;
}

function getCurrentCommitment(state) {
  return state.commitmentsByKey?.[state.currentStepKey] || state.currentStepCommitment || null;
}

function currentFragmentRegistryRoot(state) {
  if (!state.fragmentRegistry) return state.currentStepCommitment?.fragment_registry_root || null;
  return computeFragmentRegistryRoots(state.fragmentRegistry, { currentHeight: state.chain?.height || 0 }).active_root;
}

function latestBase1HeadGuard(state = loadBase1State()) {
  const summary = chainSummary(state.chain);
  const time = makeBase1TimeProof(state);
  return {
    chain_id: state.chainId || DEFAULT_CHAIN_ID,
    head_hash: summary.head_hash,
    height: summary.height,
    cumulative_work_score: summary.cumulative_work_score,
    layer_no: state.currentLayer,
    step_no: state.currentStep,
    step_commit: state.currentStepCommitment?.step_commit || null,
    fragment_registry_root: currentFragmentRegistryRoot(state),
    behavior_root: state.currentStepCommitment?.behavior_root || null,
    behavior_commitment_hash: state.currentStepCommitment?.behavior_commitment_hash || null,
    genesis_utc: time.genesis_utc,
    mazex_time_bucket: time.time_bucket,
    observed_utc: time.observed_utc,
  };
}

function hasExpectedHeadGuard(expectedHead) {
  if (!expectedHead || typeof expectedHead !== 'object') return false;
  return [
    'chain_head_hash',
    'head_hash',
    'parent_block_hash',
    'chain_height',
    'height',
    'parent_height',
    'step_commit',
  ].some((key) => Object.prototype.hasOwnProperty.call(expectedHead, key));
}

function normalizeExpectedHead(expectedHead = {}) {
  return {
    chain_id: expectedHead.chain_id || expectedHead.chainId || DEFAULT_CHAIN_ID,
    head_hash: expectedHead.chain_head_hash || expectedHead.head_hash || expectedHead.parent_block_hash || null,
    height: expectedHead.chain_height ?? expectedHead.height ?? expectedHead.parent_height ?? null,
    cumulative_work_score:
      expectedHead.chain_cumulative_work_score ??
      expectedHead.cumulative_work_score ??
      expectedHead.parent_cumulative_work_score ??
      null,
    layer_no: expectedHead.layer_no ?? null,
    step_no: expectedHead.step_no ?? null,
    step_commit: expectedHead.step_commit || null,
  };
}

function sameNumber(left, right) {
  const a = Number(left);
  const b = Number(right);
  if (!Number.isFinite(a) || !Number.isFinite(b)) return true;
  return a === b;
}

function verifyBase1LatestHead(state, expectedHead) {
  const latest = latestBase1HeadGuard(state);
  if (!hasExpectedHeadGuard(expectedHead)) {
    return {
      ok: true,
      code: 'LATEST_HEAD_NOT_REQUIRED',
      latest,
    };
  }

  const expected = normalizeExpectedHead(expectedHead);
  const mismatches = [];
  if (expected.chain_id && expected.chain_id !== latest.chain_id) mismatches.push('chain_id');
  if (expected.head_hash && expected.head_hash !== latest.head_hash) mismatches.push('head_hash');
  if (expected.height !== null && !sameNumber(expected.height, latest.height)) mismatches.push('height');
  if (
    expected.cumulative_work_score !== null &&
    !sameNumber(expected.cumulative_work_score, latest.cumulative_work_score)
  ) {
    mismatches.push('cumulative_work_score');
  }
  if (expected.layer_no !== null && !sameNumber(expected.layer_no, latest.layer_no)) mismatches.push('layer_no');
  if (expected.step_no !== null && !sameNumber(expected.step_no, latest.step_no)) mismatches.push('step_no');
  if (expected.step_commit && expected.step_commit !== latest.step_commit) mismatches.push('step_commit');

  if (mismatches.length) {
    return {
      ok: false,
      code: 'STALE_PARENT_BLOCK',
      message: 'Submitted answer is not attached to the latest mazexchain head',
      mismatches,
      expected,
      latest,
    };
  }

  return {
    ok: true,
    code: 'LATEST_HEAD_CONFIRMED',
    expected,
    latest,
  };
}

function getCurrentBase1Public(state = loadBase1State()) {
  const step = getCurrentOfficialStep(state);
  const seedSource = getCurrentSeedSource(state);
  const commitment = getCurrentCommitment(state);
  if (!step || !seedSource || !commitment) {
    return {
      status: 'missing_current_step',
      chain: chainSummary(state.chain),
    };
  }
  return {
    status: 'active',
    current: publicStep(step, seedSource, commitment),
    generated_step_count: state.generatedStepKeys.length,
    solved_count: state.solvedSteps.length,
    latest_head_guard: latestBase1HeadGuard(state),
    time: makeBase1TimeProof(state),
    time_sync: state.timeSync || null,
    solve_queue: getBase1SolveQueueSummary(state),
    fee_schedule: getBase1FeeSchedule(),
    fragment_registry: getBase1FragmentRegistry(state),
    chain: chainSummary(state.chain),
  };
}

function numberOrZero(value) {
  const numeric = Number(value);
  return Number.isFinite(numeric) ? numeric : 0;
}

function clampCoordinate(value, gridSize) {
  const numeric = Math.trunc(numberOrZero(value));
  return Math.max(0, Math.min(gridSize - 1, numeric));
}

function sampleHistoryForStep(state, step) {
  return (state.samples || []).filter(
    (sample) => sample.layer_no === step.layer_no && sample.step_no === step.step_no,
  );
}

function contextForSample(state, step, { userId, x, y }) {
  const stepSamples = sampleHistoryForStep(state, step);
  const userSamples = stepSamples.filter((sample) => sample.user_id === userId);
  const lastUser = userSamples[userSamples.length - 1] || null;
  const lastGlobal = stepSamples[stepSamples.length - 1] || null;
  const N = step.grid_size;
  const nowMs = Date.now();
  const createdMs = Date.parse(state.createdAt || '');
  const elapsedSeconds = Number.isFinite(createdMs) ? Math.max(0, Math.floor((nowMs - createdMs) / 1000)) : 0;
  const lastX = clampCoordinate(lastUser?.x ?? 0, N);
  const lastY = clampCoordinate(lastUser?.y ?? 0, N);
  const lastU = clampCoordinate(lastUser?.u ?? 0, N);
  const lastV = clampCoordinate(lastUser?.v ?? 0, N);
  const lastDx = x - lastX;
  const lastDy = y - lastY;
  const historySum = (field) => stepSamples.reduce((sum, sample) => sum + numberOrZero(sample[field]), 0);
  const uniqueInputs = new Set(stepSamples.map((sample) => `${sample.x},${sample.y}`));
  const uniqueSamplers = new Set(stepSamples.map((sample) => sample.user_id));
  const previousSolved = (state.solvedSteps || [])[state.solvedSteps.length - 1] || null;
  const currentCommit = getCurrentCommitment(state);
  const chain = chainSummary(state.chain);
  const sampleIndex = stepSamples.length + 1;
  const userSampleIndex = userSamples.length + 1;
  const baseHashPayload = {
    type: 'mazex.base1.sample_context',
    layer_no: step.layer_no,
    step_no: step.step_no,
    x,
    y,
    user_id: userId,
    sample_index: sampleIndex,
    user_sample_index: userSampleIndex,
    chain_head: chain.head_hash,
    last_global: lastGlobal
      ? {
          x: lastGlobal.x,
          y: lastGlobal.y,
          u: lastGlobal.u,
          v: lastGlobal.v,
          user_id: lastGlobal.user_id,
        }
      : null,
  };

  return {
    click_count: sampleIndex,
    user_click_count: userSampleIndex,
    global_click_count: (state.samples || []).length + 1,
    last_x: lastX,
    last_y: lastY,
    last_u: lastU,
    last_v: lastV,
    last_dx: lastDx,
    last_dy: lastDy,
    last_distance: Math.floor(Math.sqrt(lastDx * lastDx + lastDy * lastDy)),
    elapsed_seconds: elapsedSeconds,
    time_bucket: Math.floor(elapsedSeconds / 30) % 256,
    time_mod: elapsedSeconds % N,

    history_hash: sha256({ ...baseHashPayload, kind: 'history' }),
    history_sum_x: historySum('x'),
    history_sum_y: historySum('y'),
    history_sum_u: historySum('u'),
    history_sum_v: historySum('v'),
    history_unique_count: uniqueInputs.size,
    history_repeat_count: Math.max(0, stepSamples.length - uniqueInputs.size),
    history_path_length: stepSamples.reduce((sum, sample, index, list) => {
      if (index === 0) return sum;
      const previous = list[index - 1];
      const dx = numberOrZero(sample.x) - numberOrZero(previous.x);
      const dy = numberOrZero(sample.y) - numberOrZero(previous.y);
      return sum + Math.floor(Math.sqrt(dx * dx + dy * dy));
    }, 0),

    previous_step_hash: currentCommit?.step_commit || state.currentFormulaHash,
    previous_solution_hash: previousSolved?.answer_hash || state.genesisHash,
    previous_block_hash: chain.head_hash || state.genesisHash,
    block_height: Math.max(0, Number(chain.height || 0)),
    chain_seed: state.currentSeedSourceHash || state.genesisHash,
    difficulty_epoch: Math.floor(Number(step.layer_no || 1) / 100),
    hash_click_state: sha256({ ...baseHashPayload, kind: 'click_state' }),
    hash_history_state: sha256({ ...baseHashPayload, kind: 'history_state', step_samples: stepSamples.length }),
    hash_chain_state: sha256({ ...baseHashPayload, kind: 'chain_state', chain }),
    nonlinear_jump: sha256({ ...baseHashPayload, kind: 'nonlinear_jump', elapsed_seconds: elapsedSeconds }),

    half_life_bucket: Math.floor(elapsedSeconds / 90) % 1024,
    decay_value: Math.floor((N * 1024) / (1 + Math.floor(elapsedSeconds / 90))) % N,
    cooldown_value: Math.max(0, N - (elapsedSeconds % N)),
    age_factor: elapsedSeconds % N,
    freshness_factor: Math.max(0, N - (elapsedSeconds % N)),
    cycle_phase: Math.floor(elapsedSeconds / 10) % 360,
    cycle_index: Math.floor(elapsedSeconds / 10) % 1024,
    pulse_state: Math.floor(elapsedSeconds / 15) % 2,
    wave_bucket: Math.floor((Math.sin(elapsedSeconds / 30) + 1) * N) % N,
    global_sample_count: state.samples.length + 1,
    global_submit_count: state.submissions.length,
    unique_sampler_count: uniqueSamplers.size,
    solver_count: Object.keys(state.leaderboard || {}).length,
    network_activity_bucket: (state.samples.length + state.submissions.length + uniqueSamplers.size) % N,
    multi_state_hash: sha256({
      ...baseHashPayload,
      kind: 'multi_state',
      solved_count: state.solvedSteps.length,
      submission_count: state.submissions.length,
    }),
  };
}

function sampleBase1Point({ userId = 'guest', user_id, x, y } = {}) {
  const state = loadBase1State();
  const step = getCurrentOfficialStep(state);
  if (!step) throw new Error('Current base1 Step is missing');
  const solver = String(userId || user_id || 'guest').trim() || 'guest';
  const px = clampCoordinate(x, step.grid_size);
  const py = clampCoordinate(y, step.grid_size);
  const context = contextForSample(state, step, { userId: solver, x: px, y: py });
  const output = evaluateBase1Step(step, px, py, context);
  const createdAt = nowIso();
  const sample = {
    id: sha256({
      type: 'mazex.base1.sample',
      layer_no: step.layer_no,
      step_no: step.step_no,
      user_id: solver,
      x: px,
      y: py,
      output,
      context_hash: sha256(context),
      created_at: createdAt,
      index: state.samples.length + 1,
    }),
    user_id: solver,
    layer_no: step.layer_no,
    step_no: step.step_no,
    x: px,
    y: py,
    u: output.u,
    v: output.v,
    context_hash: sha256(context),
    gas_cost: DEFAULT_SAMPLE_FEE,
    created_at: createdAt,
  };
  state.samples.push(sample);
  if (state.samples.length > 2000) state.samples = state.samples.slice(-2000);
  saveBase1State(state);
  return sample;
}

function batchBase1Sample({ userId = 'guest', user_id, count = 20 } = {}) {
  const total = Math.max(1, Math.min(200, Math.trunc(Number(count) || 20)));
  const state = loadBase1State();
  const step = getCurrentOfficialStep(state);
  if (!step) throw new Error('Current base1 Step is missing');
  const offset = state.samples.length;
  const samples = [];
  for (let index = 0; index < total; index += 1) {
    const cursor = offset + index + 1;
    samples.push(
      sampleBase1Point({
        userId: userId || user_id || 'guest',
        x: (cursor * 7 + step.layer_no * 3) % step.grid_size,
        y: (cursor * 11 + step.step_no * 5) % step.grid_size,
      }),
    );
  }
  return {
    count: samples.length,
    total_gas_cost: samples.reduce((sum, sample) => sum + sample.gas_cost, 0),
    samples,
  };
}

function nextPosition(step) {
  if (step.step_no < step.step_count) {
    return {
      layer_no: step.layer_no,
      step_no: step.step_no + 1,
    };
  }
  return {
    layer_no: step.layer_no + 1,
    step_no: 1,
  };
}

function rewardForStep(step) {
  const score = Math.max(0, Number(step?.scores?.final_score || 0));
  const curve = 1 - Math.exp(-score / BASE1_REWARD_CURVE_SCORE);
  return Math.max(1, Math.round(BASE1_REWARD_FLOOR + (BASE1_REWARD_CAP - BASE1_REWARD_FLOOR) * curve));
}

function submitFeeRateForStep(step) {
  const layerNo = Math.max(1, Number(step?.layer_no || 1));
  const curve = 1 - Math.exp(-layerNo / BASE1_SUBMIT_FEE_LAYER_SCALE);
  return BASE1_SUBMIT_FEE_MIN_RATE + (BASE1_SUBMIT_FEE_MAX_RATE - BASE1_SUBMIT_FEE_MIN_RATE) * curve;
}

function submitFeeForStep(step) {
  if (!step) return DEFAULT_SUBMIT_FEE;
  return Math.max(DEFAULT_SUBMIT_FEE, Math.round(rewardForStep(step) * submitFeeRateForStep(step)));
}

function invalidSubmitFeeForStep(step) {
  return 0;
}

function updateLeaderboard(state, solver, step, reward) {
  const profile = state.leaderboard[solver] || {
    solver,
    solves: 0,
    total_rewards: 0,
    total_score: 0,
    highest_layer: 0,
    highest_step: 0,
  };
  profile.solves += 1;
  profile.total_rewards += reward;
  profile.total_score += step.scores?.final_score || 0;
  profile.highest_layer = Math.max(profile.highest_layer, step.layer_no);
  profile.highest_step = Math.max(profile.highest_step, step.step_no);
  state.leaderboard[solver] = profile;
}

function makeCandidateFromOfficial(step) {
  return {
    algorithm: step.algorithm,
    trees: step.trees,
    operator_units: step.operator_units,
  };
}

function candidateHashForBase1(candidate = {}) {
  return sha256({
    algorithm: candidate.algorithm || BASE1_ALGORITHM_VERSION,
    trees: candidate.trees || {
      u: candidate.u_tree || null,
      v: candidate.v_tree || null,
    },
    operator_units: candidate.operator_units || null,
  });
}

function stepLockKey({ parentHeadHash, layerNo, stepNo }) {
  return `${String(parentHeadHash || 'genesis')}:${stepKey(layerNo, stepNo)}`;
}

function getBase1SolveQueueSummary(state = loadBase1State()) {
  const currentKey = stepKey(state.currentLayer, state.currentStep);
  const receipts = (state.solveReceipts || []).slice(-50).reverse();
  const activeLocks = Object.values(state.stepLocks || {})
    .filter((lock) => lock.status === 'pending' || lock.status === 'finalized')
    .slice(-20)
    .reverse();
  return {
    receipt_count: state.solveReceipts?.length || 0,
    current_step_receipt_count: (state.solveReceipts || []).filter(
      (receipt) => stepKey(receipt.layer_no, receipt.step_no) === currentKey,
    ).length,
    active_lock_count: activeLocks.length,
    confirm_window_ms: DEFAULT_SOLVE_CONFIRM_WINDOW_MS,
    latest_receipts: receipts,
    locks: activeLocks,
  };
}

function compactBase1SolveReceipt(receipt = {}) {
  return {
    type: receipt.type || 'BASE1_SOLVE_RECEIPT',
    chain_id: receipt.chain_id,
    receipt_order: receipt.receipt_order,
    step_order: receipt.step_order,
    layer_no: receipt.layer_no,
    step_no: receipt.step_no,
    solver: receipt.solver,
    parent_block_hash: receipt.parent_block_hash,
    parent_height: receipt.parent_height,
    parent_chain_time_bucket: receipt.parent_chain_time_bucket,
    network_time_bucket: receipt.network_time_bucket,
    received_utc: receipt.received_utc,
    candidate_hash: receipt.candidate_hash,
    answer_hash: receipt.answer_hash,
    behavior_hash: receipt.behavior_hash,
    validation_id: receipt.validation_id,
    confirmation_hash: receipt.confirmation_hash || null,
    confirmation_status: receipt.confirmation_status || null,
    confirmation_count: receipt.confirmation_count || 0,
    required_confirmation_count: receipt.required_confirmation_count || 0,
    order_proof_hash: receipt.order_proof_hash || null,
    receipt_hash: receipt.receipt_hash,
    status: receipt.status,
    reason: receipt.reason,
    confirm_until_utc: receipt.confirm_until_utc,
    created_at: receipt.created_at,
  };
}

function compactBase1StepLock(lock = {}) {
  return {
    type: lock.type || 'BASE1_STEP_LOCK',
    chain_id: lock.chain_id,
    layer_no: lock.layer_no,
    step_no: lock.step_no,
    parent_block_hash: lock.parent_block_hash,
    winning_receipt_hash: lock.winning_receipt_hash,
    solver: lock.solver,
    receipt_order: lock.receipt_order,
    step_order: lock.step_order,
    locked_utc: lock.locked_utc,
    confirm_until_utc: lock.confirm_until_utc,
    confirmation_hash: lock.confirmation_hash || null,
    lock_hash: lock.lock_hash,
    status: lock.status,
    created_at: lock.created_at,
    finalized_at: lock.finalized_at || null,
    solve_block_hash: lock.solve_block_hash || null,
    commit_block_hash: lock.commit_block_hash || null,
  };
}

function createBase1SolveReceipt({
  state,
  step,
  solver,
  candidate,
  verification,
  headGuard,
  networkTimeProof = null,
  networkConfirmation = null,
  status = 'received',
  reason = '',
} = {}) {
  state.solveReceipts ||= [];
  state.stepLocks ||= {};
  const parentHeadHash = headGuard.latest?.head_hash || headGuard.latest?.headHash || chainSummary(state.chain).head_hash;
  const networkTime = networkTimeProof || makeBase1TimeProof(state, { source: 'local_submit' });
  const sameParentStep = (state.solveReceipts || []).filter(
    (receipt) =>
      receipt.parent_block_hash === parentHeadHash &&
      Number(receipt.layer_no) === Number(step.layer_no) &&
      Number(receipt.step_no) === Number(step.step_no),
  );
  const receiptOrder = state.solveReceipts.length + 1;
  const stepOrder = sameParentStep.length + 1;
  const orderProof = {
    type: 'BASE1_ORDER_PROOF',
    chain_id: state.chainId || DEFAULT_CHAIN_ID,
    order_source_node_id: base1NodeInfo(state).node_id,
    parent_block_hash: parentHeadHash,
    parent_height: Number(headGuard.latest?.height || 0),
    layer_no: step.layer_no,
    step_no: step.step_no,
    receipt_order: receiptOrder,
    step_order: stepOrder,
    received_utc: networkTime.observed_utc,
    network_time_bucket: networkTime.time_bucket,
  };
  const payload = {
    type: 'BASE1_SOLVE_RECEIPT',
    chain_id: state.chainId || DEFAULT_CHAIN_ID,
    receipt_order: receiptOrder,
    step_order: stepOrder,
    layer_no: step.layer_no,
    step_no: step.step_no,
    solver,
    parent_block_hash: parentHeadHash,
    parent_height: Number(headGuard.latest?.height || 0),
    parent_chain_time_bucket: headGuard.latest?.mazex_time_bucket ?? null,
    network_time_bucket: networkTime.time_bucket,
    received_utc: networkTime.observed_utc,
    candidate_hash: candidateHashForBase1(candidate),
    answer_hash: verification?.answer_hash || null,
    behavior_hash: verification?.behavior_hash || null,
    validation_id: verification?.validation_id || null,
    confirmation_hash: networkConfirmation?.confirmation_hash || null,
    confirmation_status: networkConfirmation?.status || null,
    confirmation_count: networkConfirmation?.confirmation_count || 0,
    required_confirmation_count: networkConfirmation?.required_confirmation_count || 0,
    order_proof_hash: sha256(orderProof),
  };
  const receipt = {
    ...payload,
    status,
    reason,
    confirm_until_utc: new Date(
      Number(networkTime.observed_unix_ms || Date.now()) + DEFAULT_SOLVE_CONFIRM_WINDOW_MS,
    ).toISOString(),
    network_time: networkTime,
    network_confirmation: networkConfirmation || null,
    order_proof: orderProof,
    receipt_hash: sha256(payload),
    created_at: nowIso(),
  };
  state.solveReceipts.push(receipt);
  if (state.solveReceipts.length > 2000) state.solveReceipts = state.solveReceipts.slice(-2000);
  return receipt;
}

function lockBase1StepForReceipt({ state, step, receipt, headGuard }) {
  const parentHeadHash = receipt.parent_block_hash || headGuard.latest?.head_hash || chainSummary(state.chain).head_hash;
  const key = stepLockKey({ parentHeadHash, layerNo: step.layer_no, stepNo: step.step_no });
  const existing = state.stepLocks?.[key] || null;
  if (existing && existing.winning_receipt_hash !== receipt.receipt_hash) {
    receipt.status = receipt.status === 'accepted_first' ? 'late_valid' : receipt.status;
    receipt.reason = 'step_already_locked_by_earlier_valid_receipt';
    receipt.lock = existing;
    return { ok: false, locked: true, lock: existing, receipt };
  }
  const lockPayload = {
    type: 'BASE1_STEP_LOCK',
    chain_id: state.chainId || DEFAULT_CHAIN_ID,
    layer_no: step.layer_no,
    step_no: step.step_no,
    parent_block_hash: parentHeadHash,
    winning_receipt_hash: receipt.receipt_hash,
    solver: receipt.solver,
    receipt_order: receipt.receipt_order,
    step_order: receipt.step_order,
    locked_utc: receipt.received_utc,
    confirm_until_utc: receipt.confirm_until_utc,
    confirmation_hash: receipt.confirmation_hash || null,
  };
  const lock = {
    ...lockPayload,
    status: 'pending',
    lock_hash: sha256(lockPayload),
    created_at: nowIso(),
  };
  state.stepLocks[key] = lock;
  receipt.status = 'accepted_first';
  receipt.reason = 'first_valid_receipt_locked_step';
  receipt.lock = lock;
  return { ok: true, locked: true, lock, receipt };
}

function finalizeBase1StepLock({ state, receipt, solveBlock, commitBlock }) {
  const lockKey = Object.keys(state.stepLocks || {}).find(
    (key) => state.stepLocks[key]?.winning_receipt_hash === receipt.receipt_hash,
  );
  if (!lockKey) return null;
  const lock = state.stepLocks[lockKey];
  lock.status = 'finalized';
  lock.solve_block_hash = solveBlock?.block_hash || null;
  lock.commit_block_hash = commitBlock?.block_hash || null;
  lock.finalized_at = nowIso();
  receipt.status = 'finalized_first_valid';
  receipt.solve_block_hash = solveBlock?.block_hash || null;
  receipt.commit_block_hash = commitBlock?.block_hash || null;
  return lock;
}

function validateBase1SolveCandidatePackage({
  state = loadBase1State(),
  solver = 'network-solver',
  candidateStep = null,
  expectedHead = null,
  verifierOptions = {},
  requireExpectedHead = true,
} = {}) {
  const step = getCurrentOfficialStep(state);
  const seedSource = getCurrentSeedSource(state);
  const commitment = getCurrentCommitment(state);
  if (!step || !seedSource || !commitment) {
    return { ok: false, code: 'CURRENT_STEP_MISSING', message: 'Current base1 Step is missing' };
  }
  if (requireExpectedHead && !hasExpectedHeadGuard(expectedHead)) {
    return {
      ok: false,
      code: 'EXPECTED_HEAD_REQUIRED',
      message: 'Solve candidate must bind the latest parent head before network verification',
      latest_head: latestBase1HeadGuard(state),
    };
  }

  const headGuard = verifyBase1LatestHead(state, expectedHead);
  if (!headGuard.ok) {
    return {
      ok: false,
      code: headGuard.code,
      message: headGuard.message,
      mismatches: headGuard.mismatches,
      expected_head: headGuard.expected,
      latest_head: headGuard.latest,
    };
  }

  const candidate = candidateStep || makeCandidateFromOfficial(step);
  const verification = verifyCandidateStep({
    officialStep: step,
    candidateStep: candidate,
    options: verifierOptions,
  });
  return {
    ok: Boolean(verification.ok),
    code: verification.ok ? 'SOLVE_CANDIDATE_VALID' : verification.code || 'SOLVE_CANDIDATE_REJECTED',
    message: verification.ok ? 'Solve candidate passed deterministic verifier' : verification.message || 'Candidate rejected',
    solver,
    layer_no: step.layer_no,
    step_no: step.step_no,
    candidate_hash: candidateHashForBase1(candidate),
    answer_hash: verification.answer_hash || null,
    behavior_hash: verification.behavior_hash || null,
    validation_id: verification.validation_id || null,
    formula_hash: step.formula_hash,
    seed_source_hash: seedSource.source_hash,
    step_commit: commitment.step_commit,
    latest_head: headGuard.latest,
    verification,
  };
}

function receiveBase1SolveCandidatePackage({
  solver = 'network-solver',
  candidateStep = null,
  expectedHead = null,
  verifierOptions = {},
  networkTimeProof = null,
  signedPayloadHash = null,
  answerHash = null,
  source = 'candidate-peer',
} = {}) {
  const state = loadBase1State();
  const packageBytes = jsonByteLength(
    solveCandidatePackageForSize({
      solver,
      candidateStep,
      expectedHead,
      verifierOptions,
      networkTimeProof,
      signedPayloadHash,
      answerHash,
    }),
  );
  if (packageBytes > BASE1_MAX_CANDIDATE_PACKAGE_BYTES) {
    updateBase1PeerReputation(state, {
      peerUrl: source,
      kind: 'candidate',
      valid: false,
      detail: {
        code: 'CANDIDATE_PACKAGE_TOO_LARGE',
        package_bytes: packageBytes,
        max_bytes: BASE1_MAX_CANDIDATE_PACKAGE_BYTES,
      },
    });
    pushBase1NetworkMessage(state, {
      direction: 'inbound',
      peer: source,
      type: 'SOLVE_CANDIDATE',
      status: 'candidate_package_too_large',
      detail: {
        solver,
        package_bytes: packageBytes,
        max_bytes: BASE1_MAX_CANDIDATE_PACKAGE_BYTES,
      },
    });
    saveBase1State(state);
    return {
      ok: false,
      accepted: false,
      code: 'CANDIDATE_PACKAGE_TOO_LARGE',
      message: 'Solve candidate package exceeds the network safety size limit',
      package_bytes: packageBytes,
      max_bytes: BASE1_MAX_CANDIDATE_PACKAGE_BYTES,
      latest_head: latestBase1HeadGuard(state),
    };
  }
  const claimedAnswerHash = answerHash ? String(answerHash) : '';
  const duplicateKey = answerSeenKey({
    headHash: expectedHead?.head_hash || expectedHead?.chain_head_hash || '',
    layerNo: expectedHead?.layer_no || state.currentLayer,
    stepNo: expectedHead?.step_no || state.currentStep,
    answerHash: claimedAnswerHash,
  });
  const duplicate = claimedAnswerHash ? findSeenAnswerHash(state, duplicateKey) : null;
  if (duplicate) {
    duplicate.seen_count = Number(duplicate.seen_count || 1) + 1;
    duplicate.last_seen_at = nowIso();
    pushBase1NetworkMessage(state, {
      direction: 'inbound',
      peer: source,
      type: 'SOLVE_CANDIDATE',
      status: 'duplicate_answer_hash_dropped',
      detail: {
        solver,
        answer_hash: claimedAnswerHash,
        duplicate_key: duplicateKey,
        seen_count: duplicate.seen_count,
      },
    });
    saveBase1State(state);
    return {
      ok: true,
      accepted: true,
      duplicate: true,
      code: 'DUPLICATE_ANSWER_HASH_DROPPED',
      message: 'Duplicate answer_hash already verified for this head and Step; package was not re-verified',
      confirmation: {
        validator_node_id: base1NodeInfo(state).node_id,
        source,
        witness_hash: duplicate.witness_hash || null,
        candidate_hash: duplicate.candidate_hash || null,
        answer_hash: claimedAnswerHash,
        behavior_hash: duplicate.behavior_hash || null,
        validation_id: duplicate.validation_id || null,
        layer_no: duplicate.layer_no ?? state.currentLayer,
        step_no: duplicate.step_no ?? state.currentStep,
        confirmed_at: duplicate.last_seen_at,
        duplicate: true,
      },
      latest_head: latestBase1HeadGuard(state),
    };
  }
  const result = validateBase1SolveCandidatePackage({
    state,
    solver,
    candidateStep,
    expectedHead,
    verifierOptions,
    requireExpectedHead: true,
  });
  const witness = recordBase1Witness(state, {
    witnessType: result.ok ? 'success' : 'failure',
    source,
    blockHash: result.latest_head?.head_hash || '',
    headHash: result.latest_head?.head_hash || '',
    layerNo: result.layer_no ?? state.currentLayer,
    stepNo: result.step_no ?? state.currentStep,
    stateRoot: chainSummary(state.chain).head_state_root,
    reason: result.ok ? 'solve_candidate_verified_by_peer' : result.code || 'solve_candidate_rejected_by_peer',
    detail: {
      solver,
      candidate_hash: result.candidate_hash || null,
      answer_hash: result.answer_hash || null,
      behavior_hash: result.behavior_hash || null,
      validation_id: result.validation_id || null,
      network_time_bucket: networkTimeProof?.time_bucket ?? null,
      message: result.message,
    },
  });
  updateBase1PeerReputation(state, {
    peerUrl: source,
    kind: 'candidate',
    valid: result.ok,
    detail: {
      code: result.code,
      witness_hash: witness.witness_hash,
      candidate_hash: result.candidate_hash || null,
    },
  });
  pushBase1NetworkMessage(state, {
    direction: 'inbound',
    peer: source,
    type: 'SOLVE_CANDIDATE',
    status: result.ok ? 'candidate_valid' : result.code || 'candidate_invalid',
    detail: {
      solver,
      witness_hash: witness.witness_hash,
      candidate_hash: result.candidate_hash || null,
      layer_no: result.layer_no ?? state.currentLayer,
      step_no: result.step_no ?? state.currentStep,
    },
  });
  if (result.ok) {
    const seen = rememberSeenAnswerHash(state, {
      headHash: result.latest_head?.head_hash || '',
      layerNo: result.layer_no,
      stepNo: result.step_no,
      answerHash: result.answer_hash,
      behaviorHash: result.behavior_hash,
      validationId: result.validation_id,
      source,
    });
    if (seen) {
      seen.witness_hash = witness.witness_hash;
      seen.candidate_hash = result.candidate_hash || null;
    }
  }
  saveBase1State(state);
  return {
    ok: result.ok,
    accepted: result.ok,
    code: result.code,
    message: result.message,
    confirmation: {
      validator_node_id: base1NodeInfo(state).node_id,
      source,
      witness_hash: witness.witness_hash,
      candidate_hash: result.candidate_hash || null,
      answer_hash: result.answer_hash || null,
      behavior_hash: result.behavior_hash || null,
      validation_id: result.validation_id || null,
      layer_no: result.layer_no ?? state.currentLayer,
      step_no: result.step_no ?? state.currentStep,
      confirmed_at: witness.created_at,
    },
    verification: {
      ok: result.verification?.ok || false,
      code: result.verification?.code || result.code,
      stage: result.verification?.stage || null,
      validation_id: result.validation_id || null,
      answer_hash: result.answer_hash || null,
      behavior_hash: result.behavior_hash || null,
    },
    latest_head: result.latest_head || latestBase1HeadGuard(state),
  };
}

async function postBase1SolveCandidateToPeer(peer, payload, { timeoutMs = 3000 } = {}) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), Math.max(500, Number(timeoutMs || 3000)));
  try {
    const response = await fetch(`${peer.url}/api/base1/node/solve-candidate`, {
      method: 'POST',
      signal: controller.signal,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
    const body = await response.json().catch(() => ({}));
    return {
      peer,
      ok: response.ok && body.error == null,
      status: response.status,
      response: body,
    };
  } catch (error) {
    return {
      peer,
      ok: false,
      status: 0,
      error: error.message || 'solve candidate broadcast failed',
      code: error.name === 'AbortError' ? 'SOLVE_CANDIDATE_TIMEOUT' : 'SOLVE_CANDIDATE_UNREACHABLE',
    };
  } finally {
    clearTimeout(timer);
  }
}

async function broadcastBase1SolveCandidate({
  solver = 'network-solver',
  candidateStep = null,
  expectedHead = null,
  verifierOptions = {},
  networkTimeProof = null,
  signedPayloadHash = null,
  maxPeers = DEFAULT_HEAD_QUERY_MAX_PEERS,
  timeoutMs = 3000,
} = {}) {
  const state = loadBase1State();
  const sourceNode = base1NodeInfo(state);
  const localValidation = validateBase1SolveCandidatePackage({
    state,
    solver,
    candidateStep,
    expectedHead,
    verifierOptions,
    requireExpectedHead: true,
  });
  const startedAt = nowIso();
  if (!localValidation.ok) {
    return {
      ok: false,
      status: 'local_rejected',
      code: localValidation.code,
      message: localValidation.message,
      local_validation: localValidation,
      confirmation_count: 0,
      required_confirmation_count: 1,
      peer_results: [],
      started_at: startedAt,
      ended_at: nowIso(),
    };
  }

  const payload = {
    type: 'BASE1_SOLVE_CANDIDATE_PACKAGE',
    source: sourceNode.node_id,
    solver,
    candidateStep,
    expectedHead,
    verifierOptions,
    networkTimeProof,
    signedPayloadHash,
    candidate_hash: localValidation.candidate_hash,
    answer_hash: localValidation.answer_hash,
    behavior_hash: localValidation.behavior_hash,
    validation_id: localValidation.validation_id,
    created_at: startedAt,
  };
  const packageBytes = jsonByteLength(payload);
  if (packageBytes > BASE1_MAX_CANDIDATE_PACKAGE_BYTES) {
    return {
      ok: false,
      status: 'local_rejected',
      code: 'CANDIDATE_PACKAGE_TOO_LARGE',
      message: 'Local solve candidate package exceeds the network safety size limit and will not be broadcast',
      package_bytes: packageBytes,
      max_bytes: BASE1_MAX_CANDIDATE_PACKAGE_BYTES,
      local_validation: localValidation,
      confirmation_count: 0,
      required_confirmation_count: 1,
      peer_results: [],
      started_at: startedAt,
      ended_at: nowIso(),
    };
  }
  const peers = sortBase1PeersForPropagation(state.peers || [])
    .filter(
      (peer) =>
        peer.url &&
        peer.status !== 'removed' &&
        peer.reputation?.can_query !== false &&
        peer.reputation?.can_broadcast !== false,
    )
    .slice(0, Math.max(0, Math.min(128, Math.trunc(Number(maxPeers || DEFAULT_HEAD_QUERY_MAX_PEERS)))));
  const responses = await Promise.all(
    peers.map((peer) => postBase1SolveCandidateToPeer(peer, payload, { timeoutMs })),
  );
  const stateAfter = loadBase1State();
  const peerResults = [];
  for (const result of responses) {
    const accepted = Boolean(result.ok && result.response?.accepted);
    const online = Boolean(result.ok || result.status > 0);
    peerResults.push({
      peer: result.peer.url,
      priority_relay: Boolean(result.peer.priority_relay),
      online,
      accepted,
      status: result.response?.code || result.code || (accepted ? 'accepted' : result.response?.message || 'failed'),
      witness_hash: result.response?.confirmation?.witness_hash || null,
    });
    updateBase1PeerReputation(stateAfter, {
      peerUrl: result.peer.url,
      kind: 'candidate',
      valid: accepted,
      detail: {
        status: result.response?.code || result.code || result.status,
        witness_hash: result.response?.confirmation?.witness_hash || null,
      },
    });
    pushBase1NetworkMessage(stateAfter, {
      direction: 'outbound',
      peer: result.peer.url,
      type: 'SOLVE_CANDIDATE_BROADCAST',
      status: accepted ? 'confirmed' : result.response?.code || result.code || 'failed',
      detail: {
        candidate_hash: localValidation.candidate_hash,
        witness_hash: result.response?.confirmation?.witness_hash || null,
        status: result.status,
      },
    });
  }
  const onlinePeerCount = peerResults.filter((item) => item.online).length;
  const acceptedPeerCount = peerResults.filter((item) => item.accepted).length;
  const onlineValidatorCount = 1 + onlinePeerCount;
  const requiredConfirmationCount = Math.max(1, Math.ceil((onlineValidatorCount * 2) / 3));
  const confirmationCount = 1 + acceptedPeerCount;
  const endedAt = nowIso();
  const confirmationPayload = {
    type: 'BASE1_SOLVE_NETWORK_CONFIRMATION',
    chain_id: stateAfter.chainId || DEFAULT_CHAIN_ID,
    source_node_id: sourceNode.node_id,
    solver,
    layer_no: localValidation.layer_no,
    step_no: localValidation.step_no,
    parent_block_hash: localValidation.latest_head?.head_hash || null,
    candidate_hash: localValidation.candidate_hash,
    answer_hash: localValidation.answer_hash,
    behavior_hash: localValidation.behavior_hash,
    validation_id: localValidation.validation_id,
    confirmation_count: confirmationCount,
    required_confirmation_count: requiredConfirmationCount,
    online_validator_count: onlineValidatorCount,
    peer_count: peers.length,
    accepted_peer_count: acceptedPeerCount,
    started_at: startedAt,
    ended_at: endedAt,
  };
  const confirmed = confirmationCount >= requiredConfirmationCount;
  const confirmation = {
    ...confirmationPayload,
    ok: confirmed,
    status: confirmed ? 'confirmed' : 'insufficient_confirmations',
    confirm_window_ms: DEFAULT_SOLVE_CONFIRM_WINDOW_MS,
    local_confirmation: {
      validator_node_id: sourceNode.node_id,
      accepted: true,
      validation_id: localValidation.validation_id,
    },
    peer_results: peerResults,
    confirmation_hash: sha256(confirmationPayload),
  };
  stateAfter.lastSolveConfirmation = confirmation;
  saveBase1State(stateAfter);
  return confirmation;
}

function createNextStepFromSolved({ state, previousStep, solved, solveBlock }) {
  const next = nextPosition(previousStep);
  const baseSeedSource = deriveNextStepSeedSource({
    chainId: state.chainId,
    seasonSeed: state.seasonSeed,
    algorithm: BASE1_ALGORITHM_VERSION,
    previousStep,
    previousResult: solved,
    previousBlockHash: solveBlock.block_hash,
    nextLayerNo: next.layer_no,
    nextStepNo: next.step_no,
  });
  const generated = generateFragmentBoundStep({
    layerNo: next.layer_no,
    stepNo: next.step_no,
    seedSource: baseSeedSource,
    fragmentRegistry: state.fragmentRegistry,
    currentHeight: state.chain?.height || 0,
  });
  const { step, seedSource, fragmentSelection } = generated;
  const commitment = makeStepCommitment(step, seedSource, currentFragmentRegistryRoot(state), fragmentSelection);
  const key = stepKey(step.layer_no, step.step_no);
  state.currentLayer = step.layer_no;
  state.currentStep = step.step_no;
  state.gridSize = step.grid_size;
  state.currentStepKey = key;
  state.currentFormulaHash = step.formula_hash;
  state.currentSeedSourceHash = seedSource.source_hash;
  state.currentStepCommitment = commitment;
  state.officialStepsByKey[key] = step;
  state.seedSourcesByKey[key] = seedSource;
  state.commitmentsByKey[key] = commitment;
  state.generatedStepKeys.push(key);
  solved.next_seed_source_hash = seedSource.source_hash;
  solved.next_formula_hash = step.formula_hash;
  solved.next_fragment_registry_root = commitment.fragment_registry_root;
  solved.next_fragment_selection_hash = commitment.fragment_selection?.selection_hash || null;
  solved.next_fragment_generation_profile_hash =
    commitment.fragment_selection?.generation_profile_hash || step.fragment_generation_profile_hash || null;
  solved.next_behavior_root = commitment.behavior_root;
  solved.next_behavior_commitment_hash = commitment.behavior_commitment_hash;
  return { next, seedSource, step, commitment, key };
}

function submitBase1Candidate({
  solver = 'local-solver',
  candidateStep,
  expectedHead = null,
  verifierOptions = {},
  networkTimeProof = null,
  networkConfirmation = null,
  requireExpectedHead = false,
  chargeFee = true,
  submitFee = null,
  signedPayloadHash = null,
} = {}) {
  const state = loadBase1State();
  const step = getCurrentOfficialStep(state);
  const seedSource = getCurrentSeedSource(state);
  const commitment = getCurrentCommitment(state);
  if (!step || !seedSource || !commitment) {
    throw new Error('Current base1 Step is missing');
  }
  const currentBehaviorCommitment =
    commitment.behavior_commitment || publicBehaviorCommitment(behaviorCommitmentForStep(step, behaviorOptionsForStep(step)));
  if (requireExpectedHead && !hasExpectedHeadGuard(expectedHead)) {
    return {
      correct: false,
      code: 'EXPECTED_HEAD_REQUIRED',
      message: 'Submission must bind the latest parent head before it can enter ordering',
      latest_head: latestBase1HeadGuard(state),
      current: getCurrentBase1Public(state),
    };
  }
  const headGuard = verifyBase1LatestHead(state, expectedHead);
  if (!headGuard.ok) {
    return {
      correct: false,
      code: headGuard.code,
      message: headGuard.message,
      mismatches: headGuard.mismatches,
      expected_head: headGuard.expected,
      latest_head: headGuard.latest,
      current: getCurrentBase1Public(state),
    };
  }

  const feeAmount = submitFeeAmountForResult({ accepted: true, amount: submitFee, step });

  const submittedAt = nowIso();
  const candidate = candidateStep || makeCandidateFromOfficial(step);
  const verification = verifyCandidateStep({
    officialStep: step,
    candidateStep: candidate,
    options: verifierOptions,
  });
  const submission = {
    solver,
    layer_no: step.layer_no,
    step_no: step.step_no,
    accepted: verification.ok,
    stage: verification.stage,
    code: verification.code,
    answer_hash: verification.answer_hash,
    behavior_hash: verification.behavior_hash || null,
    validation_id: verification.validation_id || null,
    created_at: submittedAt,
  };
  state.submissions.push(submission);
  if (state.submissions.length > 1000) state.submissions = state.submissions.slice(-1000);

  const receipt = createBase1SolveReceipt({
    state,
    step,
    solver,
    candidate,
    verification,
    headGuard,
    networkTimeProof,
    networkConfirmation,
    status: verification.ok ? 'verified_local' : 'rejected_local_verification',
    reason: verification.ok ? 'candidate_passed_local_verifier' : verification.code || 'candidate_rejected',
  });

  if (!verification.ok) {
    state.events.push({
      type: 'BASE1_SUBMISSION_REJECTED_LOCAL',
      created_at: submittedAt,
      layer_no: step.layer_no,
      step_no: step.step_no,
      solver,
      code: verification.code,
      validation_id: verification.validation_id || null,
      answer_hash: verification.answer_hash || null,
      behavior_hash: verification.behavior_hash || null,
      policy: 'invalid_candidate_not_broadcast_not_on_chain',
    });
    saveBase1State(state);
    return {
      correct: false,
      message: verification.message || 'Candidate rejected',
      code: verification.code || 'CANDIDATE_REJECTED',
      solve_receipt: receipt,
      submit_fee: null,
      on_chain: false,
      broadcast: false,
      policy: 'invalid_candidate_not_broadcast_not_on_chain',
      verification,
      current: getCurrentBase1Public(state),
    };
  }

  if (networkConfirmation && networkConfirmation.status !== 'confirmed') {
    return {
      correct: false,
      code: 'NETWORK_CONFIRMATION_REQUIRED',
      message: 'Solve candidate did not reach the required network confirmation threshold',
      network_confirmation: networkConfirmation,
      current: getCurrentBase1Public(state),
    };
  }

  const lockResult = lockBase1StepForReceipt({ state, step, receipt, headGuard });
  if (!lockResult.ok) {
    saveBase1State(state);
    return {
      correct: false,
      code: 'STEP_ALREADY_LOCKED',
      message: 'Current Step already has an earlier valid solve receipt',
      solve_receipt: receipt,
      step_lock: lockResult.lock,
      current: getCurrentBase1Public(state),
    };
  }

  const grossReward = rewardForStep(step);
  const solvedSubmitFee = chargeFee ? Math.min(feeAmount, grossReward) : 0;
  const netReward = Math.max(0, grossReward - solvedSubmitFee);
  const parentHeight = Number(headGuard.latest.height || 0);
  const parentCumulativeWork = Number(headGuard.latest.cumulative_work_score || 0);
  const solveTx = createTransaction({
    type: 'BASE1_SOLVE_STEP',
    nonce: 0,
    createdAt: submittedAt,
    payload: {
      layer_no: step.layer_no,
      step_no: step.step_no,
      solver,
      validation_id: verification.validation_id,
      answer_hash: verification.answer_hash,
      behavior_hash: verification.behavior_hash,
      behavior_root: currentBehaviorCommitment.behavior_root,
      behavior_commitment_hash: currentBehaviorCommitment.commitment_hash,
      fragment_registry_root: commitment.fragment_registry_root || null,
      point_set_hash: verification.point_set?.hash || null,
      context_set_hash: verification.context_set?.hash || null,
      formula_hash: step.formula_hash,
      seed_source_hash: seedSource.source_hash,
      step_commit: commitment.step_commit,
      parent_block_hash: headGuard.latest.head_hash,
      parent_height: parentHeight,
      parent_cumulative_work_score: parentCumulativeWork,
      difficulty_score: step.scores?.final_score || 0,
      work_score: step.scores?.final_score || 0,
      solve_receipt_hash: receipt.receipt_hash,
      receipt_order: receipt.receipt_order,
      step_order: receipt.step_order,
      received_utc: receipt.received_utc,
      network_time_bucket: receipt.network_time_bucket,
      network_confirmation_hash: networkConfirmation?.confirmation_hash || null,
      network_confirmation_status: networkConfirmation?.status || null,
      confirmation_count: networkConfirmation?.confirmation_count || 0,
      required_confirmation_count: networkConfirmation?.required_confirmation_count || 0,
      signed_payload_hash: signedPayloadHash,
      submit_fee_amount: solvedSubmitFee,
      submit_fee_currency: 'MAZEX',
      submit_fee_source: chargeFee ? 'solve_reward' : 'none',
      gross_reward_amount: grossReward,
      net_reward_amount: netReward,
      solve_receipt: compactBase1SolveReceipt(receipt),
      step_lock: compactBase1StepLock(lockResult.lock),
    },
  });
  const feeResult = chargeFee
    ? burnBase1SubmitFee({
        state,
        solver,
        amount: solvedSubmitFee,
        reason: 'submit_fee',
        feeSource: 'solve_reward',
        grossRewardAmount: grossReward,
        netRewardAmount: netReward,
        createdAt: submittedAt,
        txNonce: 1,
        referenceTxHash: solveTx.tx_hash,
        signedPayloadHash,
        layerNo: step.layer_no,
        stepNo: step.step_no,
        validationId: verification.validation_id,
        answerHash: verification.answer_hash,
        behaviorHash: verification.behavior_hash,
        parentBlockHash: headGuard.latest.head_hash,
        parentHeight,
      })
    : null;
  if (feeResult && !feeResult.ok) {
    return {
      correct: false,
      ...feeResult,
      current: getCurrentBase1Public(state),
    };
  }
  const rewardTx = createTransaction({
    type: 'BASE1_REWARD_MINTED',
    nonce: chargeFee ? 2 : 1,
    createdAt: submittedAt,
    payload: {
      layer_no: step.layer_no,
      step_no: step.step_no,
      recipient: solver,
      reward_amount: netReward,
      gross_reward_amount: grossReward,
      submit_fee_burned: solvedSubmitFee,
      fee_policy: chargeFee ? 'deduct_submit_fee_from_success_reward' : 'no_submit_fee',
      reason: 'first_valid_expression_tree_explanation',
    },
  });
  const pendingReward = createPendingReward({
    state,
    step,
    solver,
    rewardAmount: netReward,
    rewardTxHash: rewardTx.tx_hash,
    blockHeight: parentHeight + 1,
    parentCumulativeWork,
    createdAt: submittedAt,
  });
  const solved = {
    layer_no: step.layer_no,
    step_no: step.step_no,
    solver,
    validation_id: verification.validation_id,
    answer_hash: verification.answer_hash,
    solution_hash: verification.answer_hash,
    behavior_hash: verification.behavior_hash,
    behavior_root: currentBehaviorCommitment.behavior_root,
    behavior_commitment_hash: currentBehaviorCommitment.commitment_hash,
    fragment_registry_root: commitment.fragment_registry_root || null,
    point_set_hash: verification.point_set?.hash || null,
    context_set_hash: verification.context_set?.hash || null,
    formula_hash: step.formula_hash,
    seed_source_hash: seedSource.source_hash,
    step_commit: commitment.step_commit,
    parent_block_hash: headGuard.latest.head_hash,
    parent_height: parentHeight,
    parent_cumulative_work_score: parentCumulativeWork,
    reward_id: pendingReward.id,
    reward_status: pendingReward.status,
    reward_amount: netReward,
    gross_reward_amount: grossReward,
    submit_fee_burned: solvedSubmitFee,
    fee_policy: chargeFee ? 'deduct_submit_fee_from_success_reward' : 'no_submit_fee',
    solve_receipt_hash: receipt.receipt_hash,
    receipt_order: receipt.receipt_order,
    step_order: receipt.step_order,
    received_utc: receipt.received_utc,
    network_time_bucket: receipt.network_time_bucket,
    network_confirmation_hash: networkConfirmation?.confirmation_hash || null,
    network_confirmation_status: networkConfirmation?.status || null,
    confirmation_count: networkConfirmation?.confirmation_count || 0,
    required_confirmation_count: networkConfirmation?.required_confirmation_count || 0,
    difficulty_score: step.scores?.final_score || 0,
    work_score: step.scores?.final_score || 0,
    solved_at: submittedAt,
  };
  state.solvedSteps.push(solved);
  updateLeaderboard(state, solver, step, netReward);
  state.events.push({
    type: 'BASE1_STEP_SOLVED',
    created_at: submittedAt,
    layer_no: step.layer_no,
    step_no: step.step_no,
    solver,
    validation_id: verification.validation_id,
    answer_hash: verification.answer_hash,
    behavior_hash: verification.behavior_hash,
    behavior_root: currentBehaviorCommitment.behavior_root,
    behavior_commitment_hash: currentBehaviorCommitment.commitment_hash,
    fragment_registry_root: commitment.fragment_registry_root || null,
    seed_source_hash: seedSource.source_hash,
    formula_hash: step.formula_hash,
  });

  const solveBlock = appendBlock(state, {
    producer: solver,
    createdAt: submittedAt,
    transactions: [solveTx, ...(feeResult?.fee_tx ? [feeResult.fee_tx] : []), rewardTx],
  });
  pendingReward.block_hash = solveBlock.block_hash;
  solved.solve_block_hash = solveBlock.block_hash;
  recordBase1Witness(state, {
    source: 'local-solver',
    blockHash: solveBlock.block_hash,
    headHash: solveBlock.block_hash,
    layerNo: step.layer_no,
    stepNo: step.step_no,
    stateRoot: solveBlock.state_root,
    reason: 'local_solve_block_verified_before_package',
  });

  const nextCreatedAt = nowIso();
  const nextStep = createNextStepFromSolved({ state, previousStep: step, solved, solveBlock });
  const targetCommitHeight = solveBlock.height + 1;
  const rewardSettlement = settleBase1Rewards(state, {
    targetHeight: targetCommitHeight,
    targetCumulativeWork: solveBlock.cumulative_work_score,
    createdAt: nextCreatedAt,
  });
  state.events.push({
    type: 'BASE1_STEP_COMMITTED',
    created_at: nextCreatedAt,
    layer_no: nextStep.step.layer_no,
    step_no: nextStep.step.step_no,
    seed_source_hash: nextStep.seedSource.source_hash,
    formula_hash: nextStep.step.formula_hash,
    fragment_registry_root: nextStep.commitment.fragment_registry_root,
    fragment_selection_hash: nextStep.commitment.fragment_selection?.selection_hash || null,
    fragment_selection_root: nextStep.commitment.fragment_selection?.selection_root || null,
    fragment_composition_plan_hash: nextStep.commitment.fragment_selection?.composition_plan_hash || null,
    fragment_generation_profile_hash:
      nextStep.commitment.fragment_selection?.generation_profile_hash || nextStep.step.fragment_generation_profile_hash || null,
    fragment_selected_count: nextStep.commitment.fragment_selection?.selected_count || 0,
    behavior_root: nextStep.commitment.behavior_root,
    behavior_commitment_hash: nextStep.commitment.behavior_commitment_hash,
    step_commit: nextStep.commitment.step_commit,
    previous_solve_block_hash: solveBlock.block_hash,
  });

  const commitBlock = appendBlock(state, {
    producer: 'base1-step-committer',
    createdAt: nextCreatedAt,
    transactions: [
      createTransaction({
        type: 'BASE1_STEP_ADVANCED',
        nonce: 0,
        createdAt: nextCreatedAt,
        payload: {
          from_layer: step.layer_no,
          from_step: step.step_no,
          to_layer: nextStep.step.layer_no,
          to_step: nextStep.step.step_no,
          previous_solve_block_hash: solveBlock.block_hash,
          previous_solve_receipt_hash: receipt.receipt_hash,
        },
      }),
      createTransaction({
        type: 'BASE1_STEP_COMMITTED',
        nonce: 1,
        createdAt: nextCreatedAt,
        payload: {
          layer_no: nextStep.step.layer_no,
          step_no: nextStep.step.step_no,
          formula_hash: nextStep.step.formula_hash,
          fragment_registry_root: nextStep.commitment.fragment_registry_root,
          fragment_selection_hash: nextStep.commitment.fragment_selection?.selection_hash || null,
          fragment_selection_root: nextStep.commitment.fragment_selection?.selection_root || null,
          fragment_composition_plan_hash: nextStep.commitment.fragment_selection?.composition_plan_hash || null,
          fragment_generation_profile_hash:
            nextStep.commitment.fragment_selection?.generation_profile_hash ||
            nextStep.step.fragment_generation_profile_hash ||
            null,
          fragment_selected_count: nextStep.commitment.fragment_selection?.selected_count || 0,
          behavior_root: nextStep.commitment.behavior_root,
          behavior_commitment_hash: nextStep.commitment.behavior_commitment_hash,
          seed_source_hash: nextStep.seedSource.source_hash,
          step_seed_hash: nextStep.commitment.seed_commitment.step_seed_hash,
          step_commit: nextStep.commitment.step_commit,
          score: nextStep.step.scores.final_score,
        },
      }),
      ...rewardSettlement.confirmed.map((reward, index) =>
        createTransaction({
          type: 'BASE1_REWARD_CONFIRMED',
          nonce: 2 + index,
          createdAt: nextCreatedAt,
          payload: {
            reward_id: reward.id,
            recipient: reward.recipient,
            amount: reward.amount,
            confirmations: reward.confirmations,
            work_after: reward.work_after,
          },
        }),
      ),
    ],
  });
  recordBase1Witness(state, {
    source: 'local-committer',
    blockHash: commitBlock.block_hash,
    headHash: commitBlock.block_hash,
    layerNo: nextStep.step.layer_no,
    stepNo: nextStep.step.step_no,
    stateRoot: commitBlock.state_root,
    reason: 'local_step_commit_verified_before_package',
  });
  const finalizedLock = finalizeBase1StepLock({ state, receipt, solveBlock, commitBlock });

  saveBase1State(state);
  return {
    correct: true,
    message: 'Base1 Step solved and next Step committed',
    solver,
    reward_amount: netReward,
    gross_reward_amount: grossReward,
    net_reward_amount: netReward,
    reward_status: pendingReward.status,
    reward: netReward,
    submit_fee: feeResult
      ? {
          amount: feeResult.amount,
          currency: 'MAZEX',
          policy: 'deducted_from_success_reward_and_burned',
          fee_source: 'solve_reward',
          tx_hash: feeResult.fee_tx.tx_hash,
        }
      : null,
    solve_receipt: receipt,
    step_lock: finalizedLock,
    network_confirmation: networkConfirmation,
    solved,
    verification,
    solve_block: solveBlock,
    commit_block: commitBlock,
    reward_settlement: rewardSettlement,
    next: getCurrentBase1Public(state),
  };
}

function appendBase1ConfirmationBlock({ producer = 'local-confirmation-node' } = {}) {
  const state = loadBase1State();
  const createdAt = nowIso();
  const head = chainSummary(state.chain);
  const targetHeight = Number(head.height || 0) + 1;
  const settlement = settleBase1Rewards(state, {
    targetHeight,
    targetCumulativeWork: head.cumulative_work_score,
    createdAt,
  });
  const block = appendBlock(state, {
    producer,
    createdAt,
    transactions: [
      createTransaction({
        type: 'BASE1_HEAD_CONFIRMED',
        nonce: 0,
        createdAt,
        payload: {
          confirmed_head_hash: head.head_hash,
          confirmed_height: head.height,
          target_height: targetHeight,
          pending_reward_count: settlement.pending_count,
          confirmed_reward_ids: settlement.confirmed.map((reward) => reward.id),
        },
      }),
      ...settlement.confirmed.map((reward, index) =>
        createTransaction({
          type: 'BASE1_REWARD_CONFIRMED',
          nonce: 1 + index,
          createdAt,
          payload: {
            reward_id: reward.id,
            recipient: reward.recipient,
            amount: reward.amount,
            confirmations: reward.confirmations,
            work_after: reward.work_after,
          },
        }),
      ),
    ],
  });
  state.events.push({
    type: 'BASE1_HEAD_CONFIRMED',
    created_at: createdAt,
    block_hash: block.block_hash,
    height: block.height,
    confirmed_reward_count: settlement.confirmed.length,
  });
  saveBase1State(state);
  return {
    ok: true,
    block,
    settlement,
    chain: chainSummary(state.chain),
  };
}

function getBase1Leaderboard() {
  const state = loadBase1State();
  return Object.values(state.leaderboard || {}).sort(
    (a, b) => b.total_score - a.total_score || b.solves - a.solves || b.total_rewards - a.total_rewards,
  );
}

function getBase1Reveals() {
  return loadBase1State().solvedSteps.slice().reverse();
}

function getBase1Events() {
  return loadBase1State().events.slice(-100).reverse();
}

function getBase1Account(address) {
  const state = loadBase1State();
  return publicAccount(state, address || 'unknown');
}

function getBase1Accounts() {
  const state = loadBase1State();
  return Object.values(state.accounts || {}).sort(
    (a, b) =>
      b.confirmed_balance - a.confirmed_balance ||
      b.pending_balance - a.pending_balance ||
      String(a.address).localeCompare(String(b.address)),
  );
}

function getBase1RewardLedger({ limit = 50 } = {}) {
  const state = loadBase1State();
  return (state.rewardLedger || []).slice(-Math.max(1, Math.trunc(Number(limit) || 50))).reverse();
}

function getBase1SolveReceipts({ limit = 50 } = {}) {
  const state = loadBase1State();
  return {
    queue: getBase1SolveQueueSummary(state),
    receipts: (state.solveReceipts || []).slice(-Math.max(1, Math.trunc(Number(limit) || 50))).reverse(),
    locks: Object.values(state.stepLocks || {}).slice(-Math.max(1, Math.trunc(Number(limit) || 50))).reverse(),
  };
}

function getBase1ChainSummary() {
  return chainSummary(loadBase1State().chain);
}

function getBase1ChainBlocks({ limit = 20 } = {}) {
  return getBlocks(loadBase1State().chain, limit);
}

function getBase1BlocksSince({ afterHeight = -1, afterHash = null, limit = 50 } = {}) {
  const state = loadBase1State();
  const max = Math.max(1, Math.min(500, Math.trunc(Number(limit) || 50)));
  const height = Math.trunc(Number(afterHeight ?? -1));
  const blocks = state.chain.blocks || [];
  let startIndex = blocks.findIndex((block) => block.height > height);
  if (afterHash) {
    const hashIndex = blocks.findIndex((block) => block.block_hash === afterHash);
    if (hashIndex >= 0) startIndex = hashIndex + 1;
  }
  if (startIndex < 0) startIndex = blocks.length;
  return {
    chain: chainSummary(state.chain),
    blocks: blocks.slice(startIndex, startIndex + max),
  };
}

function replayBlockStateAfter(state) {
  return {
    current_layer: state.currentLayer,
    current_step: state.currentStep,
    grid_size: state.gridSize,
    layer_root: state.layerRoot,
    current_formula_hash: state.currentFormulaHash || null,
    current_seed_source_hash: state.currentSeedSourceHash || null,
    current_fragment_registry_root: currentFragmentRegistryRoot(state),
    solved_count: (state.solvedSteps || []).length,
    leaderboard_size: Object.keys(state.leaderboard || {}).length,
    account_count: Object.keys(state.accounts || {}).length,
    pending_reward_count: (state.rewardLedger || []).filter((reward) => reward.status === 'pending').length,
    confirmed_reward_count: (state.rewardLedger || []).filter((reward) => reward.status === 'confirmed').length,
    transfer_count: (state.transfers || []).length,
    burned_fees: state.burnedFees || 0,
  };
}

function sameJson(left, right) {
  return JSON.stringify(left || {}) === JSON.stringify(right || {});
}

function firstTx(block, type) {
  return (block.transactions || []).find((tx) => tx.type === type) || null;
}

function replayFailure(code, message, detail = {}) {
  return {
    ok: false,
    code,
    message,
    ...detail,
  };
}

function applyReplayFragmentRegistrationBlock(state, block, previousBlock, tx) {
  const payload = tx.payload || {};
  const record = payload.fragment;
  if (!record) {
    return replayFailure('REPLAY_FRAGMENT_RECORD_MISSING', 'Fragment registration transaction is missing fragment record', {
      height: block.height,
      tx_hash: tx.tx_hash,
    });
  }
  if (!state.fragmentRegistry) state.fragmentRegistry = createDefaultFragmentRegistry();
  const replayHeight = Number(previousBlock?.height ?? Math.max(0, Number(block.height || 0) - 1));
  const result = addFragmentRecord(state.fragmentRegistry, record, { currentHeight: replayHeight });
  if (!result.ok && result.code !== 'FRAGMENT_DUPLICATE') {
    return replayFailure(result.code || 'REPLAY_FRAGMENT_INVALID', result.message || 'Fragment registration failed replay', {
      height: block.height,
      tx_hash: tx.tx_hash,
      errors: result.errors || [],
    });
  }
  if (result.ok) state.fragmentRegistry = result.registry;
  const roots = computeFragmentRegistryRoots(state.fragmentRegistry, { currentHeight: replayHeight });
  if (payload.registry_root && payload.registry_root !== roots.registry_root) {
    return replayFailure('REPLAY_FRAGMENT_REGISTRY_ROOT_MISMATCH', 'Fragment registry root cannot be reproduced', {
      height: block.height,
      expected_registry_root: payload.registry_root,
      actual_registry_root: roots.registry_root,
    });
  }
  if (payload.active_root && payload.active_root !== roots.active_root) {
    return replayFailure('REPLAY_FRAGMENT_ACTIVE_ROOT_MISMATCH', 'Active fragment root cannot be reproduced', {
      height: block.height,
      expected_active_root: payload.active_root,
      actual_active_root: roots.active_root,
    });
  }
  return { ok: true, registry: state.fragmentRegistry };
}

function applyReplayFragmentUpgradeBlock(state, block, previousBlock, tx) {
  const payload = tx.payload || {};
  const record = payload.fragment;
  const previousFragmentId = payload.previous_fragment_id || record?.supersedes_fragment_id || '';
  if (!record || !previousFragmentId) {
    return replayFailure('REPLAY_FRAGMENT_UPGRADE_MISSING', 'Fragment upgrade transaction is missing required records', {
      height: block.height,
      tx_hash: tx.tx_hash,
    });
  }
  if (!state.fragmentRegistry) state.fragmentRegistry = createDefaultFragmentRegistry();
  const replayHeight = Number(previousBlock?.height ?? Math.max(0, Number(block.height || 0) - 1));
  const result = upgradeFragment(
    state.fragmentRegistry,
    {
      kind: record.kind,
      name: record.name,
      version: record.version,
      author: record.author,
      payload: record.payload,
      budget: record.budget,
      deterministic: record.deterministic,
      compatibility: record.compatibility,
      supersedes_fragment_id: previousFragmentId,
    },
    {
      previousFragmentId,
      currentHeight: replayHeight,
      activationDelay: Math.max(0, Number(record.activation_height || replayHeight) - replayHeight),
      createdAt: record.created_at || tx.created_at || block.created_at,
    },
  );
  if (!result.ok) {
    return replayFailure(result.code || 'REPLAY_FRAGMENT_UPGRADE_INVALID', result.message || 'Fragment upgrade failed replay', {
      height: block.height,
      tx_hash: tx.tx_hash,
      errors: result.errors || [],
    });
  }
  if (result.record.fragment_id !== record.fragment_id || result.record.content_hash !== record.content_hash) {
    return replayFailure('REPLAY_FRAGMENT_UPGRADE_HASH_MISMATCH', 'Fragment upgrade hash cannot be reproduced', {
      height: block.height,
      expected_fragment_id: record.fragment_id,
      actual_fragment_id: result.record.fragment_id,
    });
  }
  state.fragmentRegistry = result.registry;
  const roots = computeFragmentRegistryRoots(state.fragmentRegistry, { currentHeight: replayHeight });
  if (payload.registry_root && payload.registry_root !== roots.registry_root) {
    return replayFailure('REPLAY_FRAGMENT_UPGRADE_REGISTRY_ROOT_MISMATCH', 'Fragment registry root cannot be reproduced after upgrade', {
      height: block.height,
      expected_registry_root: payload.registry_root,
      actual_registry_root: roots.registry_root,
    });
  }
  if (payload.active_root && payload.active_root !== roots.active_root) {
    return replayFailure('REPLAY_FRAGMENT_UPGRADE_ACTIVE_ROOT_MISMATCH', 'Active fragment root cannot be reproduced after upgrade', {
      height: block.height,
      expected_active_root: payload.active_root,
      actual_active_root: roots.active_root,
    });
  }
  return { ok: true, registry: state.fragmentRegistry };
}

function applyReplayFragmentQuarantineBlock(state, block, previousBlock, tx) {
  const payload = tx.payload || {};
  const quarantine = payload.quarantine;
  if (!payload.fragment_id || !quarantine) {
    return replayFailure('REPLAY_FRAGMENT_QUARANTINE_MISSING', 'Fragment quarantine transaction is missing required proof', {
      height: block.height,
      tx_hash: tx.tx_hash,
    });
  }
  if (!state.fragmentRegistry) state.fragmentRegistry = createDefaultFragmentRegistry();
  const replayHeight = Number(previousBlock?.height ?? Math.max(0, Number(block.height || 0) - 1));
  const result = quarantineFragment(
    state.fragmentRegistry,
    {
      fragment_id: payload.fragment_id,
      challenger: quarantine.challenger,
      reason_code: quarantine.reason_code,
      evidence: quarantine.evidence,
      created_at: quarantine.created_at || tx.created_at || block.created_at,
    },
    {
      currentHeight: replayHeight,
      createdAt: quarantine.created_at || tx.created_at || block.created_at,
    },
  );
  if (!result.ok) {
    return replayFailure(result.code || 'REPLAY_FRAGMENT_QUARANTINE_INVALID', result.message || 'Fragment quarantine failed replay', {
      height: block.height,
      tx_hash: tx.tx_hash,
      errors: result.errors || [],
    });
  }
  if (quarantine.proof_hash && quarantine.proof_hash !== result.quarantine.proof_hash) {
    return replayFailure('REPLAY_FRAGMENT_QUARANTINE_PROOF_MISMATCH', 'Fragment quarantine proof hash cannot be reproduced', {
      height: block.height,
      expected_proof_hash: quarantine.proof_hash,
      actual_proof_hash: result.quarantine.proof_hash,
    });
  }
  state.fragmentRegistry = result.registry;
  const roots = computeFragmentRegistryRoots(state.fragmentRegistry, { currentHeight: replayHeight });
  if (payload.registry_root && payload.registry_root !== roots.registry_root) {
    return replayFailure('REPLAY_FRAGMENT_QUARANTINE_REGISTRY_ROOT_MISMATCH', 'Fragment registry root cannot be reproduced after quarantine', {
      height: block.height,
      expected_registry_root: payload.registry_root,
      actual_registry_root: roots.registry_root,
    });
  }
  if (payload.active_root && payload.active_root !== roots.active_root) {
    return replayFailure('REPLAY_FRAGMENT_QUARANTINE_ACTIVE_ROOT_MISMATCH', 'Active fragment root cannot be reproduced after quarantine', {
      height: block.height,
      expected_active_root: payload.active_root,
      actual_active_root: roots.active_root,
    });
  }
  return { ok: true, registry: state.fragmentRegistry };
}

function applyReplaySubmitFeeBurnTx(state, block, feeTx) {
  const payload = feeTx.payload || {};
  const senderAddress = String(payload.from || '').trim();
  const amount = normalizePositiveInteger(payload.amount);
  const accountNonce = Math.trunc(Number(payload.account_nonce || 0));
  const feeSource = payload.fee_source || 'confirmed_balance';
  if (!senderAddress || amount <= 0) {
    return replayFailure('REPLAY_INVALID_SUBMIT_FEE', 'Submit fee burn transaction is missing sender or amount', {
      height: block.height,
      tx_hash: feeTx.tx_hash,
    });
  }
  const account = ensureAccount(state, senderAddress);
  const expectedNonce = account.nonce + 1;
  if (accountNonce !== expectedNonce) {
    return replayFailure('REPLAY_SUBMIT_FEE_NONCE_MISMATCH', 'Submit fee nonce does not match replay account state', {
      height: block.height,
      expected_nonce: expectedNonce,
      actual_nonce: accountNonce,
      tx_hash: feeTx.tx_hash,
    });
  }
  if (feeSource !== 'solve_reward' && account.confirmed_balance < amount) {
    return replayFailure('REPLAY_SUBMIT_FEE_BALANCE_MISMATCH', 'Submit fee spends more confirmed balance than replay state allows', {
      height: block.height,
      confirmed_balance: account.confirmed_balance,
      required: amount,
      tx_hash: feeTx.tx_hash,
    });
  }
  const createdAt = feeTx.created_at || block.created_at;
  if (feeSource !== 'solve_reward') account.confirmed_balance -= amount;
  account.total_sent += amount;
  account.total_submit_fees_burned = Number(account.total_submit_fees_burned || 0) + amount;
  if (feeSource === 'solve_reward') {
    account.total_reward_fees_burned = Number(account.total_reward_fees_burned || 0) + amount;
  }
  account.nonce = accountNonce;
  account.updated_at = createdAt;
  state.burnedFees += amount;
  return { ok: true, amount };
}

function applyReplaySolveBlock(state, block, previousBlock, solveTx) {
  const rewardTx = firstTx(block, 'BASE1_REWARD_MINTED');
  if (!rewardTx) {
    return replayFailure('REPLAY_REWARD_TX_MISSING', 'Solve block is missing BASE1_REWARD_MINTED', {
      height: block.height,
      block_hash: block.block_hash,
    });
  }
  const payload = solveTx.payload || {};
  const step = getCurrentOfficialStep(state);
  const seedSource = getCurrentSeedSource(state);
  const commitment = getCurrentCommitment(state);
  if (!step || !seedSource || !commitment) {
    return replayFailure('REPLAY_CURRENT_STEP_MISSING', 'Replay state has no current Step', { height: block.height });
  }
  if (Number(payload.layer_no) !== Number(step.layer_no) || Number(payload.step_no) !== Number(step.step_no)) {
    return replayFailure('REPLAY_SOLVE_STEP_MISMATCH', 'Solve transaction does not match replay current Step', {
      height: block.height,
      tx_layer_no: payload.layer_no,
      tx_step_no: payload.step_no,
      current_layer_no: step.layer_no,
      current_step_no: step.step_no,
    });
  }
  if (payload.formula_hash && payload.formula_hash !== step.formula_hash) {
    return replayFailure('REPLAY_FORMULA_HASH_MISMATCH', 'Solve transaction formula hash does not match current Step', {
      height: block.height,
    });
  }
  if (payload.seed_source_hash && payload.seed_source_hash !== seedSource.source_hash) {
    return replayFailure('REPLAY_SEED_SOURCE_HASH_MISMATCH', 'Solve transaction seed source hash does not match current Step', {
      height: block.height,
    });
  }
  if (payload.fragment_registry_root && payload.fragment_registry_root !== commitment.fragment_registry_root) {
    return replayFailure('REPLAY_FRAGMENT_ROOT_MISMATCH', 'Solve transaction fragment registry root does not match current Step', {
      height: block.height,
    });
  }
  if (payload.step_commit && payload.step_commit !== commitment.step_commit) {
    return replayFailure('REPLAY_STEP_COMMIT_MISMATCH', 'Solve transaction commitment does not match current Step', {
      height: block.height,
    });
  }

  const solver = String(payload.solver || block.producer || 'unknown-solver');
  const rewardAmount = normalizePositiveInteger(rewardTx.payload?.reward_amount, rewardForStep(step));
  const parentCumulativeWork = Number.isFinite(Number(payload.parent_cumulative_work_score))
    ? Number(payload.parent_cumulative_work_score)
    : Number(previousBlock?.cumulative_work_score || 0);
  const createdAt = solveTx.created_at || block.created_at;
  const pendingReward = createPendingReward({
    state,
    step,
    solver,
    rewardAmount,
    rewardTxHash: rewardTx.tx_hash,
    blockHeight: block.height,
    parentCumulativeWork,
    createdAt,
  });
  const solved = {
    layer_no: step.layer_no,
    step_no: step.step_no,
    solver,
    validation_id: payload.validation_id,
    answer_hash: payload.answer_hash,
    solution_hash: payload.answer_hash,
    behavior_hash: payload.behavior_hash || null,
    behavior_root: payload.behavior_root || null,
    behavior_commitment_hash: payload.behavior_commitment_hash || null,
    fragment_registry_root: payload.fragment_registry_root || commitment.fragment_registry_root || null,
    point_set_hash: payload.point_set_hash || null,
    context_set_hash: payload.context_set_hash || null,
    formula_hash: step.formula_hash,
    seed_source_hash: seedSource.source_hash,
    step_commit: commitment.step_commit,
    parent_block_hash: payload.parent_block_hash || previousBlock?.block_hash || null,
    parent_height: Number(payload.parent_height ?? previousBlock?.height ?? 0),
    parent_cumulative_work_score: parentCumulativeWork,
    reward_id: pendingReward.id,
    reward_status: pendingReward.status,
    reward_amount: rewardAmount,
    gross_reward_amount: normalizePositiveInteger(rewardTx.payload?.gross_reward_amount, rewardAmount),
    submit_fee_burned: normalizePositiveInteger(rewardTx.payload?.submit_fee_burned, 0),
    fee_policy: rewardTx.payload?.fee_policy || null,
    solve_receipt_hash: payload.solve_receipt_hash || payload.solve_receipt?.receipt_hash || null,
    receipt_order: payload.receipt_order || payload.solve_receipt?.receipt_order || null,
    step_order: payload.step_order || payload.solve_receipt?.step_order || null,
    received_utc: payload.received_utc || payload.solve_receipt?.received_utc || null,
    network_time_bucket: payload.network_time_bucket ?? payload.solve_receipt?.network_time_bucket ?? null,
    network_confirmation_hash: payload.network_confirmation_hash || payload.solve_receipt?.confirmation_hash || null,
    network_confirmation_status: payload.network_confirmation_status || payload.solve_receipt?.confirmation_status || null,
    confirmation_count: payload.confirmation_count || payload.solve_receipt?.confirmation_count || 0,
    required_confirmation_count: payload.required_confirmation_count || payload.solve_receipt?.required_confirmation_count || 0,
    difficulty_score: Number(payload.difficulty_score || step.scores?.final_score || 0),
    work_score: Number(payload.work_score || payload.difficulty_score || step.scores?.final_score || 0),
    solved_at: createdAt,
  };
  state.solvedSteps.push(solved);
  if (payload.solve_receipt?.receipt_hash) {
    state.solveReceipts ||= [];
    if (!state.solveReceipts.some((receipt) => receipt.receipt_hash === payload.solve_receipt.receipt_hash)) {
      state.solveReceipts.push({
        ...payload.solve_receipt,
        status: payload.solve_receipt.status || 'finalized_first_valid',
      });
    }
  }
  if (payload.step_lock?.lock_hash) {
    state.stepLocks ||= {};
    const lockKey = stepLockKey({
      parentHeadHash: payload.step_lock.parent_block_hash || payload.parent_block_hash,
      layerNo: step.layer_no,
      stepNo: step.step_no,
    });
    state.stepLocks[lockKey] = {
      ...payload.step_lock,
      status: payload.step_lock.status || 'pending',
      solve_block_hash: block.block_hash,
    };
  }
  updateLeaderboard(state, solver, step, rewardAmount);
  pendingReward.block_hash = block.block_hash;
  solved.solve_block_hash = block.block_hash;
  return { ok: true, solved, reward: pendingReward };
}

function applyReplayStepCommitBlock(state, block, previousBlock) {
  const advancedTx = firstTx(block, 'BASE1_STEP_ADVANCED');
  const committedTx = firstTx(block, 'BASE1_STEP_COMMITTED');
  const previousStep = getCurrentOfficialStep(state);
  const solved = (state.solvedSteps || [])[state.solvedSteps.length - 1];
  if (!previousStep || !solved) {
    return replayFailure('REPLAY_STEP_COMMIT_CONTEXT_MISSING', 'Step commit block has no previous Step or solved result', {
      height: block.height,
    });
  }
  const solveBlockHash =
    advancedTx?.payload?.previous_solve_block_hash ||
    committedTx?.payload?.previous_solve_block_hash ||
    solved.solve_block_hash ||
    previousBlock?.block_hash;
  const nextStep = createNextStepFromSolved({
    state,
    previousStep,
    solved,
    solveBlock: { block_hash: solveBlockHash },
  });
  const payload = committedTx?.payload || {};
  if (payload.layer_no && Number(payload.layer_no) !== Number(nextStep.step.layer_no)) {
    return replayFailure('REPLAY_NEXT_LAYER_MISMATCH', 'Committed layer does not match replay generated layer', {
      height: block.height,
      committed_layer_no: payload.layer_no,
      replay_layer_no: nextStep.step.layer_no,
    });
  }
  if (payload.step_no && Number(payload.step_no) !== Number(nextStep.step.step_no)) {
    return replayFailure('REPLAY_NEXT_STEP_MISMATCH', 'Committed Step does not match replay generated Step', {
      height: block.height,
      committed_step_no: payload.step_no,
      replay_step_no: nextStep.step.step_no,
    });
  }
  if (payload.formula_hash && payload.formula_hash !== nextStep.step.formula_hash) {
    return replayFailure('REPLAY_NEXT_FORMULA_MISMATCH', 'Committed formula hash does not match replay generated Step', {
      height: block.height,
    });
  }
  if (payload.seed_source_hash && payload.seed_source_hash !== nextStep.seedSource.source_hash) {
    return replayFailure('REPLAY_NEXT_SEED_SOURCE_MISMATCH', 'Committed seed source hash does not match replay generated Step', {
      height: block.height,
    });
  }
  if (payload.fragment_registry_root && payload.fragment_registry_root !== nextStep.commitment.fragment_registry_root) {
    return replayFailure('REPLAY_NEXT_FRAGMENT_ROOT_MISMATCH', 'Committed fragment registry root does not match replay generated Step', {
      height: block.height,
    });
  }
  if (
    payload.fragment_selection_hash &&
    payload.fragment_selection_hash !== (nextStep.commitment.fragment_selection?.selection_hash || null)
  ) {
    return replayFailure('REPLAY_NEXT_FRAGMENT_SELECTION_HASH_MISMATCH', 'Committed fragment selection hash does not match replay generated Step', {
      height: block.height,
    });
  }
  if (
    payload.fragment_selection_root &&
    payload.fragment_selection_root !== (nextStep.commitment.fragment_selection?.selection_root || null)
  ) {
    return replayFailure('REPLAY_NEXT_FRAGMENT_SELECTION_ROOT_MISMATCH', 'Committed fragment selection root does not match replay generated Step', {
      height: block.height,
    });
  }
  if (
    payload.fragment_composition_plan_hash &&
    payload.fragment_composition_plan_hash !== (nextStep.commitment.fragment_selection?.composition_plan_hash || null)
  ) {
    return replayFailure(
      'REPLAY_NEXT_FRAGMENT_COMPOSITION_PLAN_MISMATCH',
      'Committed fragment composition plan does not match replay generated Step',
      {
        height: block.height,
      },
    );
  }
  const replayGenerationProfileHash =
    nextStep.commitment.fragment_selection?.generation_profile_hash || nextStep.step.fragment_generation_profile_hash || null;
  if (payload.fragment_generation_profile_hash && payload.fragment_generation_profile_hash !== replayGenerationProfileHash) {
    return replayFailure(
      'REPLAY_NEXT_FRAGMENT_GENERATION_PROFILE_MISMATCH',
      'Committed fragment generation profile does not match replay generated Step',
      {
        height: block.height,
      },
    );
  }
  if (payload.step_commit && payload.step_commit !== nextStep.commitment.step_commit) {
    return replayFailure('REPLAY_NEXT_COMMIT_MISMATCH', 'Committed Step hash does not match replay generated Step', {
      height: block.height,
    });
  }
  const receiptHash = advancedTx?.payload?.previous_solve_receipt_hash || solved.solve_receipt_hash || null;
  if (receiptHash) {
    const lockKey = Object.keys(state.stepLocks || {}).find(
      (key) => state.stepLocks[key]?.winning_receipt_hash === receiptHash,
    );
    if (lockKey) {
      state.stepLocks[lockKey].status = 'finalized';
      state.stepLocks[lockKey].commit_block_hash = block.block_hash;
      state.stepLocks[lockKey].finalized_at = committedTx?.created_at || advancedTx?.created_at || block.created_at;
    }
    const receipt = (state.solveReceipts || []).find((item) => item.receipt_hash === receiptHash);
    if (receipt) {
      receipt.status = 'finalized_first_valid';
      receipt.commit_block_hash = block.block_hash;
    }
  }
  settleBase1Rewards(state, {
    targetHeight: block.height,
    targetCumulativeWork: Number(previousBlock?.cumulative_work_score || 0),
    createdAt: committedTx?.created_at || advancedTx?.created_at || block.created_at,
  });
  return { ok: true, next: nextStep };
}

function applyReplayTransferBlock(state, block, transferTx) {
  const payload = transferTx.payload || {};
  const senderAddress = String(payload.from || '').trim();
  const receiverAddress = String(payload.to || '').trim();
  const transferAmount = normalizePositiveInteger(payload.amount);
  const transferFee = Math.max(0, normalizePositiveInteger(payload.fee, DEFAULT_TRANSFER_FEE));
  const transferNonce = Math.trunc(Number(payload.account_nonce || 0));
  if (!senderAddress || !receiverAddress || senderAddress === receiverAddress) {
    return replayFailure('REPLAY_INVALID_TRANSFER_PARTIES', 'Transfer block has invalid sender or receiver', {
      height: block.height,
    });
  }
  const sender = ensureAccount(state, senderAddress);
  const receiver = ensureAccount(state, receiverAddress);
  const expectedNonce = sender.nonce + 1;
  if (transferNonce !== expectedNonce) {
    return replayFailure('REPLAY_TRANSFER_NONCE_MISMATCH', 'Transfer nonce does not match replay account state', {
      height: block.height,
      expected_nonce: expectedNonce,
      actual_nonce: transferNonce,
    });
  }
  const totalDebit = transferAmount + transferFee;
  if (sender.confirmed_balance < totalDebit) {
    return replayFailure('REPLAY_TRANSFER_BALANCE_MISMATCH', 'Transfer spends more confirmed balance than replay state allows', {
      height: block.height,
      confirmed_balance: sender.confirmed_balance,
      required: totalDebit,
    });
  }
  const createdAt = transferTx.created_at || block.created_at;
  sender.confirmed_balance -= totalDebit;
  sender.total_sent += totalDebit;
  sender.nonce = transferNonce;
  sender.updated_at = createdAt;
  receiver.confirmed_balance += transferAmount;
  receiver.total_received += transferAmount;
  receiver.updated_at = createdAt;
  state.burnedFees += transferFee;
  const transfer = {
    id: sha256({
      type: 'mazex.base1.transfer',
      tx_hash: transferTx.tx_hash,
      from: senderAddress,
      to: receiverAddress,
      amount: transferAmount,
      fee: transferFee,
      nonce: transferNonce,
    }),
    from: senderAddress,
    to: receiverAddress,
    amount: transferAmount,
    fee: transferFee,
    nonce: transferNonce,
    tx_hash: transferTx.tx_hash,
    signed_payload_hash: payload.signed_payload_hash || null,
    block_height: block.height,
    block_hash: block.block_hash,
    created_at: createdAt,
  };
  state.transfers.push(transfer);
  return { ok: true, transfer };
}

function applyReplayBlock(state, block, previousBlock) {
  const fragmentTx = firstTx(block, 'BASE1_FRAGMENT_REGISTERED');
  if (fragmentTx) {
    const result = applyReplayFragmentRegistrationBlock(state, block, previousBlock, fragmentTx);
    if (!result.ok) return result;
  }

  const fragmentUpgradeTx = firstTx(block, 'BASE1_FRAGMENT_UPGRADED');
  if (fragmentUpgradeTx) {
    const result = applyReplayFragmentUpgradeBlock(state, block, previousBlock, fragmentUpgradeTx);
    if (!result.ok) return result;
  }

  const fragmentQuarantineTx = firstTx(block, 'BASE1_FRAGMENT_QUARANTINED');
  if (fragmentQuarantineTx) {
    const result = applyReplayFragmentQuarantineBlock(state, block, previousBlock, fragmentQuarantineTx);
    if (!result.ok) return result;
  }

  const submitFeeTxs = (block.transactions || []).filter((tx) => tx.type === 'BASE1_SUBMIT_FEE_BURNED');
  for (const feeTx of submitFeeTxs) {
    const result = applyReplaySubmitFeeBurnTx(state, block, feeTx);
    if (!result.ok) return result;
  }

  const solveTx = firstTx(block, 'BASE1_SOLVE_STEP');
  if (solveTx) {
    const result = applyReplaySolveBlock(state, block, previousBlock, solveTx);
    if (!result.ok) return result;
  }

  if (firstTx(block, 'BASE1_STEP_ADVANCED') || firstTx(block, 'BASE1_STEP_COMMITTED')) {
    const result = applyReplayStepCommitBlock(state, block, previousBlock);
    if (!result.ok) return result;
  } else if (firstTx(block, 'BASE1_HEAD_CONFIRMED')) {
    const headTx = firstTx(block, 'BASE1_HEAD_CONFIRMED');
    settleBase1Rewards(state, {
      targetHeight: block.height,
      targetCumulativeWork: Number(previousBlock?.cumulative_work_score || 0),
      createdAt: headTx.created_at || block.created_at,
    });
  }

  const transferTx = firstTx(block, 'BASE1_TRANSFER');
  if (transferTx) {
    const result = applyReplayTransferBlock(state, block, transferTx);
    if (!result.ok) return result;
  }

  return { ok: true };
}

function replayBase1Chain({ state = loadBase1State(), chain = null, includeState = false } = {}) {
  const source = normalizeBase1State(cloneJson(state));
  if (chain) source.chain = cloneJson(chain);
  const blocks = source.chain?.blocks || [];
  if (!blocks.length) return replayFailure('REPLAY_EMPTY_CHAIN', 'Cannot replay an empty chain');

  const chainCheck = verifyLocalChain(source.chain);
  if (!chainCheck.ok) return replayFailure(chainCheck.code || 'REPLAY_CHAIN_INVALID', 'Chain hash sequence is invalid', chainCheck);

  const replayState = buildFreshBase1State({
    chainId: source.chainId || DEFAULT_CHAIN_ID,
    seasonSeed: source.seasonSeed || DEFAULT_SEASON_SEED,
    genesisCreatedAt: source.genesisCreatedAt || DEFAULT_GENESIS_CREATED_AT,
  });
  const genesis = blocks[0];
  const replayGenesis = replayState.chain.blocks[0];
  if (genesis.block_hash !== replayGenesis.block_hash) {
    return replayFailure('REPLAY_GENESIS_MISMATCH', 'Replay genesis block does not match chain genesis', {
      expected_genesis_hash: genesis.block_hash,
      replay_genesis_hash: replayGenesis.block_hash,
    });
  }
  if (genesis.state_root !== computeStateRoot(replayState)) {
    return replayFailure('REPLAY_GENESIS_STATE_ROOT_MISMATCH', 'Genesis state root cannot be reproduced', {
      height: 0,
      expected_state_root: genesis.state_root,
      actual_state_root: computeStateRoot(replayState),
    });
  }
  if (!sameJson(genesis.state_after, replayBlockStateAfter(replayState))) {
    return replayFailure('REPLAY_GENESIS_STATE_AFTER_MISMATCH', 'Genesis state_after cannot be reproduced', {
      height: 0,
      expected_state_after: genesis.state_after,
      actual_state_after: replayBlockStateAfter(replayState),
    });
  }

  replayState.chain.blocks = [cloneJson(genesis)];
  replayState.chain.genesis_hash = genesis.block_hash;
  replayState.chain.head_hash = genesis.block_hash;
  replayState.chain.height = genesis.height;

  const checkpoints = [
    {
      height: 0,
      block_hash: genesis.block_hash,
      state_root: genesis.state_root,
      current: `${replayState.currentLayer}/${replayState.currentStep}`,
    },
  ];

  for (let index = 1; index < blocks.length; index += 1) {
    const block = blocks[index];
    const previousBlock = replayState.chain.blocks[replayState.chain.blocks.length - 1];
    const blockCheck = verifyBlock(block, previousBlock);
    if (!blockCheck.ok) return replayFailure(blockCheck.code || 'REPLAY_BLOCK_INVALID', 'Block failed replay hash verification', blockCheck);

    const applyResult = applyReplayBlock(replayState, block, previousBlock);
    if (!applyResult.ok) return applyResult;

    const actualStateRoot = computeStateRoot(replayState);
    if (block.state_root !== actualStateRoot) {
      return replayFailure('REPLAY_STATE_ROOT_MISMATCH', 'Block state_root cannot be reproduced from transactions', {
        height: block.height,
        block_hash: block.block_hash,
        expected_state_root: block.state_root,
        actual_state_root: actualStateRoot,
      });
    }
    const actualStateAfter = replayBlockStateAfter(replayState);
    if (!sameJson(block.state_after, actualStateAfter)) {
      return replayFailure('REPLAY_STATE_AFTER_MISMATCH', 'Block state_after cannot be reproduced from transactions', {
        height: block.height,
        block_hash: block.block_hash,
        expected_state_after: block.state_after,
        actual_state_after: actualStateAfter,
      });
    }

    replayState.chain.blocks.push(cloneJson(block));
    replayState.chain.head_hash = block.block_hash;
    replayState.chain.height = block.height;
    checkpoints.push({
      height: block.height,
      block_hash: block.block_hash,
      state_root: block.state_root,
      current: `${replayState.currentLayer}/${replayState.currentStep}`,
    });
  }

  return {
    ok: true,
    status: 'replayed',
    checked_blocks: blocks.length,
    checked_state_roots: checkpoints.length,
    chain: chainSummary(replayState.chain),
    current_layer: replayState.currentLayer,
    current_step: replayState.currentStep,
    generated_step_count: replayState.generatedStepKeys.length,
    solved_count: replayState.solvedSteps.length,
    reward_count: replayState.rewardLedger.length,
    transfer_count: replayState.transfers.length,
    checkpoints: checkpoints.slice(-10),
    replay_state: includeState ? replayState : undefined,
  };
}

function validateBase1StateSnapshot(snapshot = {}, { anchorBlock = null } = {}) {
  if (!snapshot || !snapshot.state || !snapshot.anchor) {
    return replayFailure('SNAPSHOT_INCOMPLETE', 'Snapshot must include state and anchor metadata');
  }
  const snapshotState = cloneJson(snapshot.state);
  const anchor = snapshot.anchor || {};
  const blocks = snapshotState.chain?.blocks || [];
  const headBlock = blocks[blocks.length - 1] || null;
  if (!headBlock) return replayFailure('SNAPSHOT_CHAIN_EMPTY', 'Snapshot state must include at least the anchor block');
  if (Number(headBlock.height) !== Number(anchor.height) || headBlock.block_hash !== anchor.block_hash) {
    return replayFailure('SNAPSHOT_HEAD_MISMATCH', 'Snapshot state chain head does not match snapshot anchor', {
      anchor_height: anchor.height,
      head_height: headBlock.height,
      anchor_hash: anchor.block_hash,
      head_hash: headBlock.block_hash,
    });
  }
  if (anchorBlock) {
    if (anchorBlock.block_hash !== anchor.block_hash) {
      return replayFailure('SNAPSHOT_ANCHOR_BLOCK_HASH_MISMATCH', 'Snapshot anchor block hash does not match supplied anchor block');
    }
    if (anchorBlock.state_root !== anchor.state_root) {
      return replayFailure('SNAPSHOT_ANCHOR_STATE_ROOT_MISMATCH', 'Snapshot anchor state_root does not match supplied anchor block');
    }
    if (!sameJson(anchorBlock.state_after, anchor.state_after)) {
      return replayFailure('SNAPSHOT_ANCHOR_STATE_AFTER_MISMATCH', 'Snapshot anchor state_after does not match supplied anchor block');
    }
  }
  const actualStateRoot = computeStateRoot(snapshotState);
  if (actualStateRoot !== snapshot.state_root || actualStateRoot !== anchor.state_root) {
    return replayFailure('SNAPSHOT_STATE_ROOT_MISMATCH', 'Snapshot state_root cannot be reproduced from snapshot state', {
      expected_state_root: snapshot.state_root,
      anchor_state_root: anchor.state_root,
      actual_state_root: actualStateRoot,
    });
  }
  const actualStateAfter = replayBlockStateAfter(snapshotState);
  if (!sameJson(actualStateAfter, snapshot.state_after) || !sameJson(actualStateAfter, anchor.state_after)) {
    return replayFailure('SNAPSHOT_STATE_AFTER_MISMATCH', 'Snapshot state_after cannot be reproduced from snapshot state', {
      expected_state_after: snapshot.state_after,
      anchor_state_after: anchor.state_after,
      actual_state_after: actualStateAfter,
    });
  }
  const actualFullStateHash = sha256({
    type: 'mazex.base1.snapshot.full_state',
    state: snapshotState,
  });
  if (snapshot.full_state_hash && snapshot.full_state_hash !== actualFullStateHash) {
    return replayFailure('SNAPSHOT_FULL_STATE_HASH_MISMATCH', 'Snapshot full_state_hash cannot be reproduced');
  }
  const expectedPayload = {
    type: snapshot.type || 'mazex.base1.state_snapshot',
    version: snapshot.version || 'mazexchain-base1-snapshot-1.0',
    chain_id: snapshot.chain_id,
    genesis_hash: snapshot.genesis_hash,
    anchor,
    state_root: snapshot.state_root,
    state_after: snapshot.state_after,
    full_state_hash: snapshot.full_state_hash || actualFullStateHash,
  };
  const actualSnapshotHash = sha256(expectedPayload);
  if (snapshot.snapshot_hash && snapshot.snapshot_hash !== actualSnapshotHash) {
    return replayFailure('SNAPSHOT_HASH_MISMATCH', 'Snapshot hash cannot be reproduced', {
      expected_snapshot_hash: snapshot.snapshot_hash,
      actual_snapshot_hash: actualSnapshotHash,
    });
  }
  return {
    ok: true,
    status: 'snapshot_verified',
    height: anchor.height,
    block_hash: anchor.block_hash,
    state_root: actualStateRoot,
    state_after: actualStateAfter,
    full_state_hash: actualFullStateHash,
    snapshot_hash: snapshot.snapshot_hash || actualSnapshotHash,
  };
}

function replayBase1BlocksFromSnapshot({ snapshot, blocks = [], includeState = false } = {}) {
  const snapshotCheck = validateBase1StateSnapshot(snapshot);
  if (!snapshotCheck.ok) return snapshotCheck;
  const incoming = Array.isArray(blocks) ? blocks : [];
  const replayState = cloneJson(snapshot.state);
  replayState.chain ||= {};
  replayState.chain.blocks ||= [];
  const anchorBlock = replayState.chain.blocks[replayState.chain.blocks.length - 1];
  if (!incoming.length) {
    return {
      ok: true,
      status: 'snapshot_replayed',
      checked_blocks: 0,
      checked_state_roots: 1,
      chain: chainSummary(replayState.chain),
      current_layer: replayState.currentLayer,
      current_step: replayState.currentStep,
      checkpoints: [
        {
          height: snapshot.anchor.height,
          block_hash: snapshot.anchor.block_hash,
          state_root: snapshot.anchor.state_root,
          current: `${replayState.currentLayer}/${replayState.currentStep}`,
        },
      ],
      replay_state: includeState ? replayState : undefined,
    };
  }
  if (incoming[0]?.previous_block_hash !== anchorBlock.block_hash) {
    return replayFailure('SNAPSHOT_BLOCK_SEQUENCE_NOT_CONNECTED', 'First block must connect to snapshot anchor', {
      anchor_hash: anchorBlock.block_hash,
      first_previous_hash: incoming[0]?.previous_block_hash || null,
    });
  }

  const checkpoints = [
    {
      height: snapshot.anchor.height,
      block_hash: snapshot.anchor.block_hash,
      state_root: snapshot.anchor.state_root,
      current: `${replayState.currentLayer}/${replayState.currentStep}`,
    },
  ];

  for (const block of incoming) {
    const previousBlock = replayState.chain.blocks[replayState.chain.blocks.length - 1];
    const blockCheck = verifyBlock(block, previousBlock);
    if (!blockCheck.ok) return replayFailure(blockCheck.code || 'SNAPSHOT_BLOCK_INVALID', 'Block failed snapshot replay verification', blockCheck);

    const applyResult = applyReplayBlock(replayState, block, previousBlock);
    if (!applyResult.ok) return applyResult;

    const actualStateRoot = computeStateRoot(replayState);
    if (block.state_root !== actualStateRoot) {
      return replayFailure('SNAPSHOT_REPLAY_STATE_ROOT_MISMATCH', 'Block state_root cannot be reproduced from snapshot state', {
        height: block.height,
        block_hash: block.block_hash,
        expected_state_root: block.state_root,
        actual_state_root: actualStateRoot,
      });
    }
    const actualStateAfter = replayBlockStateAfter(replayState);
    if (!sameJson(block.state_after, actualStateAfter)) {
      return replayFailure('SNAPSHOT_REPLAY_STATE_AFTER_MISMATCH', 'Block state_after cannot be reproduced from snapshot state', {
        height: block.height,
        block_hash: block.block_hash,
        expected_state_after: block.state_after,
        actual_state_after: actualStateAfter,
      });
    }

    replayState.chain.blocks.push(cloneJson(block));
    replayState.chain.head_hash = block.block_hash;
    replayState.chain.height = block.height;
    checkpoints.push({
      height: block.height,
      block_hash: block.block_hash,
      state_root: block.state_root,
      current: `${replayState.currentLayer}/${replayState.currentStep}`,
    });
  }

  return {
    ok: true,
    status: 'snapshot_replayed',
    snapshot_height: snapshot.anchor.height,
    checked_blocks: incoming.length,
    checked_state_roots: incoming.length + 1,
    chain: chainSummary(replayState.chain),
    current_layer: replayState.currentLayer,
    current_step: replayState.currentStep,
    generated_step_count: replayState.generatedStepKeys.length,
    solved_count: replayState.solvedSteps.length,
    reward_count: replayState.rewardLedger.length,
    transfer_count: replayState.transfers.length,
    checkpoints: checkpoints.slice(-10),
    replay_state: includeState ? replayState : undefined,
  };
}

function submitBase1Blocks({ blocks = [], source = 'unknown-peer' } = {}) {
  const incoming = Array.isArray(blocks) ? blocks : [];
  const state = loadBase1State();
  const localHead = chainSummary(state.chain);
  const receivedAt = nowIso();
  if (!incoming.length) {
    return {
      ok: true,
      adopted: false,
      status: 'empty',
      chain: localHead,
    };
  }
  if (incoming[0]?.previous_block_hash !== localHead.head_hash) {
    return {
      ok: false,
      code: 'BLOCK_SEQUENCE_NOT_CONNECTED',
      message: 'First incoming block must connect to the local head',
      local_head_hash: localHead.head_hash,
      first_previous_hash: incoming[0]?.previous_block_hash || null,
    };
  }

  const accepted = [];
  let previous = state.chain.blocks[state.chain.blocks.length - 1];
  for (const block of incoming) {
    const verifyResult = verifyBlock(block, previous);
    if (!verifyResult.ok) {
      recordBase1NetworkMessage({
        direction: 'inbound',
        peer: source,
        type: 'BLOCKS_RECEIVED',
        status: 'rejected',
        detail: {
          code: verifyResult.code,
          height: block.height,
          block_hash: block.block_hash,
        },
      });
      return {
        ok: false,
        code: verifyResult.code,
        message: 'Incoming block sequence is invalid or not connected to local head',
        accepted_count: accepted.length,
        rejected_height: block.height,
      };
    }
    accepted.push(block);
    previous = block;
  }

  const candidateHead = accepted[accepted.length - 1];
  const candidateVerify = {
    ok: true,
    height: candidateHead.height,
    head_hash: candidateHead.block_hash,
    cumulative_work_score: candidateHead.cumulative_work_score,
  };

  const replay = replayBase1BlocksFromSnapshot({
    snapshot: createBase1StateSnapshot({ state }),
    blocks: accepted,
    includeState: true,
  });
  if (!replay.ok) {
    pushBase1NetworkMessage(state, {
      direction: 'inbound',
      peer: source,
      type: 'BLOCKS_RECEIVED',
      status: 'replay_rejected',
      detail: {
        code: replay.code,
        accepted_count: accepted.length,
        head_hash: candidateVerify.head_hash,
      },
    });
    saveBase1State(state);
    return {
      ok: false,
      code: replay.code,
      message: replay.message || 'Candidate blocks could not be replayed into valid state',
      accepted_count: accepted.length,
      replay,
    };
  }

  const syncRecord = {
    id: sha256({
      type: 'mazex.base1.block_sync',
      source,
      head_hash: candidateVerify.head_hash,
      received_at: receivedAt,
    }),
    source,
    status: 'replayed',
    received_at: receivedAt,
    accepted_count: accepted.length,
    from_height: accepted[0]?.height,
    to_height: accepted[accepted.length - 1]?.height,
    head_hash: candidateVerify.head_hash,
    cumulative_work_score: candidateVerify.cumulative_work_score,
  };

  if (compareBase1StateHeads(replay.replay_state, state) > 0) {
    const adopted = normalizeBase1State(replay.replay_state);
    adopted.samples = state.samples || [];
    adopted.submissions = state.submissions || [];
    adopted.peers = state.peers || [];
    adopted.networkMessages = state.networkMessages || [];
    adopted.blockSyncInbox = [...(state.blockSyncInbox || []), { ...syncRecord, status: 'adopted_by_replay' }].slice(-100);
    adopted.witnesses = state.witnesses || [];
    recordBase1Witness(adopted, {
      source,
      blockHash: accepted[accepted.length - 1]?.block_hash,
      headHash: candidateVerify.head_hash,
      layerNo: replay.current_layer,
      stepNo: replay.current_step,
      stateRoot: accepted[accepted.length - 1]?.state_root,
      reason: 'peer_blocks_replayed_and_adopted',
      detail: {
        accepted_count: accepted.length,
        from_height: syncRecord.from_height,
        to_height: syncRecord.to_height,
      },
    });
    adopted.events ||= [];
    adopted.events.push({
      type: 'BASE1_BLOCKS_REPLAY_ADOPTED',
      created_at: receivedAt,
      source,
      from_height: syncRecord.from_height,
      to_height: syncRecord.to_height,
      head_hash: candidateVerify.head_hash,
    });
    pushBase1NetworkMessage(adopted, {
      direction: 'inbound',
      peer: source,
      type: 'BLOCKS_RECEIVED',
      status: 'adopted_by_replay',
      detail: {
        accepted_count: accepted.length,
        head_hash: candidateVerify.head_hash,
        cumulative_work_score: candidateVerify.cumulative_work_score,
      },
    });
    saveBase1State(adopted);
    return {
      ok: true,
      adopted: true,
      status: 'adopted_by_replay',
      message: 'Blocks are valid, replayed, and adopted as the stronger chain state',
      accepted_count: accepted.length,
      candidate_chain: candidateVerify,
      local_chain: localHead,
      replay: {
        ok: replay.ok,
        checked_blocks: replay.checked_blocks,
        current_layer: replay.current_layer,
        current_step: replay.current_step,
      },
      chain: chainSummary(adopted.chain),
    };
  }

  state.blockSyncInbox ||= [];
  state.blockSyncInbox.push(syncRecord);
  recordBase1Witness(state, {
    source,
    blockHash: accepted[accepted.length - 1]?.block_hash,
    headHash: candidateVerify.head_hash,
    layerNo: replay.current_layer,
    stepNo: replay.current_step,
    stateRoot: accepted[accepted.length - 1]?.state_root,
    reason: 'peer_blocks_replayed_not_adopted',
    detail: {
      accepted_count: accepted.length,
      from_height: syncRecord.from_height,
      to_height: syncRecord.to_height,
    },
  });
  if (state.blockSyncInbox.length > 100) state.blockSyncInbox = state.blockSyncInbox.slice(-100);
  pushBase1NetworkMessage(state, {
    direction: 'inbound',
    peer: source,
    type: 'BLOCKS_RECEIVED',
    status: 'replayed_not_adopted',
    detail: {
      accepted_count: accepted.length,
      head_hash: candidateVerify.head_hash,
      note: 'blocks replayed but local chain remains stronger or equal',
    },
  });
  saveBase1State(state);
  return {
    ok: true,
    adopted: false,
    status: 'replayed_not_adopted',
    message: 'Blocks are valid and replayed, but local chain remains stronger or equal',
    accepted_count: accepted.length,
    candidate_chain: candidateVerify,
    local_chain: localHead,
    replay: {
      ok: replay.ok,
      checked_blocks: replay.checked_blocks,
      current_layer: replay.current_layer,
      current_step: replay.current_step,
    },
  };
}

function verifyBase1Chain() {
  return verifyLocalChain(loadBase1State().chain);
}

function getBase1RuntimeConfig() {
  return getRuntimeConfigSnapshot();
}

module.exports = {
  BASE1_DATA_PATH,
  BASE1_STATE_VERSION,
  appendBase1ConfirmationBlock,
  base1NodeInfo,
  bootstrapBase1DefaultNetwork,
  bootstrapBase1PriorityRelays,
  bootstrapBase1SeedPeers,
  broadcastBase1SolveCandidate,
  batchBase1Sample,
  compareBase1StateHeads,
  createBase1StateSnapshot,
  discoverBase1Heads,
  buildFreshBase1State,
  getBase1Account,
  getBase1Accounts,
  getBase1ChainBlocks,
  getBase1ChainSummary,
  getBase1Events,
  getBase1BlocksSince,
  getBase1FeeSchedule,
  getBase1FragmentDownload,
  getBase1FragmentRegistry,
  getBase1FragmentRecord,
  getBase1HeadProof,
  getBase1Leaderboard,
  getBase1NetworkStatus,
  getBase1RewardLedger,
  getBase1Reveals,
  getBase1RuntimeConfig,
  getBase1SolveReceipts,
  getBase1StorageStatus: shardedStorageStatus,
  getBase1PrivateVaultStatus: privateVaultStatus,
  getBase1TimeProof,
  getBase1WitnessStats,
  getCurrentBase1Public,
  invalidSubmitFeeForStep,
  latestBase1HeadGuard,
  loadBase1State,
  makeCandidateFromOfficial,
  quarantineBase1Fragment,
  recordBase1NetworkMessage,
  receiveBase1SolveCandidatePackage,
  registerBase1Peer,
  registerBase1Fragment,
  removeBase1Peer,
  resetBase1State,
  replayBase1Chain,
  replayBase1BlocksFromSnapshot,
  rewardForStep,
  sampleBase1Point,
  saveBase1State,
  snapshotBase1State,
  syncBase1NetworkTime,
  submitFeeForStep,
  submitBase1Candidate,
  submitBase1Blocks,
  submitBase1Transfer,
  upgradeBase1Fragment,
  verifyBase1LatestHead,
  validateBase1SolveCandidatePackage,
  validateBase1StateSnapshot,
  verifyBase1Chain,
};
