#!/usr/bin/env bash
# =============================================================================
#  xOne  -  xone.sh installer (same file at /install.sh and /one.sh)  -  node manager for xOneRS
# -----------------------------------------------------------------------------
#  curl -fsSL https://xone.sh | bash                    XDC Apothem testnet (default)
#  curl -fsSL https://xone.sh | bash -s -- mainnet      XDC mainnet: explicit, prints a not-qualified warning
#                                                       or: devnet hoodi sepolia eth-mainnet
#  curl -fsSL https://xone.sh | bash -s -- status       or: stop logs update restart
#  Long flags of the XDC one.sh (--network --mode --name --client ...) still work. Safe to re-run.
# =============================================================================
set -euo pipefail

# One brace group: bash reads the whole file before running it, so a piped run never stops half-way.
{
# Release pins. linux-amd64 is v0.2.11. linux-arm64 and
# darwin-arm64 keep the v0.2.9 binary pins from the 2.1.2 installer until
# v0.2.11 builds exist for them. The published image xonesh/xone:0.2.11
# (and 0.2.10, 0.2.9) is linux/amd64 only, so --docker on other platforms is refused
# and the operator is pointed at the pinned binary path.
XONE_SH_VERSION="2.1.10"
XONE_RS_VERSION="v0.2.11"
XONE_RS_IMAGE="xonesh/xone:0.2.11"
# the same v0.2.11 image by manifest digest: with --validator --docker the key is created in, and the node
# that holds it runs from, this exact image (unless you pass --image or XONESH_IMAGE)
XONE_RS_IMAGE_DIGEST="docker.io/xonesh/xone@sha256:ee8354a837a837702cb6f9fdd8792ff96e80cd914f517b6aea6d9580453f38d5"
XONE_RS_LINUX_AMD64_SHA256="a15dcbfb933c48dd42ee1215951e2e26c31272b4bd115210cefc4f14fa5108fd"
XONE_RS_LINUX_ARM64_VERSION="v0.2.9"
XONE_RS_LINUX_ARM64_SHA256="12d4b618503d84a5d4dda840c13ec1482e2a6399d61f1c8d22c8410bd15e9333"
XONE_RS_DARWIN_ARM64_VERSION="v0.2.9"
XONE_RS_DARWIN_ARM64_SHA256="b51ea1fa99f30ae660dfa7967724ce5067ff63c0f3df3f7ca4b805fda0692a3e"
XONE_MINISIGN_PUBKEY="RWQZuv3gjviEAqM/VzzO90gjXb9JxvMhb8hY90AuJb700OOIsfZEhZ2b"   # signs each release SHA256SUMS (v0.2.11 and later)
XONESH_BASE_URL="${XONESH_BASE_URL:-https://xone.sh}"
XONESH_BIN_URL="${XONESH_BIN_URL:-$XONESH_BASE_URL/bin}"
XONESH_DL_URL="${XONESH_DL_URL:-https://dl.xone.sh}"   # xone.sh-owned release host (Cloudflare R2 bucket xone-releases)
XONESH_SEEDS_URL="${XONESH_SEEDS_URL:-$XONESH_BASE_URL/seeds}"

# ----------------------------- OUTPUT ----------------------------------------
if [ -t 1 ]; then B=$'\033[1m'; G=$'\033[32m'; Y=$'\033[33m'; R=$'\033[31m'; D=$'\033[2m'; N=$'\033[0m'; TTY=1
else B=""; G=""; Y=""; R=""; D=""; N=""; TTY=0; fi
hr(){ printf '%s\n' "--------------------------------------------------------------"; }
ok(){   printf '   %s✓%s %s\n' "$G" "$N" "$*"; }
warn(){ printf '   %s•%s %s\n' "$Y" "$N" "$*"; }
err(){  printf '   %s✗%s %s\n' "$R" "$N" "$*" >&2; }
die(){  err "$*"; exit 1; }
step(){ printf '\n%s▶ %s%s\n' "$B" "$*" "$N"; }
_abs(){ case "$1" in /*) printf '%s' "$1" ;; *) printf '%s' "$PWD/$1" ;; esac; }
need(){
  command -v "$1" >/dev/null 2>&1 && return 0
  [ -n "${3:-}" ] && telemetry_emit error "$3"
  die "$1 is required${2:+: $2}"
}
sha256_of(){ if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | awk '{print $1}'; else shasum -a 256 "$1" | awk '{print $1}'; fi; }

# ----------------------------- FLAGS -----------------------------------------
CLIENT="${CLIENT:-}"; NETWORK="${NETWORK:-}"; MODE="${NODETYPE:-}"
DRY=0; FORCE=0; YES=0; YES_VALIDATOR=0; PURGE=0; MK_KS=""; MK_PW=""; RESYNC_WHAT=""; VALIDATOR=0; SINGLE_OK=0; CONFIRM_MAINNET=0; NO_ETHSTATS=0; NO_WAIT=0
USER_MINE=""; USER_KS=""; USER_PW=""; GENESIS_ARG=""; NETID_ARG=""; BOOT_ARG=""; CHAINSPEC_ARG=""
GAP_RPC="${XDC_GAP_RPC:-}"; DATADIR_ARG=""; NAME_ARG=""; DIR_ARG=""
EL_EXTRA=""; CL_EXTRA=""; DOCKER_EXTRA=""; LOG_LINES=100; LOG_SINCE=""; PORT_ARG=""; RPCPORT_ARG=""; WSPORT_ARG=""; AUTHPORT_ARG=""; MAXPEERS_ARG=""
IMAGE="${XONESH_IMAGE:-$XONE_RS_IMAGE}"; RUNTIME="${XONESH_RUNTIME:-}"; IMAGE_FROM_USER=0
CL="${XONESH_CL:-lighthouse}"; CHECKPOINT_ARG=""; CL_HTTP_PORT="${XONESH_CL_HTTP_PORT:-5052}"; CL_P2P_PORT="${XONESH_CL_P2P_PORT:-9000}"
[ "${XONESH_DRY_RUN:-${XDC_DRY_RUN:-0}}" = "1" ] && DRY=1
# Ethstats stays on unless the operator opts out. The value is not a login.
case "${XONESH_ETHSTATS:-}" in
  0|false|no|off|FALSE|NO|OFF) NO_ETHSTATS=1 ;;
esac
# Stage telemetry is default-on, and a no-op until XONESH_TELEMETRY_URL is set.
TELEMETRY=1
XONESH_TELEMETRY_URL="${XONESH_TELEMETRY_URL:-}"
case "${XONESH_TELEMETRY:-}" in
  0|false|no|off|FALSE|NO|OFF) TELEMETRY=0 ;;
esac
case "${DO_NOT_TRACK:-}" in
  1|true|yes|TRUE|YES) TELEMETRY=0 ;;
esac
# Only the literal "internal" is forwarded. Any other value is dropped (no free text).
case "${XONESH_COHORT:-}" in
  internal) COHORT=internal ;;
  *) COHORT="" ;;
esac
ACTION=""
val(){ if [ $# -lt 2 ] || [ -z "$2" ]; then die "$1 requires a value"; fi; printf '%s' "$2"; }
while [ $# -gt 0 ]; do
  case "$1" in
    --client|-c)          CLIENT="$(val "$@")"; shift 2 ;;
    --network|-n)         NETWORK="$(val "$@")"; shift 2 ;;
    --tail)               LOG_LINES="$(val "$@")"; shift 2 ;;
    --el-extra)           EL_EXTRA="$(val "$@")"; shift 2 ;;
    --cl-extra)           CL_EXTRA="$(val "$@")"; shift 2 ;;
    --docker-extra)       DOCKER_EXTRA="$(val "$@")"; shift 2 ;;
    --since)              LOG_SINCE="$(val "$@")"; shift 2 ;;
    --mode|--nodetype|-m) MODE="$(val "$@")"; shift 2 ;;
    --name)               NAME_ARG="$(val "$@")"; shift 2 ;;
    --dir)                DIR_ARG="$(_abs "$(val "$@")")"; shift 2 ;;
    --datadir)            DATADIR_ARG="$(_abs "$(val "$@")")"; shift 2 ;;
    --dry-run)            DRY=1; shift ;;
    --force)              FORCE=1; shift ;;
    --yes|-y)             YES=1; shift ;;
    --yes-validator)      YES_VALIDATOR=1; shift ;;
    --purge)              PURGE=1; shift ;;
    --validator)          VALIDATOR=1; shift ;;
    --i-understand-single-signer) SINGLE_OK=1; shift ;;
    --confirm-mainnet-validator)  CONFIRM_MAINNET=1; shift ;;
    --mine)               VALIDATOR=1; case "${2:-}" in ""|-*) shift ;; *) USER_MINE="$2"; shift 2 ;; esac ;;
    --keystore)           USER_KS="$(_abs "$(val "$@")")"; shift 2 ;;
    --password-file)      USER_PW="$(_abs "$(val "$@")")"; shift 2 ;;
    --genesis)            GENESIS_ARG="$(val "$@")"; shift 2 ;;
    --chainspec)          CHAINSPEC_ARG="$(_abs "$(val "$@")")"; shift 2 ;;
    --networkid)          NETID_ARG="$(val "$@")"; shift 2 ;;
    --bootnodes)          BOOT_ARG="$(val "$@")"; shift 2 ;;
    --gap-rpc)            GAP_RPC="$(val "$@")"; shift 2 ;;
    --port)               PORT_ARG="$(val "$@")"; shift 2 ;;
    --rpcport)            RPCPORT_ARG="$(val "$@")"; shift 2 ;;
    --wsport)             WSPORT_ARG="$(val "$@")"; shift 2 ;;
    --authrpc-port)       AUTHPORT_ARG="$(val "$@")"; shift 2 ;;
    --maxpeers)           MAXPEERS_ARG="$(val "$@")"; shift 2 ;;
    --image)              IMAGE="$(val "$@")"; IMAGE_FROM_USER=1; RUNTIME=docker; shift 2 ;;
    --docker)             RUNTIME=docker; shift ;;
    --binary)             RUNTIME=binary; shift ;;
    --cl)                 CL="$(val "$@")"; shift 2 ;;
    --checkpoint-url)     CHECKPOINT_ARG="$(val "$@")"; shift 2 ;;
    --cl-http-port)       CL_HTTP_PORT="$(val "$@")"; shift 2 ;;
    --cl-p2p-port)        CL_P2P_PORT="$(val "$@")"; shift 2 ;;
    --no-ethstats)        NO_ETHSTATS=1; shift ;;
    --no-telemetry)       TELEMETRY=0; shift ;;
    --no-wait)            NO_WAIT=1; shift ;;
    --no-snapshot|--no-snap) shift ;;   # accepted for one.sh compatibility: xOneRS has no published snapshot
    -h|--help|help)       ACTION="help"; shift ;;
    -V|--version)         ACTION="version"; shift ;;
    --)                   shift; [ $# -gt 0 ] && ACTION="${ACTION:-$1}"; break ;;
    -*)                   die "Unknown flag '$1'. Run with --help." ;;
    *)
      case "$1" in
        mainnet|xdc|xdc-mainnet|xinfin|50|apothem|testnet|xdc-testnet|51|net2040|2040|devnet|5551|private|custom|\
        eth-mainnet|ethereum|eth|1|sepolia|11155111|hoodi|560048|holesky|17000|ephemery|pq|pqnet|pq-devnet|pq-devnet-1|701522068|quantum|post-quantum)
          NETWORK="$1" ;;
        el|cl|all) [ "$ACTION" = resync ] || die "Unexpected '$1'. Run with --help."; RESYNC_WHAT="$1" ;;
        *) [ -z "$ACTION" ] || die "Unexpected '$1'. Run with --help."; ACTION="$1" ;;
      esac; shift ;;
  esac
done
ACTION="${ACTION:-start}"
case "$ACTION" in
  setup|init|download) ACTION=setup ;; start|up) ACTION=start ;; stop|down) ACTION=stop ;;
  browser-plan) DRY=1 ;;
  uninstall|remove) ACTION=uninstall ;;
  restart|status|logs|update|resync|rollback|clients|networks|version|help|flags) : ;;
  info) ACTION=status ;; log) ACTION=logs ;; matrix) ACTION=clients ;; upgrade) ACTION=update ;;
  attach|console) ACTION=attach ;;
  *) die "Unknown command '$ACTION'. Commands: start stop restart status logs update resync rollback uninstall setup networks flags version help" ;;
esac

usage(){
  cat <<USAGE
${B}xOne node installer ${XONE_SH_VERSION}${N}   https://xone.sh

  curl -fsSL https://xone.sh | bash -s -- [network] [command] [flags]

  network   apothem (default, XDC 51)  mainnet (XDC 50, not yet qualified)  devnet
            hoodi  sepolia  eth-mainnet  pq-devnet-1  (Ethereum followers with Lighthouse in Docker)
  command   start (default)  stop  restart  status  logs  update  resync [el|cl|all]  rollback  uninstall [--purge]  networks  flags  browser-plan

  Default: XDC Apothem testnet, snap sync. xOneRS is not yet qualified for XDC mainnet, so mainnet
  must be named: it prints a warning, then does a full sync (snap needs XDC_SNAP_PINS).
  The default is a follower: no node key and no password file are created, and the client gets no
  --keystore, --password or --miner.etherbase, unless you pass --validator or --keystore.
  Re-running uses the existing node directory.

  curl -fsSL https://xone.sh | bash                      start Apothem testnet
  curl -fsSL https://xone.sh | bash -s -- mainnet        start XDC mainnet (not yet qualified, see the warning)
  curl -fsSL https://xone.sh | bash -s -- hoodi          start Ethereum Hoodi
  curl -fsSL https://xone.sh | bash -s -- status         (or: cd xone-apothem && ./one.sh status)

  Common flags: --name NAME  --dir DIR  --mode snap|full  --dry-run  --docker
  All flags: curl -fsSL https://xone.sh | bash -s -- flags
USAGE
}
flags(){
  cat <<FLAGS
  --network N (or a bare name)  --client xone-rs  --mode XDC: snap|full  ETH: minimal|full|archive|snap
  --name NAME (default: xone-rs-<network>-<8 hex chars>, not the hostname)  --dir DIR (default ./xone-<network>)  --datadir DIR
  --dry-run   print every step and command; download, create and start nothing
  logs [--tail N] [--since 1h]   last N lines (default 100), then follow; --since needs --docker
  resync: --yes (no prompt)  --yes-validator (allow it on a validator node; its safety record is kept)
  uninstall: --purge (also delete chain data and keys)  --yes (no prompt)
  --force     start even if --network/--genesis/--networkid differ from the chain already in the node's datadir
  browser-plan   print a built-in network's browser launch plan as JSON
  --port --rpcport --wsport --authrpc-port --maxpeers  --bootnodes enode://..,..  --gap-rpc URL
  --keystore DIR [--mine ADDR]   set the coinbase from your own keystore; the node is not given the key
  --keystore DIR --password-file F --validator ...   produce blocks with your own key. The keystore file and F
                must be mode 0600 or 0400 and owned by you. With --docker, DIR and F alone are mounted read-only;
                F is pinned by inode, so re-run the installer after replacing F by rename
  --validator --i-understand-single-signer   create a key and enable block production (XDC testnets; mainnet is refused by xOneRS).
                The key is made by the pinned xOneRS binary (account new). Its generated password is stored
                in PLAINTEXT (mode 0600) at DIR/validator/password.txt
                so the node can start unattended; add --password-file F (a path that does not exist yet,
                e.g. on a tmpfs or secrets mount) to store it at F instead
  --genesis path|url --networkid N --chainspec F   (private network)
  --binary  run the pinned binary (switches back a node dir that remembers docker)
  --docker  --image IMG (default $XONE_RS_IMAGE)   run the image instead of the binary
  --el-extra "ARGS"  --cl-extra "ARGS"   extra client flags, appended last (split on spaces; no quotes, no shell)
  --docker-extra "ARGS"   extra docker run options, e.g. "--memory 8g --cpus 4" (all three are kept in .one-node;
                pass none to clear one). Allowed: letters, digits, spaces and _ . / : % @ + = , ~ [ ] -
  --cl lighthouse --checkpoint-url URL --cl-http-port 5052 --cl-p2p-port 9000   (Ethereum)
  --no-ethstats   do not report to the XDC stats page (same as XONESH_ETHSTATS=0)
  --no-telemetry  do not send anonymous installer stage events (same as XONESH_TELEMETRY=0 or DO_NOT_TRACK=1)
  --no-wait       do not wait for the first RPC answer (treatment arm). Ctrl-C during the wait leaves the node running
FLAGS
}
[ "$ACTION" = help ] && { usage; exit 0; }
[ "$ACTION" = flags ] && { flags; exit 0; }

# ----------------------------- NODE DIR MEMORY ---------------------------------
# A node dir remembers what start/setup ran (.one-node), so ./one.sh status|stop there needs no flags. Parsed, never sourced.
_self_dir=""
if [ -n "${BASH_SOURCE[0]:-}" ] && [ -f "${BASH_SOURCE[0]}" ]; then _self_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; fi
_marker_dir="${DIR_ARG:-${XONESH_DIR:-$_self_dir}}"
if [ -n "$_marker_dir" ] && [ -f "$_marker_dir/.one-node" ]; then
  _mkraw(){ sed -n "s/^$1=\\(.*\\)\$/\\1/p" "$_marker_dir/.one-node" | head -1; }
  _mk(){ _mkraw "$1" | tr -cd "$2"; }
  _safe='A-Za-z0-9_./:%@+=,-'
  _mk_net="$(_mk ONE_NETWORK 'a-z0-9-')"; _mk_gen="$(_mk ONE_GENESIS "$_safe")"; _mk_netid="$(_mk ONE_NETID '0-9')"
  [ -n "$NETWORK" ]       || NETWORK="$(_mk ONE_NETWORK 'a-z0-9-')"
  [ -n "$MODE" ]          || MODE="$(_mk ONE_MODE 'a-z')"
  [ -n "$NAME_ARG" ]      || NAME_ARG="$(_mk ONE_NAME "$_safe")"
  if [ -z "$DATADIR_ARG" ]; then
    DATADIR_ARG="$(_mk ONE_DATADIR "$_safe")"
    # a path restored differently from what was saved could point at another directory: stop instead
    [ "$DATADIR_ARG" = "$(_mkraw ONE_DATADIR)" ] || die "$_marker_dir/.one-node: ONE_DATADIR has characters this installer cannot restore. Pass --datadir explicitly."
  fi
  [ -n "$RUNTIME" ]       || RUNTIME="$(_mk ONE_RUNTIME 'a-z')"
  MK_KS="$(_mkraw ONE_KEYSTORE)"; MK_PW="$(_mkraw ONE_PASSWORD_FILE)"   # only to protect them from resync/uninstall
  [ -n "$GENESIS_ARG" ]   || GENESIS_ARG="$(_mk ONE_GENESIS "$_safe")"
  [ -n "$NETID_ARG" ]     || NETID_ARG="$(_mk ONE_NETID '0-9')"
  [ -n "$BOOT_ARG" ]      || BOOT_ARG="$(_mk ONE_BOOTNODES "$_safe")"
  [ -n "$CHAINSPEC_ARG" ] || CHAINSPEC_ARG="$(_mk ONE_CHAINSPEC "$_safe")"
  [ -n "$PORT_ARG" ]      || PORT_ARG="$(_mk ONE_PORT '0-9')"
  [ -n "$RPCPORT_ARG" ]   || RPCPORT_ARG="$(_mk ONE_RPCPORT '0-9')"
  [ -n "$WSPORT_ARG" ]    || WSPORT_ARG="$(_mk ONE_WSPORT '0-9')"
  [ -n "$AUTHPORT_ARG" ]  || AUTHPORT_ARG="$(_mk ONE_AUTHPORT '0-9')"
  [ -n "$CHECKPOINT_ARG" ] || CHECKPOINT_ARG="$(_mk ONE_CHECKPOINT "$_safe")"
  [ -n "$EL_EXTRA" ]      || EL_EXTRA="$(_mkraw ONE_EL_EXTRA)"
  [ -n "$CL_EXTRA" ]      || CL_EXTRA="$(_mkraw ONE_CL_EXTRA)"
  [ -n "$DOCKER_EXTRA" ]  || DOCKER_EXTRA="$(_mkraw ONE_DOCKER_EXTRA)"
  DIR_ARG="$_marker_dir"
fi
# Extras (flag or marker): "none" clears; anything outside this set is refused, so a restart gets the same words.
_extra_ok(){
  case "$2" in *[!A-Za-z0-9_./:%@+=\ ,~\[\]-]*)
    die "$1: only letters, digits, spaces and _ . / : % @ + = , ~ [ ] - are allowed (use $1 none to clear)" ;; esac
}
[ "$EL_EXTRA" != none ] || EL_EXTRA=""; _extra_ok --el-extra "$EL_EXTRA"
[ "$CL_EXTRA" != none ] || CL_EXTRA=""; _extra_ok --cl-extra "$CL_EXTRA"
[ "$DOCKER_EXTRA" != none ] || DOCKER_EXTRA=""; _extra_ok --docker-extra "$DOCKER_EXTRA"

# ----------------------------- CLIENT ----------------------------------------
case "${CLIENT:-xone-rs}" in
  xone-rs|xoners|xone|xOneRS|rs) CLIENT="xone-rs" ;;
  geth|erigon|reth|besu|nethermind|xone-ts|xone-py|xone-c|all)
    die "xone.sh installs xOneRS (--client xone-rs). '$CLIENT' is not distributed from xone.sh." ;;
  *) die "Unknown client '$CLIENT'. Valid: xone-rs" ;;
esac

# ----------------------------- NETWORKS --------------------------------------
# KIND=xdc|eth. Chain ids and genesis hashes are the ones the pinned binary reports (xone-rs checkconfig).
NETWORK="${NETWORK:-apothem}"   # bare run = Apothem; mainnet needs the explicit word (or --network mainnet)
not_available(){ err "Network '$1' is not available from xone.sh yet: $2"; err "Run: curl -fsSL https://xone.sh/install.sh | bash -s -- networks"; exit 2; }
KIND=xdc; CHAIN_ARGS=(); NETID=""; NET_LABEL=""; CHECKPOINT_DEFAULT=""
case "$NETWORK" in
  mainnet|xdc|xdc-mainnet|xinfin|50) NETWORK=mainnet; NET_LABEL="XDC MAINNET"; NETID=50;   CHAIN_ARGS=(--network mainnet) ;;
  apothem|testnet|xdc-testnet|51)    NETWORK=apothem; NET_LABEL="XDC APOTHEM"; NETID=51;   CHAIN_ARGS=(--network apothem) ;;
  net2040|2040)
    # net2040 was shut down on 1 Dec 2026. Only stop/status/logs still work, so an existing node can be shut down.
    case "$ACTION" in
      stop|status|logs)
        NETWORK=net2040; NET_LABEL="XDC NET2040 (shut down)"; NETID=2040; CHAIN_ARGS=(--network net2040)
        warn "net2040 has been shut down (1 Dec 2026); use apothem. Run: curl -fsSL https://xone.sh | bash" ;;
      *) err "net2040 has been shut down (1 Dec 2026); use apothem."
         err "Run: curl -fsSL https://xone.sh | bash   (XDC Apothem testnet, the default)"
         err "To stop a node still running on net2040: curl -fsSL https://xone.sh | bash -s -- stop --dir <node dir>"
         exit 2 ;;
    esac ;;
  devnet|5551)                       NETWORK=devnet;  NET_LABEL="XDC DEVNET";  NETID=5551; CHAIN_ARGS=(--network devnet) ;;
  private|custom)                    NETWORK=private; NET_LABEL="PRIVATE";     NETID="$NETID_ARG" ;;
  eth-mainnet|ethereum|eth|1)        NETWORK=eth-mainnet; KIND=eth; NET_LABEL="ETHEREUM MAINNET"; NETID=1;        CHAIN_ARGS=(--chain mainnet); CHECKPOINT_DEFAULT="https://mainnet.checkpoint.sigp.io"; CL_NET=mainnet ;;
  sepolia|11155111)                  NETWORK=sepolia; KIND=eth; NET_LABEL="ETHEREUM SEPOLIA";     NETID=11155111; CHAIN_ARGS=(--chain sepolia); CHECKPOINT_DEFAULT="https://checkpoint-sync.sepolia.ethpandaops.io"; CL_NET=sepolia ;;
  hoodi|560048)                      NETWORK=hoodi;   KIND=eth; NET_LABEL="ETHEREUM HOODI";       NETID=560048;   CHAIN_ARGS=(--chain hoodi);   CHECKPOINT_DEFAULT="https://checkpoint-sync.hoodi.ethpandaops.io"; CL_NET=hoodi ;;
  holesky|17000)   not_available holesky "Holesky is deprecated upstream (replaced by Hoodi) and the pinned xOneRS build has no Holesky chain. Use --network hoodi." ;;
  ephemery)        not_available ephemery "the pinned xOneRS build has no Ephemery chain (it resets on a schedule and needs a fresh genesis each cycle)." ;;
  pq|pqnet|pq-devnet|pq-devnet-1|701522068|quantum|post-quantum)
    NETWORK=pq-devnet-1; KIND=eth; NET_LABEL="ETHEREUM PQ-DEVNET-1"; NETID=701522068
    CHECKPOINT_DEFAULT="https://beacon.pq-devnet-1.ethpandaops.io"; CL_NET=pq-devnet-1 ;;
  *) die "Unknown network '$NETWORK'. Run: bash -s -- networks" ;;
esac
CL_NET="${CL_NET:-}"

# ----------------------------- MODE ------------------------------------------
if [ "$KIND" = xdc ]; then
  case "${MODE:-}" in
    "")
      # xOneRS refuses mainnet snap sync without --snap.pins. Default
      # mainnet to full when XDC_SNAP_PINS is unset so the next release does not
      # break installs. Apothem (and an explicit --mode) are unchanged.
      if [ "$NETWORK" = mainnet ] && [ -z "${XDC_SNAP_PINS:-}" ]; then
        MODE=full; _mode_default=1
        case "$ACTION" in start|setup)
          warn "mainnet snap sync needs XDC_SNAP_PINS; defaulting to full. Set XDC_SNAP_PINS to opt into snap." ;;
        esac
      else
        MODE=snap; _mode_default=1
      fi
      ;;
    snap|fast) MODE=snap; _mode_default=0 ;;
    full) _mode_default=0 ;;
    *) die "XDC networks support --mode snap|full (got '$MODE')." ;;
  esac
  case "$NETWORK" in
    devnet|private) [ "$MODE" = snap ] && { [ "$_mode_default" = 1 ] || warn "$NETWORK peers serve no snap state: using --mode full"; MODE=full; } ;;
  esac
else
  case "${MODE:-}" in
    "") if [ "$NETWORK" = pq-devnet-1 ]; then MODE=snap; else MODE=minimal; fi ;;
    minimal|full|archive) : ;;
    snap|fast) MODE=snap ;;
    *) die "Ethereum networks support --mode minimal|full|archive|snap (got '$MODE')." ;;
  esac
fi

# ----------------------------- VALIDATOR GATE ------------------------------------
if [ "$VALIDATOR" = 1 ]; then
  [ "$KIND" = xdc ] || die "--validator is for XDC networks. Ethereum validators run in the consensus client, not here."
  [ "$NETWORK" = mainnet ] && die "--validator: xOneRS release builds refuse block production on XDC mainnet (chain 50)."
  printf '\n   %s! A validator key must NEVER produce on two nodes at once (double-sign).%s\n' "$Y" "$N"
  case "$NETWORK" in apothem) [ "$SINGLE_OK" = 1 ] || die "--validator on $NETWORK needs --i-understand-single-signer (this node becomes the ONLY producer for its key)." ;; esac
fi
: "$CONFIRM_MAINNET"
# docker: a node that creates or holds a key runs the image pinned by digest, unless you chose an image
IMAGE_USER=0; if [ "$IMAGE_FROM_USER" = 1 ] || [ -n "${XONESH_IMAGE:-}" ]; then IMAGE_USER=1; fi
if [ "$VALIDATOR" = 1 ] && [ "$IMAGE_USER" = 0 ]; then IMAGE="$XONE_RS_IMAGE_DIGEST"; fi

# ----------------------------- LAYOUT & PORTS ------------------------------------
DIR="${DIR_ARG:-${XONESH_DIR:-$PWD/xone-$NETWORK}}"
DATADIR="${DATADIR_ARG:-$DIR/data}"
# A genesis URL as given; a path resolved, so the same file via another path compares equal.
_genesis_id(){
  case "$1" in ""|https://*|http://*) printf '%s' "$1" ;;
    *) realpath "$1" 2>/dev/null || readlink -f "$1" 2>/dev/null || _abs "$1" ;; esac
}
# Explicit flags that select another chain than the node dir's marker must not reuse its datadir.
case "$ACTION" in start|setup|restart|update)
  if [ -n "${_mk_net:-}" ] && [ "$FORCE" != 1 ] && [ -n "$(ls -A "$DATADIR" 2>/dev/null)" ]; then
    _clash=""
    [ "$NETWORK" = "$_mk_net" ] || _clash="--network"
    [ "$(_genesis_id "$GENESIS_ARG")" = "$(_genesis_id "$_mk_gen")" ] || _clash="${_clash:+$_clash and }--genesis"
    # built-in networks ignore --networkid
    [ "$NETWORK" != private ] || [ "$NETID_ARG" = "$_mk_netid" ] || _clash="${_clash:+$_clash and }--networkid"
    [ -z "$_clash" ] || die "$DATADIR holds data of network '$_mk_net'${_mk_netid:+ (networkid $_mk_netid)}; the flag $_clash selects '$NETWORK'${NETID_ARG:+ (networkid $NETID_ARG)}. Use another --dir for $NETWORK, or pass --force to reuse this datadir."
  fi ;;
esac
BIN="$DIR/xone-rs"; LOGDIR="$DIR/logs"; LOG="$LOGDIR/node.log"; PIDFILE="$DIR/node.pid"
JWT="$DIR/jwt.hex"; CL_DIR="$DIR/cl"
PQ_CONFIG="$DIR/pq-devnet-1"
# Default node name is a random id kept in the node dir. It is not the hostname.
persist_anon_id(){
  [ "$DRY" = 1 ] && return 0
  [ -n "$NAME_ARG" ] && return 0
  [ "${#ANON_ID}" = 8 ] || return 0
  mkdir -p "$DIR"
  printf '%s\n' "$ANON_ID" > "$DIR/.anon-id"
}
resolve_node_name(){
  ANON_ID=""
  if [ -n "$NAME_ARG" ]; then
    NODE_NAME="$NAME_ARG"
  else
    if [ -f "$DIR/.anon-id" ]; then
      IFS= read -r ANON_ID < "$DIR/.anon-id" || ANON_ID=""
      ANON_ID=$(printf '%s' "$ANON_ID" | tr -cd 'a-f0-9')
      ANON_ID="${ANON_ID:0:8}"
      [ "${#ANON_ID}" = 8 ] || ANON_ID=""
    fi
    if [ -z "$ANON_ID" ]; then
      if [ -r /dev/urandom ]; then ANON_ID=$(od -An -N4 -tx1 /dev/urandom | tr -d ' \n')
      else ANON_ID=$(printf '%04x%04x' "${RANDOM:-0}" "$$"); fi
      ANON_ID=$(printf '%s' "$ANON_ID" | tr -cd 'a-f0-9')
      ANON_ID="${ANON_ID:0:8}"
    fi
    [ "${#ANON_ID}" = 8 ] || die "could not make an anonymous node id"
    NODE_NAME="xone-rs-${NETWORK}-${ANON_ID}"
  fi
  case "$NODE_NAME" in *[!A-Za-z0-9_.-]*) die "--name may hold letters, digits, '.', '_' and '-' only." ;; esac
  EL_CONTAINER="xone-el-$(printf '%s' "$NODE_NAME" | tr -cd 'a-zA-Z0-9_.-' | cut -c1-60)"
  CL_CONTAINER="xone-cl-$(printf '%s' "$NODE_NAME" | tr -cd 'a-zA-Z0-9_.-' | cut -c1-60)"
}
resolve_node_name
if [ "$KIND" = eth ]; then RPC_PORT=8545; WS_PORT=8546; P2P_PORT=30303; AUTH_PORT=8551
else RPC_PORT=8625; WS_PORT=8626; P2P_PORT=30366; AUTH_PORT=8627; fi
RPC_PORT="${RPCPORT_ARG:-$RPC_PORT}"; WS_PORT="${WSPORT_ARG:-$WS_PORT}"; P2P_PORT="${PORT_ARG:-$P2P_PORT}"; AUTH_PORT="${AUTHPORT_ARG:-$AUTH_PORT}"
MAXPEERS="${MAXPEERS_ARG:-50}"
for _p in "$RPC_PORT" "$WS_PORT" "$P2P_PORT" "$AUTH_PORT" "$MAXPEERS" "$CL_HTTP_PORT" "$CL_P2P_PORT"; do
  case "$_p" in ''|*[!0-9]*) die "ports and --maxpeers must be numbers (got '$_p')" ;; esac
done
CHECKPOINT_URL="${CHECKPOINT_ARG:-$CHECKPOINT_DEFAULT}"
# Public-tier ethstats login. This word is not a credential: the stats server
# has to accept it for ordinary node reports. A private login, if the operator
# has one, is read from the environment and is never written into this script.
ETHSTATS_LOGIN="${XONESH_ETHSTATS_SECRET:-public}"
ETHSTATS_TARGET="${XONESH_ETHSTATS_HOST:-stats.xdcindia.com:443}"

# ----------------------------- PLATFORM & PINNED RELEASE -------------------------
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
case "$(uname -m)" in x86_64|amd64) ARCH=amd64 ;; arm64|aarch64) ARCH=arm64 ;; *) ARCH="$(uname -m)" ;; esac
PLATFORM="$OS-$ARCH"
# Optional override for installer checks and the platform dry-run matrix.
if [ -n "${XONESH_PLATFORM:-}" ]; then
  PLATFORM="$XONESH_PLATFORM"
  OS="${PLATFORM%-*}"
  ARCH="${PLATFORM#*-}"
fi
# Pinned xOneRS fallback from the release-pin block above. linux-amd64 is
# v0.2.11. linux-arm64 and darwin-arm64 keep the v0.2.9 pins from the 2.1.2
# installer until apply_latest_manifest sees a v0.2.11 file for that platform
# in $XONESH_DL_URL/xone/latest.json whose sha256 the minisign-signed release
# SHA256SUMS lists. The downloaded binary is still sha256-checked.
BIN_URL=""
case "$PLATFORM" in
  linux-amd64)  BIN_FILE="xone-rs-${XONE_RS_VERSION}-linux-amd64"
                BIN_URL="$XONESH_DL_URL/xone/${XONE_RS_VERSION}/$BIN_FILE"
                BIN_SHA="$XONE_RS_LINUX_AMD64_SHA256" ;;
  linux-arm64)  XONE_RS_VERSION="$XONE_RS_LINUX_ARM64_VERSION"
                BIN_FILE="xone-rs-${XONE_RS_VERSION}-linux-arm64"
                BIN_URL="$XONESH_DL_URL/xone/${XONE_RS_VERSION}/$BIN_FILE"
                BIN_SHA="$XONE_RS_LINUX_ARM64_SHA256" ;;
  darwin-arm64) XONE_RS_VERSION="$XONE_RS_DARWIN_ARM64_VERSION"
                BIN_FILE="xone-rs-${XONE_RS_VERSION}-darwin-arm64"
                BIN_URL="$XONESH_DL_URL/xone/${XONE_RS_VERSION}/$BIN_FILE"
                BIN_SHA="$XONE_RS_DARWIN_ARM64_SHA256" ;;
  *) BIN_FILE=""; BIN_SHA="" ;;
esac
# First top-level JSON string for key (bash-only; macOS has no python3 by default).
_json_string() {
  awk -v k="$2" '
    {
      if (match($0, "\"" k "\"[ \\t]*:[ \\t]*\"[^\"]*\"")) {
        s = substr($0, RSTART, RLENGTH)
        sub(/^"[^"]+"[[:blank:]]*:[[:blank:]]*"/, "", s)
        sub(/"$/, "", s)
        print s
        exit
      }
    }
  ' "$1"
}
# sha256 for a files[].name entry in latest.json (pretty or compact).
_json_sha_for() {
  awk -v want="$2" '
    {
      if (match($0, /"name"[ \t]*:[ \t]*"[^"]+"/)) {
        n = substr($0, RSTART, RLENGTH)
        sub(/.*"name"[ \t]*:[ \t]*"/, "", n)
        sub(/".*/, "", n)
      }
      if (n == want && match($0, /"sha256"[ \t]*:[ \t]*"[^"]+"/)) {
        s = substr($0, RSTART, RLENGTH)
        sub(/.*"sha256"[ \t]*:[ \t]*"/, "", s)
        sub(/".*/, "", s)
        print s
        exit
      }
    }
  ' "$1"
}
# true if version $1 < $2 (vX.Y.Z, both already validated)
_ver_lt() {
  local IFS=. i a b
  read -r -a a <<< "${1#v}"; read -r -a b <<< "${2#v}"
  for i in 0 1 2; do
    [ "$((10#${a[i]:-0}))" -lt "$((10#${b[i]:-0}))" ] && return 0
    [ "$((10#${a[i]:-0}))" -gt "$((10#${b[i]:-0}))" ] && return 1
  done
  return 1
}
BIN_SHA_FROM="pinned in this script"
apply_latest_manifest() {
  local src tmp tag base name sha
  src="${XONESH_LATEST_JSON:-$XONESH_DL_URL/xone/latest.json}"
  tmp="$(mktemp)" || return 0
  if [ -f "$src" ]; then
    cat "$src" >"$tmp" || { rm -f "$tmp"; return 0; }
  else
    curl -fsSL --max-time 20 "$src" >"$tmp" 2>/dev/null || { rm -f "$tmp"; return 0; }
  fi
  tag="$(_json_string "$tmp" tag)"
  [ -n "$tag" ] || tag="v$(_json_string "$tmp" version)"
  # strict: nothing but vX.Y.Z is used or printed (a raw tag could carry terminal escapes)
  printf '%s' "$tag" | grep -qxE 'v[0-9]+\.[0-9]+\.[0-9]+' || { rm -f "$tmp"; return 0; }
  if _ver_lt "$tag" "$XONE_RS_VERSION"; then
    rm -f "$tmp"; warn "ignoring latest.json ($tag): older than the built-in pin $XONE_RS_VERSION."; return 0
  fi
  name="xone-rs-${tag}-${PLATFORM}"
  sha="$(_json_sha_for "$tmp" "$name")"
  base="$(_json_string "$tmp" base)"
  rm -f "$tmp"
  [ "${#sha}" -eq 64 ] || return 0
  printf '%s' "$sha" | grep -qxE '[0-9a-f]{64}' || return 0
  [ "$name" = "$BIN_FILE" ] && [ "$sha" = "$BIN_SHA" ] && return 0   # same as the built-in pin
  case "$base" in https://*) ;; *) base="$XONESH_DL_URL/xone/${tag}" ;; esac   # https only, else the default host
  # latest.json is unsigned: use it only if that release's SHA256SUMS verifies
  # with the pinned minisign key and lists $sha for $name. Else keep the built-in pins.
  tmp="$(mktemp -d)" || return 0
  if ! command -v "${XONESH_MINISIGN:-minisign}" >/dev/null 2>&1 \
    || ! curl -fsSL --max-time 20 "${base%/}/SHA256SUMS" -o "$tmp/SHA256SUMS" 2>/dev/null \
    || ! curl -fsSL --max-time 20 "${base%/}/SHA256SUMS.minisig" -o "$tmp/SHA256SUMS.minisig" 2>/dev/null \
    || ! "${XONESH_MINISIGN:-minisign}" -Vq -P "$XONE_MINISIGN_PUBKEY" -m "$tmp/SHA256SUMS" -x "$tmp/SHA256SUMS.minisig" >/dev/null 2>&1 \
    || [ "$(awk -v f="$name" '$2 == f {print $1; exit}' "$tmp/SHA256SUMS")" != "$sha" ]; then
    rm -rf "$tmp"
    warn "ignoring latest.json ($tag): no minisign, or its SHA256SUMS signature or sha256 does not verify. Using the built-in pin $BIN_FILE."
    return 0
  fi
  rm -rf "$tmp"
  XONE_RS_VERSION="$tag"
  BIN_FILE="$name"
  BIN_URL="${base%/}/$name"
  BIN_SHA="$sha"
  BIN_SHA_FROM="from latest.json, listed in the signed SHA256SUMS"
}
[ "$ACTION" = browser-plan ] || apply_latest_manifest
# runtime: the pinned binary where one is published, else the public image (docker)
if [ -z "$RUNTIME" ]; then if [ -n "$BIN_FILE" ]; then RUNTIME=binary; else RUNTIME=docker; fi; fi
case "$RUNTIME" in binary|docker) : ;; *) die "XONESH_RUNTIME must be binary or docker" ;; esac
LIGHTHOUSE_IMAGE="${XONESH_LIGHTHOUSE_IMAGE:-sigp/lighthouse:v8.3.2@sha256:6b83ea5d5b5b183536d7dd45d1db1b6d4c8aa038eb7bbd0f336a2e175e9fe28a}"
if [ "$NETWORK" = pq-devnet-1 ]; then
  LIGHTHOUSE_IMAGE="${XONESH_LIGHTHOUSE_IMAGE:-ethpandaops/lighthouse@sha256:dfd0d001f7063ef9091741783fbe6763c1461392eb267db9c84f43b5eada881f}"
fi
PQ_METADATA="https://raw.githubusercontent.com/ethpandaops/pq-devnets/e2d78260b02a5be6800f1d298cfa8041fc91a942/network-configs/devnet-1/metadata"
PQ_GENESIS_SHA256="34a0bb14b4c79b81a637fdc72c3b781e60d14179f0923c6a303a4083dbd35b12"

# ----------------------------- PEERS (from the XDCIndia one.sh, unchanged) --------
SEED_HOST="${XDC_SEED_HOST-seed.xdc.dev}"
seed_enodes(){
  [ -n "$SEED_HOST" ] || return 0
  case "$1" in
    mainnet) echo "enode://d17e8d00db894bb0a77d58889548dcb37dd2c004afe1e05312eaa33b545dc9fe9f2d7811c36edf11ec46577c1c708400d13b3c7ce45523c1f2d345eae093208a@$SEED_HOST:30306" ;;
    apothem) echo "enode://10f3cfe53b64b93aab58250295173f4192dbb15b66ea1be974e5aa12b56a7abe3049e8328856f3867884d2942ba0ecc35c29cd4bbd9a01ace193fb892e8cce33@$SEED_HOST:30950,enode://493430448fe489e3de752ac8d9f7bce3f35ddbb0e1ead9698fadea97cafbd53be4bb5fb4fca59156eb4441835f1e0c0c3a33f64cb6565f05c597229e701fcfb3@$SEED_HOST:30410" ;;
    devnet)  echo "enode://0d3a30a74aa8dde6916cf8c1662cbdde35e63c4848ee65289140a8a7fbf64b81551a514bf302c585bead60e836c36a5544737321ea268a247736b5c73d888791@$SEED_HOST:30302" ;;
  esac
}
APOTHEM_MODERN_PEERS="enode://5929639e1f64c5cf12627712075ace463299d9c1fe1c3ecd6c624ffe82fd1504b322e4a7660e8fe1ee28785a3998924170785b8fa2cc94c5158a5ac9ccb5bbc2@65.21.71.4:30910,enode://bd71cdc87f50a6dd829cde5475d12aaa7bfc15377e9fce5424bce45ed9f8f86e8c2a171d1d846b00f7306c9b7aa8ef60219465f68e4de69a457897175fb270a9@65.21.71.4:30930,enode://df7730cf6e79d3edc1a4d0c33f62874ed0c7ae32e3ef886c368763208d064017002f07b8c1af36586569c6d3cdfe60ab4fcd91da4ac992023c8121a501e9f2f7@65.21.71.4:30955"
XONESH_MAINNET_SNAP_PEERS="${XONESH_MAINNET_SNAP_PEERS-enode://7c85aec14c29134878b883c9b08328fc67b5d242f397c03c758a9a919acb6d2625b1eda37189579e5ef197843da55a28ffe1b0028e0264928b13c486f239145d@snap-mainnet.xdc.dev:30382,enode://a9f23f800ccd7fdcd2d2ad1c18e006ba90caef4303ed6a400b835c186dcb9fe601adb3eaa817c1bc3ed240ac7cfab3c1fc8395c49dce7e4021b373621656cf94@snap-mainnet.xdc.dev:30384,enode://60b013e02047922ce08355307541fff996cf3725613e04f112bef5195701bc7561cf377dfd71911b931fa1dd38547174ca34ab78980e0136ad3810df509796d7@snap-mainnet.xdc.dev:30340}"
XONESH_APOTHEM_SNAP_PEERS="${XONESH_APOTHEM_SNAP_PEERS-enode://10f3cfe53b64b93aab58250295173f4192dbb15b66ea1be974e5aa12b56a7abe3049e8328856f3867884d2942ba0ecc35c29cd4bbd9a01ace193fb892e8cce33@snap-apothem.xdc.dev:30950}"

host_ip(){
  local ip=""
  ip=$(getent ahostsv4 "$1" 2>/dev/null | awk 'NR==1{print $1}') || true
  [ -n "$ip" ] || ip=$(python3 -c 'import socket,sys; print(socket.gethostbyname(sys.argv[1]))' "$1" 2>/dev/null) || true
  [ -n "$ip" ] || ip=$(dig +short A "$1" 2>/dev/null | grep -E '^[0-9.]+$' | head -1) || true
  printf '%s' "$ip"
}
# --bootnodes takes IPs only: resolve host names; an enode whose name does not resolve is dropped.
resolve_enode_hosts(){
  local out="" en host ip
  for en in $(printf '%s' "$1" | tr ',' ' '); do
    host=$(printf '%s' "$en" | sed -E 's|^enode://[0-9a-fA-F]+@([^:]+):.*$|\1|')
    if printf '%s' "$host" | grep -qE '^[0-9.]+$'; then out="$out${out:+,}$en"; continue; fi
    if [ "$DRY" = 1 ]; then out="$out${out:+,}$en"; continue; fi
    ip=$(host_ip "$host")
    if [ -n "$ip" ]; then
      out="$out${out:+,}${en/@$host:/@$ip:}"
    else
      warn "Could not resolve bootnode $host. Skipping it." >&2
    fi
  done
  printf '%s' "$out"
}
BOOT=""
resolve_boot(){
  BOOT="$BOOT_ARG"
  [ -n "$BOOT" ] && return 0
  if [ "$NETWORK" = pq-devnet-1 ]; then
    if [ "$DRY" = 1 ]; then BOOT="<pinned PQ execution ENRs>"
    else BOOT=$(paste -sd, "$PQ_CONFIG/el_enrs.txt"); fi
    return 0
  fi
  [ "$KIND" = eth ] && return 0          # Ethereum: the binary's built-in bootnodes
  local list=""
  case "$NETWORK" in
    mainnet|apothem)
      if [ "$DRY" != 1 ]; then
        list=$(curl -fsSL -A 'Mozilla/5.0' --max-time 15 "$XONESH_SEEDS_URL/$NETWORK.enodes" 2>/dev/null) || list=""
      fi
      BOOT=$(printf '%s\n' "$list" | grep -E '^enode://[0-9a-f]{128}@[0-9.]+:[0-9]+$' | paste -sd, - ) || BOOT=""
      [ "$NETWORK" = apothem ] && BOOT="$APOTHEM_MODERN_PEERS${BOOT:+,$BOOT}" ;;
    private) [ "$DRY" = 1 ] || warn "no --bootnodes for the private network: the node only finds peers that dial it" ;;
  esac
  local seed; seed=$(seed_enodes "$NETWORK")
  [ -n "$seed" ] && BOOT="$seed${BOOT:+,$BOOT}"
  BOOT=$(resolve_enode_hosts "$BOOT")
}

static_peers(){
  [ "$KIND" = xdc ] && [ "${1:-$MODE}" = snap ] || return 0
  case "$NETWORK" in
    mainnet) printf '%s' "$XONESH_MAINNET_SNAP_PEERS" ;;
    apothem) printf '%s' "$XONESH_APOTHEM_SNAP_PEERS" ;;
  esac
}

browser_enodes(){
  local nodes=() en delimiter=""
  IFS=, read -r -a nodes <<< "$1"
  printf '['
  for en in "${nodes[@]}"; do
    [[ "$en" =~ ^enode://[[:xdigit:]]{128}@[A-Za-z0-9.-]+:[0-9]{1,5}$ ]] || continue
    printf '%s"%s"' "$delimiter" "$en"
    delimiter=,
  done
  printf ']'
}

if [ "$ACTION" = browser-plan ]; then
  [ "$NETWORK" != private ] || die "browser-plan is available for built-in networks."
  [ "$VALIDATOR" = 0 ] || die "browser-plan supports followers only."
  if [ "$NETWORK" = pq-devnet-1 ]; then
    printf '{"version":"%s","network":"%s","chainId":%s,"kind":"eth","args":["--override.genesis","/mnt/release/genesis.json","--networkid","%s"],"mode":"%s","genesisSha256":"%s","bootnodes":[],"staticPeers":[]}\n' \
      "$XONE_SH_VERSION" "$NETWORK" "$NETID" "$NETID" "$MODE" "$PQ_GENESIS_SHA256"
    exit 0
  fi
  resolve_boot
  printf '{"version":"%s","network":"%s","chainId":%s,"kind":"%s","args":["%s","%s"],"mode":"%s","bootnodes":%s,"staticPeers":%s}\n' \
    "$XONE_SH_VERSION" "$NETWORK" "$NETID" "$KIND" "${CHAIN_ARGS[0]}" "${CHAIN_ARGS[1]}" "$MODE" \
    "$(browser_enodes "$BOOT")" "$(browser_enodes "$(static_peers snap)")"
  exit 0
fi

# ----------------------------- HELPERS ------------------------------------------
ctr_state(){ local st; st=$(docker ps -a --filter "name=^/${1}\$" --format '{{.State}}' 2>/dev/null | head -1) || st=""; printf '%s' "${st:-absent}"; }
is_running(){
  if [ "$RUNTIME" = docker ]; then command -v docker >/dev/null 2>&1 && [ "$(ctr_state "$EL_CONTAINER")" = running ]; return; fi
  [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE" 2>/dev/null)" 2>/dev/null
}
el_desc(){ if [ "$RUNTIME" = docker ]; then printf 'container %s' "$EL_CONTAINER"; else printf 'pid %s' "$(cat "$PIDFILE" 2>/dev/null)"; fi; }
rpc(){ curl -s -m6 -X POST -H 'Content-Type: application/json' --data "{\"jsonrpc\":\"2.0\",\"method\":\"$1\",\"params\":${2:-[]},\"id\":1}" "http://127.0.0.1:$RPC_PORT" 2>/dev/null || true; }
h2d(){ local h; h=$(printf '%s' "$1" | grep -oE '"result":"0x[0-9a-fA-F]+"' | grep -oE '0x[0-9a-fA-F]+' | head -1) || true; [ -n "$h" ] && printf '%d' "$h"; return 0; }
docker_ok(){ command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; }

banner(){
  hr
  printf '%s   xOne · %s · %s%s   %s(%s)%s\n' "$B" "$NET_LABEL" "$(printf '%s' "$MODE" | tr '[:lower:]' '[:upper:]')" "$N" "$D" "$DIR" "$N"
  printf '%s   client:%s xOneRS %s   %snode name:%s %s\n' "$D" "$N" "$([ "$RUNTIME" = docker ] && echo "image $IMAGE" || echo "$XONE_RS_VERSION binary ($PLATFORM)")" "$D" "$N" "$NODE_NAME"
  if [ "$KIND" = eth ]; then printf '%s   consensus:%s %s (docker)   %scheckpoint:%s %s\n' "$D" "$N" "$CL" "$D" "$N" "${CHECKPOINT_URL:-none}"
  else printf '%s   block production:%s %s\n' "$D" "$N" "$([ "$VALIDATOR" = 1 ] && echo 'ON (--validator)' || echo 'OFF')"; fi
  [ "$DRY" = 1 ] && printf '   %sDRY RUN: nothing is downloaded, created or started.%s\n' "$Y" "$N"
  mainnet_warning
  hr
}
mainnet_warning(){
  [ "$NETWORK" = mainnet ] || return 0
  case "${ACTION:-}" in start|restart|setup) ;; *) return 0 ;; esac
  printf '   %sWARNING: xOneRS is not yet qualified for XDC mainnet.%s\n' "$R" "$N"
  printf '   %sThis node only follows the chain; do not use it for production or for a validator. Apothem is the default: drop the word "mainnet" to use it.%s\n' "$Y" "$N"
}

save_marker(){
  [ "$DRY" = 1 ] && return 0
  mkdir -p "$DIR"
  persist_anon_id
  printf 'ONE_CLIENT=%s\nONE_NETWORK=%s\nONE_MODE=%s\nONE_NAME=%s\nONE_DATADIR=%s\nONE_GENESIS=%s\nONE_NETID=%s\nONE_BOOTNODES=%s\nONE_CHAINSPEC=%s\nONE_PORT=%s\nONE_RPCPORT=%s\nONE_WSPORT=%s\nONE_AUTHPORT=%s\nONE_CHECKPOINT=%s\nONE_EL_EXTRA=%s\nONE_CL_EXTRA=%s\nONE_DOCKER_EXTRA=%s\nONE_RUNTIME=%s\nONE_KEYSTORE=%s\nONE_PASSWORD_FILE=%s\n' \
    "$CLIENT" "$NETWORK" "$MODE" "$NAME_ARG" "$DATADIR_ARG" "$GENESIS_ARG" "$NETID_ARG" "$BOOT_ARG" "$CHAINSPEC_ARG" "$PORT_ARG" "$RPCPORT_ARG" "$WSPORT_ARG" "$AUTHPORT_ARG" "$CHECKPOINT_ARG" \
    "${EL_EXTRA//$'\n'/ }" "${CL_EXTRA//$'\n'/ }" "${DOCKER_EXTRA//$'\n'/ }" "$RUNTIME" \
    "${USER_KS:-$MK_KS}" "${USER_PW:-$MK_PW}" > "$DIR/.one-node"
}

# keep a copy of this script in the node dir (piped runs have no file), sha256-checked against xone.sh
save_self(){
  [ "$DRY" = 1 ] && return 0
  [ -f "$DIR/one.sh" ] && return 0
  if [ -n "$_self_dir" ] && [ -f "${BASH_SOURCE[0]}" ]; then cp "${BASH_SOURCE[0]}" "$DIR/one.sh" && chmod +x "$DIR/one.sh"; return 0; fi
  fetch_script "$DIR/one.sh" || warn "could not save a copy of the script into $DIR (re-run it with curl for status/stop)"
}
fetch_script(){
  local dest="$1" want
  curl -fsSL --max-time 60 "$XONESH_BASE_URL/install.sh" -o "$dest.tmp" 2>/dev/null || { rm -f "$dest.tmp"; return 1; }
  want=$(curl -fsSL --max-time 20 "$XONESH_BASE_URL/install.sh.sha256" 2>/dev/null | grep -oE '[0-9a-f]{64}' | head -1) || want=""
  if [ -z "$want" ] || [ "$(sha256_of "$dest.tmp")" != "$want" ]; then rm -f "$dest.tmp"; return 1; fi
  mv "$dest.tmp" "$dest" && chmod +x "$dest"
}

fetch_verified(){   # <url> <dest> <sha256>
  local url="$1" dest="$2" want="$3" temp
  if [ -f "$dest" ] && [ "$(sha256_of "$dest")" = "$want" ]; then return 0; fi
  mkdir -p "$(dirname "$dest")"
  temp=$(mktemp "$dest.XXXXXX")
  if ! curl -fsSL --retry 2 -A 'Mozilla/5.0' --max-time 120 "$url" -o "$temp"; then
    rm -f "$temp"
    die "could not download $url"
  fi
  if [ "$(sha256_of "$temp")" != "$want" ]; then
    rm -f "$temp"
    die "sha256 mismatch for $url. The saved copy has been kept."
  fi
  mv -f "$temp" "$dest"
}

# ----------------------------- BINARY --------------------------------------------
# Check the release SHA256SUMS signature (minisign) and that it lists $BIN_FILE with $BIN_SHA.
# No .minisig published (v0.2.9, v0.2.10): sha256 pin only. No minisign installed: warn, sha256 pin only.
# A signature that does not verify, or a listed hash that differs from the pin, aborts.
verify_release_sums(){
  local base="${BIN_URL%/*}" t listed
  t="$(mktemp -d)" || return 0
  if ! curl -fsSL --max-time 20 "$base/SHA256SUMS.minisig" -o "$t/SHA256SUMS.minisig" 2>/dev/null || [ ! -s "$t/SHA256SUMS.minisig" ]; then
    rm -rf "$t"; warn "no SHA256SUMS signature published for $XONE_RS_VERSION: relying on the sha256 pinned in this script"; return 0
  fi
  if ! command -v "${XONESH_MINISIGN:-minisign}" >/dev/null 2>&1; then
    rm -rf "$t"; warn "minisign not installed: skipping the SHA256SUMS signature check (sha256 is still verified). Install minisign to verify releases."; return 0
  fi
  curl -fsSL --max-time 20 "$base/SHA256SUMS" -o "$t/SHA256SUMS" 2>/dev/null || { rm -rf "$t"; telemetry_emit download_fail download_failed; die "could not download $base/SHA256SUMS to check its signature"; }
  "${XONESH_MINISIGN:-minisign}" -Vq -P "$XONE_MINISIGN_PUBKEY" -m "$t/SHA256SUMS" -x "$t/SHA256SUMS.minisig" >/dev/null 2>&1 || { rm -rf "$t"; telemetry_emit download_fail sha256_mismatch; die "SHA256SUMS signature check FAILED for $XONE_RS_VERSION: aborting"; }
  listed="$(awk -v f="$BIN_FILE" '$2 == f {print $1; exit}' "$t/SHA256SUMS")"
  rm -rf "$t"
  [ "$listed" = "$BIN_SHA" ] || { telemetry_emit download_fail sha256_mismatch; die "signed SHA256SUMS lists a different sha256 for $BIN_FILE than this run expects: aborting"; }
  ok "SHA256SUMS signature verified (minisign key ${XONE_MINISIGN_PUBKEY:0:8}…); $BIN_FILE sha256 matches"
}
# The published default image (xonesh/xone:0.2.11, also
# :latest) is a single linux/amd64 manifest (digest sha256:ee8354a8…).
# xonesh/xone:0.2.10 and 0.2.9 are also linux/amd64 only, so it is not a safe fallback.
# Refuse --docker on other platforms, including dry-run and the control arm
# (which skips treatment preflight), and point at the pinned binary. An
# explicit --image or XONESH_IMAGE is left to the manifest check.
assert_default_image_arch(){
  [ "${RUNTIME:-}" = docker ] || return 0
  [ "${IMAGE_FROM_USER:-0}" != 1 ] || return 0
  [ -z "${XONESH_IMAGE:-}" ] || return 0
  case "$PLATFORM" in
    linux-amd64) return 0 ;;
    linux-arm64|darwin-arm64)
      telemetry_emit preflight_fail image_arch
      die "the published image $IMAGE is linux/amd64 only. On $PLATFORM, drop --docker to install the pinned $BIN_FILE binary from $BIN_URL (sha256-verified)."
      ;;
    *)
      telemetry_emit preflight_fail image_arch
      die "the published image $IMAGE is linux/amd64 only. $PLATFORM has no pinned binary and no matching image. Pass --image of a build that includes this platform, or build from source at https://github.com/xOneSH/xone-rs."
      ;;
  esac
}
ensure_image(){
  assert_default_image_arch
  printf '   %simage:%s %s\n' "$D" "$N" "$IMAGE"
  [ "$DRY" = 1 ] && { printf '   %s[dry-run]%s docker pull %s\n' "$Y" "$N" "$IMAGE"; return 0; }
  docker_ok || die "the docker runtime needs docker (installed, running, and usable by $(id -un))"
  if [ "${XONESH_UPGRADE_BINARY:-0}" = 1 ] || ! docker image inspect "$IMAGE" >/dev/null 2>&1; then
    step "Pull $IMAGE"
    docker pull "$IMAGE" >/dev/null || { telemetry_emit download_fail image_pull_failed; die "could not pull $IMAGE (not published yet for $PLATFORM?). Pass --image IMG, or use a platform with a pinned binary."; }
  fi
  ok "image ready: $IMAGE"
  telemetry_emit binary_ok
}
ensure_binary(){
  if [ "$RUNTIME" = docker ]; then
    [ -n "$BIN_FILE" ] || warn "no pinned xOneRS binary for $PLATFORM: running the public image instead"
    ensure_image; return 0
  fi
  if [ -z "$BIN_FILE" ]; then
    die "no xOneRS $XONE_RS_VERSION build for $PLATFORM yet (published: linux-amd64). Other platforms: build from source at https://github.com/xOneSH/xone-rs."
  fi
  if [ -x "$BIN" ] && [ "$(sha256_of "$BIN")" = "$BIN_SHA" ]; then ok "xOneRS $XONE_RS_VERSION present ($BIN)"; telemetry_emit binary_ok; return 0; fi
  if [ -x "$BIN" ] && [ "${XONESH_UPGRADE_BINARY:-0}" != 1 ] && [ -n "$(ls -A "$DATADIR" 2>/dev/null)" ]; then
    warn "$BIN is not the pinned $XONE_RS_VERSION build; keeping it because $DATADIR holds data (run: update)"; return 0
  fi
  step "Download xOneRS $XONE_RS_VERSION for $PLATFORM"
  printf '   %ssource:%s %s\n' "$D" "$N" "$BIN_URL"
  verify_release_sums
  [ "$DRY" = 1 ] && { printf '   %s[dry-run]%s download, verify sha256 %s, install to %s\n' "$Y" "$N" "${BIN_SHA:0:16}…" "$BIN"; return 0; }
  mkdir -p "$DIR"
  local progress="-s"; [ "$TTY" = 1 ] && progress="--progress-bar"
  curl -fL --retry 5 --retry-delay 3 -A 'Mozilla/5.0' "$progress" -o "$BIN.tmp" "$BIN_URL" || { rm -f "$BIN.tmp"; telemetry_emit download_fail download_failed; die "could not download $BIN_URL"; }
  [ "$(sha256_of "$BIN.tmp")" = "$BIN_SHA" ] || { rm -f "$BIN.tmp"; telemetry_emit download_fail sha256_mismatch; die "xOneRS integrity check FAILED (sha256 mismatch): aborting"; }
  chmod +x "$BIN.tmp"
  [ -x "$BIN" ] && mv -f "$BIN" "$BIN.prev"
  mv "$BIN.tmp" "$BIN"
  "$BIN" --version >/dev/null 2>&1 || die "the downloaded binary does not run on this system ($PLATFORM)"
  ok "binary verified (sha256 $BIN_SHA_FROM): $("$BIN" --version 2>/dev/null | head -1)"
  telemetry_emit binary_ok
}

# ----------------------------- PRIVATE GENESIS ----------------------------------
GENESIS_FILE=""
resolve_private_genesis(){
  [ "$NETWORK" = private ] || return 0
  [ -n "$GENESIS_ARG" ] || die "--network private needs --genesis <path|https-url> --chainspec <forks file> [--networkid N] [--bootnodes ..]"
  [ -n "$CHAINSPEC_ARG" ] || die "xone-rs on a private network needs --chainspec <forks file> next to --genesis"
  case "$GENESIS_ARG" in
    https://*|http://*)
      GENESIS_FILE="$DIR/private-genesis.json"
      if [ "$DRY" != 1 ] && [ ! -f "$GENESIS_FILE" ]; then
        mkdir -p "$DIR"; curl -fsSL --max-time 60 "$GENESIS_ARG" -o "$GENESIS_FILE" || die "could not download $GENESIS_ARG"
        warn "private genesis is not pinned: sha256 $(sha256_of "$GENESIS_FILE")"
      fi ;;
    *) GENESIS_FILE="$(_abs "$GENESIS_ARG")"; [ "$DRY" = 1 ] || [ -f "$GENESIS_FILE" ] || die "genesis file not found: $GENESIS_FILE" ;;
  esac
  if [ -z "$NETID" ] && [ -f "$GENESIS_FILE" ]; then
    NETID=$(tr -d ' \n\t' < "$GENESIS_FILE" | grep -oE '"chainId":[0-9]+' | head -1 | grep -oE '[0-9]+') || NETID=""
  fi
  [ -n "$NETID" ] || { [ "$DRY" = 1 ] && NETID="<chainId-of-genesis>"; } || die "could not read chainId from the genesis: pass --networkid N"
  CHAIN_ARGS=(--override.genesis "$GENESIS_FILE" --networkid "$NETID" --chainspec "$CHAINSPEC_ARG")
}

prepare_pq_network(){
  [ "$NETWORK" = pq-devnet-1 ] || return 0
  GENESIS_FILE="$PQ_CONFIG/genesis.json"
  CHAIN_ARGS=(--override.genesis "$GENESIS_FILE" --networkid "$NETID" --discovery.v4=false --snap.offer2)
  if [ "$DRY" = 1 ]; then
    printf '   %s[dry-run]%s Fetch and verify the pinned ethPandaOps network files in %s\n' "$Y" "$N" "$PQ_CONFIG"
    return 0
  fi
  fetch_verified "$PQ_METADATA/genesis.json" "$GENESIS_FILE" "$PQ_GENESIS_SHA256"
  fetch_verified "$PQ_METADATA/config.yaml" "$PQ_CONFIG/config.yaml" 189726a0976bae0dc5dda75c7e0380e2ee475898f63213edfdeff499f4e10970
  fetch_verified "$PQ_METADATA/genesis.ssz" "$PQ_CONFIG/genesis.ssz" 46dc193f9aecc05124e9a0f37f51947846f868e4ac1f1d163a7c8a140dd829d8
  fetch_verified "$PQ_METADATA/bootstrap_nodes.yaml" "$PQ_CONFIG/boot_enr.yaml" 4b063f5ce88619932f363afd3d25c1c38026835d5aed6ef9695ecc3c7b863bc4
  fetch_verified "$PQ_METADATA/deposit_contract_block.txt" "$PQ_CONFIG/deposit_contract_block.txt" 9a271f2a916b0b6ee6cecb2426f0b3206ef074578be55d9bc94f6f3fe3ab86aa
  fetch_verified "$PQ_METADATA/el_enrs.txt" "$PQ_CONFIG/el_enrs.txt" de3430088762e6b8c928f5b8173036937b1a254270517e7a0ae6472b0c919dab
  ok "Verified pq-devnet-1 network files"
}

# ----------------------------- NODE KEY (XDC, opt-in with --validator or --keystore) ------
# The node reads --keystore/--password only with --mine (--validator), through one handle, and refuses any
# mode with bits in 0o177. Key material is passed to it (and mounted into the container) only with --validator.
COINBASE=""; KS_FILE=""; PW_FILE=""; KEY_TMP=""; KEY_PW_NEW=""; KEY_PW_TMP=""
# octal permission bits and owner of the file a path resolves to (follows symlinks; GNU and BSD stat)
file_mode(){ stat -L -c %a "$1" 2>/dev/null || stat -L -f %Lp "$1" 2>/dev/null || echo ""; }
file_uid(){ stat -L -c %u "$1" 2>/dev/null || stat -L -f %u "$1" 2>/dev/null || echo ""; }
# a key or password file the node will load: only 0600 or 0400 (the node's own rule), readable by the user
# the node runs as (the container runs as --user $(id -u):$(id -g)), so a bad file stops here, not in a
# container that keeps restarting
require_loadable_secret(){
  local f="$1" m u me; m=$(file_mode "$f"); u=$(file_uid "$f"); me=$(id -u)
  [ -f "$f" ] || die "$f does not exist or is not a file"
  case "$m" in 600|400) : ;; *) die "$f is mode ${m:-unknown}; the node loads key and password files only at 0600 or 0400. Run: chmod 600 $f" ;; esac
  [ -r "$f" ] || die "$f is not readable by $(id -un) (uid $me), the user the node runs as"
  [ "$me" = 0 ] || [ "$u" = "$me" ] || die "$f is owned by uid $u, not $(id -un) (uid $me), the user the node runs as. Run: chown $me:$(id -g) $f"
}
# the generated password file for --validator: --password-file F when given, else DIR/validator/password.txt
validator_pw_file(){ if [ -n "${USER_PW:-}" ]; then printf '%s' "$USER_PW"; else printf '%s' "$DIR/validator/password.txt"; fi; }
plaintext_pw_warning(){
  printf '\n   %s! The node key password is stored in PLAINTEXT at %s (mode 0600) so the node can start%s\n' "$Y" "$1" "$N"
  printf '   %s  unattended. Anyone who can read it and the keystore can sign as this node. Keep this host%s\n' "$Y" "$N"
  printf '   %s  single-user; to keep the password elsewhere, pass --password-file F (a new path, e.g. on tmpfs).%s\n' "$Y" "$N"
}
# a follower run that finds key material from an earlier installer (2.1.2 and older created it by default)
legacy_key_note(){
  local vd="$DIR/validator"
  [ -d "$vd" ] || return 0
  [ -e "$vd/password.txt" ] || [ -d "$vd/keystore" ] || return 0
  warn "Found a node key from an earlier installer in $vd/ (keystore and a PLAINTEXT password.txt)."
  warn "This follower run does not load it. If you do not run a validator, back it up off this host, then remove it: rm -r $vd"
}
# undo a key creation that did not finish: this run's temp dir, a password file this run created, the lock
# KEY_PW_NEW is set only between placing the password and committing the keystore (its rename), so a
# password whose keystore is in place is never removed
node_key_cleanup(){
  [ -z "$KEY_TMP" ] || rm -rf "$KEY_TMP"
  [ -z "$KEY_PW_TMP" ] || rm -f "$KEY_PW_TMP"
  [ -z "$KEY_PW_NEW" ] || rm -f "$KEY_PW_NEW"
  rmdir "$DIR/validator.lock" 2>/dev/null || true
  KEY_TMP=""; KEY_PW_NEW=""; KEY_PW_TMP=""
}
# place the generated password at <dest> atomically and never over an existing path: a hard link when <dest>
# is on the temp dir's filesystem (the default DIR/validator/password.txt), else a full copy to a temp file
# beside <dest> that is then hard-linked into place. A failed write leaves nothing at <dest>.
place_password(){   # <src> <dest>
  local src="$1" dest="$2"
  # refuse anything already there (a file, a directory, a symlink to one) before linking: ln into a directory
  # would succeed inside it. -n: never follow a symlink at <dest>.
  if [ -e "$dest" ] || [ -L "$dest" ]; then die "could not write $dest: it already exists"; fi
  if ln -n "$src" "$dest" 2>/dev/null; then KEY_PW_NEW="$dest"; return 0; fi
  if [ -e "$dest" ] || [ -L "$dest" ]; then die "could not write $dest: it already exists"; fi
  KEY_PW_TMP=$(umask 077; mktemp "$(dirname "$dest")/.xone-password.XXXXXX") || die "could not create a temporary file beside $dest"
  ( umask 077; cat "$src" > "$KEY_PW_TMP" ) 2>/dev/null || die "could not write the password beside $dest"
  cmp -s "$src" "$KEY_PW_TMP" || die "the password copy beside $dest is incomplete"
  if [ -e "$dest" ] || [ -L "$dest" ]; then die "could not write $dest: it already exists"; fi
  ln -n "$KEY_PW_TMP" "$dest" 2>/dev/null || die "could not write $dest (does it already exist?)"
  KEY_PW_NEW="$dest"
  rm -f "$KEY_PW_TMP"; KEY_PW_TMP=""
}
# create the node key with the pinned xOneRS binary (or image): `xone account new` writes a v3 keystore that
# the node's own decrypt path is tested against. The password is 32 random bytes (hex) from openssl, written
# under umask 077 and only ever passed by path. Both files are made in a temp dir and moved into place last.
create_node_key(){   # <keystore dir> <password file>
  local ks="$1" pw="$2" vd="$DIR/validator" name addr
  need openssl "to create the node key" openssl_missing
  ( umask 077; mkdir -p "$vd" ); chmod 700 "$vd"
  [ -d "$(dirname "$pw")" ] || die "--password-file: directory $(dirname "$pw") does not exist"
  ( umask 077; mkdir "$DIR/validator.lock" ) 2>/dev/null \
    || die "another run is creating the key, or one was killed. If none is running, remove $DIR/validator.lock and any $vd/.new-key.* directory (a killed run leaves a key and password pair there, mode 0600)"
  trap 'node_key_cleanup' EXIT; trap 'exit 130' INT; trap 'exit 143' TERM; trap 'exit 129' HUP
  KEY_TMP=$(umask 077; mktemp -d "$vd/.new-key.XXXXXX") || die "could not create a temporary directory in $vd"
  ( umask 077; mkdir "$KEY_TMP/keystore"; openssl rand -hex 32 > "$KEY_TMP/password" ) || die "could not generate the node key password"
  if [ "$RUNTIME" = docker ]; then
    # the node's image (pinned by digest unless you chose one), no network, as your uid, only the temp dir mounted
    local kimg="$IMAGE"
    docker run --rm --network none --user "$(id -u):$(id -g)" -e NETWORK= -v "$KEY_TMP:$KEY_TMP" "$kimg" \
      account new --keydir "$KEY_TMP/keystore" --password "$KEY_TMP/password" >/dev/null 2>&1 \
      || die "key creation failed (docker run $kimg account new)"
  else
    "$BIN" account new --keydir "$KEY_TMP/keystore" --password "$KEY_TMP/password" >/dev/null 2>&1 \
      || die "key creation failed ($BIN account new)"
  fi
  [ "$(find "$KEY_TMP/keystore" -maxdepth 1 -type f | wc -l | tr -d ' ')" = 1 ] || die "key creation did not produce exactly one keystore file"
  name=$(basename "$(find "$KEY_TMP/keystore" -maxdepth 1 -type f | head -1)")
  case "$(file_mode "$KEY_TMP/keystore/$name")" in 600|400) : ;; *) die "the new keystore file is not mode 0600; refusing to use it" ;; esac
  addr=$(printf '%s' "$name" | sed -E 's/.*--//; s/^(0x|xdc)//I' | tr 'A-F' 'a-f')
  case "$addr" in *[!0-9a-f]*|"") die "could not read the new key's address from $name" ;; esac
  [ "${#addr}" = 40 ] || die "could not read the new key's address from $name"
  ( umask 077; printf '0x%s\n' "$addr" > "$KEY_TMP/address.txt" ) || die "could not write the new key's address"
  ( umask 077; mkdir -p "$ks" ); chmod 700 "$ks"
  # password first (atomic, never over an existing path), then the keystore by rename: that rename commits.
  # Signals are ignored from placing the password to the commit, so none can land between a link and
  # recording it in KEY_PW_NEW, or between the rename and clearing KEY_PW_NEW. die still runs the EXIT trap.
  trap '' INT TERM HUP
  place_password "$KEY_TMP/password" "$pw"
  if ! mv "$KEY_TMP/keystore/$name" "$ks/$name"; then trap 'exit 130' INT; trap 'exit 143' TERM; trap 'exit 129' HUP; die "could not move the new keystore into $ks"; fi
  KEY_PW_NEW=""
  trap 'exit 130' INT; trap 'exit 143' TERM; trap 'exit 129' HUP
  # committed: nothing below may remove the key pair. address.txt is informational only.
  if [ -e "$vd/address.txt" ] && [ ! -f "$vd/address.txt" ]; then warn "$vd/address.txt is not a regular file; the address was not saved there"
  else mv -f "$KEY_TMP/address.txt" "$vd/address.txt" 2>/dev/null || warn "could not save $vd/address.txt"; fi
  node_key_cleanup; trap - EXIT INT TERM HUP
  KS_FILE="$ks/$name"; COINBASE="0x$addr"
  require_loadable_secret "$PW_FILE"; require_loadable_secret "$KS_FILE"
  plaintext_pw_warning "$pw"
  printf '\n   BACK UP %s and %s. Losing them loses the node key.\n' "$KS_FILE" "$pw"
}
prepare_node_key(){
  [ "$KIND" = xdc ] || return 0
  if [ "$VALIDATOR" != 1 ] && [ -z "$USER_KS" ]; then
    [ -z "$USER_PW" ] || warn "--password-file is ignored without --validator or --keystore"
    legacy_key_note; return 0
  fi
  local vd="$DIR/validator" ks f
  if [ "$VALIDATOR" = 1 ] && [ "$RUNTIME" = docker ] && [ "$IMAGE_USER" = 1 ]; then
    case "$IMAGE" in *@sha256:*) : ;; *) warn "--image/XONESH_IMAGE $IMAGE is not pinned by digest; this image creates and holds the node key. Prefer <repo>@sha256:..." ;; esac
  fi
  if [ -n "$USER_KS" ]; then
    if [ -n "$USER_MINE" ]; then COINBASE="0x$(printf '%s' "$USER_MINE" | sed -E 's/^(0x|xdc)//I' | tr 'A-F' 'a-f')"
    else [ "$(find "$USER_KS" -maxdepth 1 -type f | wc -l | tr -d ' ')" = 1 ] || die "$USER_KS holds several keys: pass --mine ADDR"
      COINBASE="0x$(find "$USER_KS" -maxdepth 1 -type f -exec basename {} \; | head -1 | sed -E 's/.*--//; s/^(0x|xdc)//I' | tr 'A-F' 'a-f')"; fi
    f=$(find "$USER_KS" -maxdepth 1 -type f -iname "*${COINBASE#0x}*" | head -1) || f=""
    [ -n "$f" ] || die "no keystore file for $COINBASE in $USER_KS"
    if [ "$VALIDATOR" = 1 ]; then
      [ -n "$USER_PW" ] || die "--keystore with --validator needs --password-file"
      KS_FILE="$f"; PW_FILE="$USER_PW"
      if [ "$DRY" != 1 ] || [ -e "$PW_FILE" ]; then require_loadable_secret "$PW_FILE"; fi
      require_loadable_secret "$KS_FILE"
    else
      # the node reads key files only to produce blocks: pass the coinbase alone, mount no key material
      [ -z "$USER_PW" ] || warn "--password-file is not passed to the node without --validator (it reads key files only to produce blocks)"
      KS_FILE=""; PW_FILE=""
    fi
  else
    ks="$vd/keystore"; PW_FILE="$(validator_pw_file)"
    local n=0; [ -d "$ks" ] && n=$(find "$ks" -maxdepth 1 -type f | wc -l | tr -d ' ')
    if [ "$n" -gt 1 ]; then die "$ks holds $n keys; refusing to guess. Keep exactly one."; fi
    if [ "$n" = 1 ] && [ -f "$PW_FILE" ]; then
      KS_FILE=$(find "$ks" -maxdepth 1 -type f | head -1)
      COINBASE="0x$(basename "$KS_FILE" | sed -E 's/.*--//; s/^(0x|xdc)//I' | tr 'A-F' 'a-f')"
      require_loadable_secret "$PW_FILE"; require_loadable_secret "$KS_FILE"
    elif [ "$n" = 1 ]; then
      die "$ks holds a key but its password file $PW_FILE is missing. Pass --password-file F for that key."
    elif [ -n "$USER_PW" ] && { [ -e "$USER_PW" ] || [ -L "$USER_PW" ]; }; then
      die "--validator creates a new key and writes its generated password to --password-file, but $USER_PW already exists. To use your own password, create the key yourself (xone account new) and pass --keystore DIR --password-file F."
    elif [ -e "$PW_FILE" ] || [ -L "$PW_FILE" ]; then
      die "$PW_FILE already exists but $ks holds no key; refusing to create a key next to it. Move it away, then re-run."
    elif [ "$DRY" = 1 ]; then
      COINBASE="0x<new-key-created-on-first-run>"; KS_FILE="$ks/<keystore-file>"
      printf '   %s[dry-run]%s create a node key with "%s account new"; its password would be stored in PLAINTEXT at %s (mode 0600)\n' "$Y" "$N" "$([ "$RUNTIME" = docker ] && echo "docker run $IMAGE" || echo "$BIN")" "$PW_FILE"
    else
      create_node_key "$ks" "$PW_FILE"
    fi
  fi
  printf '\n   %sCOINBASE: %s%s  (stake via the XDC masternode portal to become a validator)\n' "$B" "$COINBASE" "$N"
}

# ----------------------------- JWT ---------------------------------------------------
ensure_jwt(){
  [ -s "$JWT" ] && { ok "JWT secret present ($JWT)"; return 0; }
  if [ "$DRY" = 1 ]; then printf '   %s[dry-run]%s create %s (32 random bytes, hex)\n' "$Y" "$N" "$JWT"; return 0; fi
  mkdir -p "$DIR"
  ( umask 077; if command -v openssl >/dev/null 2>&1; then openssl rand -hex 32; else od -An -N32 -tx1 /dev/urandom | tr -d ' \n'; fi | tr -d '\n' > "$JWT" )
  ok "JWT secret created ($JWT)"
}

# ----------------------------- EXECUTION CLIENT ARGS ------------------------------------
EL_ARGS=()
BIND=127.0.0.1
build_el_args(){
  EL_ARGS=()
  # Docker Desktop (macOS) has no host networking: listen inside the container, publish on 127.0.0.1 only
  if [ "$RUNTIME" = docker ] && [ "$OS" = darwin ]; then BIND=0.0.0.0; fi
  EL_ARGS+=("${CHAIN_ARGS[@]}" --datadir "$DATADIR" --port "$P2P_PORT" --maxpeers "$MAXPEERS"
    --http --http.addr "$BIND" --http.port "$RPC_PORT"
    --ws --ws.addr "$BIND" --ws.port "$WS_PORT" --identity "$NODE_NAME")
  if [ "$KIND" = eth ]; then
    local vhosts="localhost" beacon_host="127.0.0.1" prune="$MODE"
    if [ "$OS" = darwin ]; then
      vhosts="localhost,host.docker.internal"
      [ "$RUNTIME" != docker ] || beacon_host="host.docker.internal"
    fi
    if [ "$MODE" = snap ]; then
      prune=minimal
      EL_ARGS+=(--syncmode snap --snap.beacon "http://$beacon_host:$CL_HTTP_PORT")
    fi
    EL_ARGS+=(--http.api "eth,net,web3" --prune "$prune"
      --authrpc.addr "$BIND" --authrpc.port "$AUTH_PORT" --authrpc.vhosts "$vhosts" --authrpc.jwtsecret "$JWT")
  else
    EL_ARGS+=(--http.api "eth,net,web3,XDPoS" --syncmode "$MODE")
    # least disk that still validates: state of the last 3213 blocks (the XDC minimum, the snap/gap window) and
    # bodies, receipts and tx index of the last XONESH_HISTORY blocks (default 4500 = 5 epochs, the longest
    # consensus lookback in xOneRS spec/retention.md). Set XONESH_HISTORY=0 to keep the whole chain.
    EL_ARGS+=(--gcmode full --history.state "${XONESH_STATE_BLOCKS:-3213}")
    if [ "${XONESH_HISTORY:-4500}" != 0 ]; then
      EL_ARGS+=(--history.bodies "${XONESH_HISTORY:-4500}" --history.receipts "${XONESH_HISTORY:-4500}" --history.transactions "${XONESH_HISTORY:-4500}")
    fi
    if [ "$MODE" = snap ] && [ -n "$GAP_RPC" ]; then EL_ARGS+=(--snap.gap-rpc "$GAP_RPC"); fi
    case "$NETWORK" in mainnet|apothem)
      if [ -f "$DATADIR/.xone-state-disk" ] || [ -z "$(ls -A "$DATADIR/xone" 2>/dev/null)" ]; then
        EL_ARGS+=(--state.disk); [ "$DRY" = 1 ] || { mkdir -p "$DATADIR"; : > "$DATADIR/.xone-state-disk"; }
      fi ;;
    esac
    if [ -n "${XDC_SNAP_PINS:-}" ] && [ "$MODE" = snap ]; then EL_ARGS+=(--snap.pins "$(_abs "$XDC_SNAP_PINS")"); fi
    # key material reaches the node only with --mine (--validator); --keystore alone sets the coinbase
    if [ "$VALIDATOR" = 1 ]; then
      EL_ARGS+=(--mine --keystore "$KS_FILE" --password "$PW_FILE" --miner.etherbase "$COINBASE")
    elif [ -n "$USER_KS" ]; then
      EL_ARGS+=(--miner.etherbase "$COINBASE")
    fi
    if [ "$NO_ETHSTATS" != 1 ]; then
      case "$ETHSTATS_LOGIN" in ''|*[!A-Za-z0-9._-]*) die "XONESH_ETHSTATS_SECRET may hold only letters, digits, '.', '_' and '-'" ;; esac
      case "$ETHSTATS_TARGET" in ''|*[!A-Za-z0-9.:-]*) die "XONESH_ETHSTATS_HOST must look like host:port" ;; esac
      EL_ARGS+=(--ethstats "${NODE_NAME}:${ETHSTATS_LOGIN}@${ETHSTATS_TARGET}")
    fi
  fi
  if [ -n "$BOOT" ]; then EL_ARGS+=(--bootnodes "$BOOT"); fi
  _words "$EL_EXTRA"; EL_ARGS+=(${XW[@]+"${XW[@]}"})
  return 0
}

# --el-extra/--cl-extra/--docker-extra: split on whitespace into argv (read -a: no eval, no globbing, no quote parsing)
XW=()
_words(){ XW=(); read -r -a XW <<< "$1" || true; }
# docker runtime: the image runs `xone <args>` when NETWORK is unset (its run-xone.sh), as your uid, with the node dir
# mounted at the same path so every path in EL_ARGS (datadir, jwt, keys, genesis) is unchanged.
EL_DOCKER=()
build_el_docker(){
  local net=(--network host) mounts=() m
  for m in "$DATADIR" "${GENESIS_FILE:+$(dirname "$GENESIS_FILE")}" "${CHAINSPEC_ARG:+$(dirname "$CHAINSPEC_ARG")}"; do
    case "$m" in ""|"$DIR"|"$DIR"/*) : ;; *) mounts+=(-v "$m:$m") ;; esac
  done
  # the node dir is read-write, but the node key in it is read-only for the container
  if [ -d "$DIR/validator" ] || { [ "$VALIDATOR" = 1 ] && [ -z "$USER_KS" ]; }; then
    mounts+=(-v "$DIR/validator:$DIR/validator:ro")
  fi
  # your own key material, only when the node loads it (--validator): read-only, the keystore directory and the
  # password file itself, never the password's directory. A single-file bind mount pins the file's inode: if the
  # password is rotated by writing a new file and renaming it over the old one, re-run the installer so the
  # container is re-created and sees the new file.
  if [ "$VALIDATOR" = 1 ]; then
    for m in "$USER_KS" "${PW_FILE:-}"; do
      case "$m" in ""|"$DIR/validator"|"$DIR/validator"/*) : ;; *) mounts+=(-v "$m:$m:ro") ;; esac
    done
  fi
  if [ "$KIND" = xdc ] && [ "$MODE" = snap ] && [ -n "${XDC_SNAP_PINS:-}" ]; then
    m="$(_abs "$XDC_SNAP_PINS")"
    case "$m" in "$DIR"/*) : ;; *) mounts+=(-v "$m:$m:ro") ;; esac
  fi
  if [ "$OS" = darwin ]; then
    net=(-p "$P2P_PORT:$P2P_PORT/tcp" -p "$P2P_PORT:$P2P_PORT/udp" -p "127.0.0.1:$RPC_PORT:$RPC_PORT" -p "127.0.0.1:$WS_PORT:$WS_PORT")
    [ "$KIND" = eth ] && net+=(-p "127.0.0.1:$AUTH_PORT:$AUTH_PORT")
  fi
  EL_DOCKER=(docker run -d --name "$EL_CONTAINER" --restart unless-stopped --log-driver json-file --log-opt max-size=100m --log-opt max-file=5 "${net[@]}" --user "$(id -u):$(id -g)"
    -e NETWORK= -v "$DIR:$DIR" "${mounts[@]}" --label "sh.xone.node=$NETWORK")
  _words "$DOCKER_EXTRA"; EL_DOCKER+=(${XW[@]+"${XW[@]}"})
  EL_DOCKER+=("$IMAGE" "${EL_ARGS[@]}")
  return 0
}

# snap on mainnet/apothem: most public peers serve no snap/1, so dial the XDCIndia snap peers (a new datadir only)
write_static_peers(){
  local sp
  sp="$(static_peers)"
  [ -n "$sp" ] && [ ! -f "$DATADIR/static-nodes.json" ] || return 0
  if [ "$DRY" = 1 ]; then printf '   %s[dry-run]%s write %s/static-nodes.json (XDCIndia snap/1 peers)\n' "$Y" "$N" "$DATADIR"; return 0; fi
  mkdir -p "$DATADIR"
  printf '%s' "$sp" | tr ',' '\n' | awk 'NF{printf "%s\"%s\"", (n++ ? ",\n  " : "[\n  "), $0} END{if (n) print "\n]"}' > "$DATADIR/static-nodes.json"
  ok "snap peers written to $DATADIR/static-nodes.json"
}

# ----------------------------- CONSENSUS CLIENT (Ethereum) --------------------------------
CL_ARGS=()
build_cl_cmd(){
  local el_host="127.0.0.1" net=(--network host)
  if [ "$OS" = darwin ]; then
    el_host="host.docker.internal"
    net=(-p "$CL_P2P_PORT:$CL_P2P_PORT/tcp" -p "$CL_P2P_PORT:$CL_P2P_PORT/udp" -p "$((CL_P2P_PORT+1)):$((CL_P2P_PORT+1))/udp" -p "127.0.0.1:$CL_HTTP_PORT:$CL_HTTP_PORT")
  fi
  CL_ARGS=(docker run -d --name "$CL_CONTAINER" --restart unless-stopped --log-driver json-file --log-opt max-size=100m --log-opt max-file=5 "${net[@]}"
    --user "$(id -u):$(id -g)" -v "$CL_DIR:/data" -v "$JWT:/jwt.hex:ro"
    --label "sh.xone.node=$NETWORK")
  _words "$DOCKER_EXTRA"; CL_ARGS+=(${XW[@]+"${XW[@]}"})
  if [ "$NETWORK" = pq-devnet-1 ]; then
    CL_ARGS+=(-v "$PQ_CONFIG:/network:ro" "$LIGHTHOUSE_IMAGE" lighthouse --testnet-dir /network bn)
  else
    CL_ARGS+=("$LIGHTHOUSE_IMAGE" lighthouse bn --network "$CL_NET")
  fi
  CL_ARGS+=(--datadir /data
    --execution-endpoint "http://$el_host:$AUTH_PORT" --execution-jwt /jwt.hex
    --http --http-address "$([ "$OS" = darwin ] && echo 0.0.0.0 || echo 127.0.0.1)" --http-port "$CL_HTTP_PORT"
    --port "$CL_P2P_PORT" --quic-port "$((CL_P2P_PORT+1))" --disable-upnp)
  if [ -n "$CHECKPOINT_URL" ]; then CL_ARGS+=(--checkpoint-sync-url "$CHECKPOINT_URL"); fi
  _words "$CL_EXTRA"; CL_ARGS+=(${XW[@]+"${XW[@]}"})
  return 0
}
cl_state(){ ctr_state "$CL_CONTAINER"; }
start_cl(){
  [ "$CL" = lighthouse ] || die "--cl $CL: only lighthouse is wired today"
  build_cl_cmd
  if [ "$DRY" = 1 ]; then
    printf '\n   %sconsensus client:%s\n   %s\n' "$B" "$N" "$(printf '%q ' "${CL_ARGS[@]}")"; return 0
  fi
  docker_ok || die "Ethereum networks run Lighthouse in docker: install docker (and start it, with access for $(id -un)), then re-run"
  case "$(cl_state)" in
    running) ok "Lighthouse already running ($CL_CONTAINER)"; return 0 ;;
    absent) : ;;
    *) docker start "$CL_CONTAINER" >/dev/null && { ok "Lighthouse restarted ($CL_CONTAINER)"; return 0; } ;;
  esac
  if [ -n "$CHECKPOINT_URL" ]; then
    curl -fsS -m 15 -o /dev/null "$CHECKPOINT_URL/eth/v1/beacon/states/finalized/finality_checkpoints" 2>/dev/null \
      || warn "checkpoint endpoint $CHECKPOINT_URL does not answer: Lighthouse may fail to start (pass --checkpoint-url)"
  else
    printf '   Lighthouse starts from the configured genesis.\n'
  fi
  mkdir -p "$CL_DIR"
  step "Starting Lighthouse ($CL_NET) in docker"
  docker image inspect "$LIGHTHOUSE_IMAGE" >/dev/null 2>&1 || docker pull "$LIGHTHOUSE_IMAGE"
  "${CL_ARGS[@]}" >/dev/null
  ok "Lighthouse started (container $CL_CONTAINER, beacon API 127.0.0.1:$CL_HTTP_PORT)"
}

wait_for_beacon_finality(){
  local cap="${XONESH_WAIT_CAP:-1200}" started now state
  if [ "$DRY" = 1 ]; then
    printf '   %s[dry-run]%s Wait for a finalized checkpoint from the local Lighthouse API\n' "$Y" "$N"
    return 0
  fi
  [[ "$cap" =~ ^[1-9][0-9]*$ ]] || die "XONESH_WAIT_CAP must be a positive number of seconds"
  started=$(date +%s)
  step "Waiting for a finalized checkpoint from Lighthouse"
  while [ "$(cl_state)" = running ]; do
    state=$(curl -fsS --max-time 4 "http://127.0.0.1:$CL_HTTP_PORT/eth/v1/beacon/states/head/finality_checkpoints" 2>/dev/null) || state=""
    if tr -d '\r\n' <<< "$state" | grep -Eq '"finalized"[[:space:]]*:[[:space:]]*[{][^}]*"epoch"[[:space:]]*:[[:space:]]*"[1-9][0-9]*"'; then
      ok "Lighthouse has a finalized checkpoint"
      return 0
    fi
    now=$(date +%s)
    if [ $((now - started)) -ge "$cap" ]; then
      die "Lighthouse is running and still waiting for finality. Check docker logs $CL_CONTAINER."
    fi
    sleep 3
  done
  die "Lighthouse exited before finalizing. Check docker logs $CL_CONTAINER."
}

stop_cl(){
  [ "$KIND" = eth ] || return 0
  if [ "$DRY" = 1 ]; then printf '   %s[dry-run]%s docker stop %s\n' "$Y" "$N" "$CL_CONTAINER"; return 0; fi
  docker_ok || return 0
  case "$(cl_state)" in
    absent) : ;;
    *) docker stop -t 60 "$CL_CONTAINER" >/dev/null 2>&1 || true; docker rm "$CL_CONTAINER" >/dev/null 2>&1 || true; ok "Lighthouse stopped" ;;
  esac
}

# One line on start. XDC only: Ethereum starts from this script do not pass --ethstats.
ethstats_note(){
  [ "$KIND" = xdc ] || return 0
  if [ "$NO_ETHSTATS" = 1 ]; then
    printf '   %sStats:%s not reporting to stats.xdcindia.com (--no-ethstats or XONESH_ETHSTATS=0).\n' "$B" "$N"
    return 0
  fi
  printf '   %sStats:%s this node reports anonymously to stats.xdcindia.com as %s (a random id, not this machine'\''s hostname). Opt out: --no-ethstats or XONESH_ETHSTATS=0. https://xone.sh/privacy/\n' "$B" "$N" "$NODE_NAME"
}

# A renamed anonymous node must not leave the previous container for this network running.
drop_old_el(){
  [ "$RUNTIME" = docker ] || return 0
  docker_ok || return 0
  local id
  while IFS= read -r id; do
    [ -n "$id" ] || continue
    docker rm -f "$id" >/dev/null 2>&1 || true
  done < <(docker ps -aq --filter "label=sh.xone.node=${NETWORK}" 2>/dev/null || true)
}

# ----------------------------- STAGE TELEMETRY ----------------------------------------------
# Nothing is sent unless XONESH_TELEMETRY_URL is set. Opt out: --no-telemetry,
# XONESH_TELEMETRY=0, or DO_NOT_TRACK=1. status/stop/logs/update/dry-run send nothing.
telemetry_on(){
  [ "$TELEMETRY" = 1 ] || return 1
  [ -n "${XONESH_TELEMETRY_URL:-}" ] || return 1
  [ "${DRY:-0}" = 1 ] && return 1
  case "${ACTION:-}" in
    start|restart) ;;
    *) return 1 ;;
  esac
  return 0
}
telemetry_notice(){
  [ "${TELEMETRY_NOTE_DONE:-0}" = 1 ] && return 0
  case "${ACTION:-}" in start|restart) ;; *) return 0 ;; esac
  TELEMETRY_NOTE_DONE=1
  if [ "$TELEMETRY" != 1 ]; then
    printf '   %sTelemetry:%s off (--no-telemetry, XONESH_TELEMETRY=0, or DO_NOT_TRACK=1).\n' "$B" "$N"
    return 0
  fi
  if [ -z "${XONESH_TELEMETRY_URL:-}" ]; then
    printf '   %sTelemetry:%s anonymous stage events are not sent, because no collector URL is set. Opt out: --no-telemetry, XONESH_TELEMETRY=0, or DO_NOT_TRACK=1. https://xone.sh/privacy/\n' "$B" "$N"
    return 0
  fi
  printf '   %sTelemetry:%s sending anonymous stage events (install id, stage, elapsed seconds, installer version, xOneRS version, OS/arch, network, runtime, mode, error code). No IP and no hostname. Opt out: --no-telemetry, XONESH_TELEMETRY=0, or DO_NOT_TRACK=1. https://xone.sh/privacy/\n' "$B" "$N"
}
ensure_install_id(){
  local id=""
  if [ -f "$DIR/.install-id" ]; then
    IFS= read -r id < "$DIR/.install-id" || id=""
    id=$(printf '%s' "$id" | tr -cd 'a-f0-9')
    id="${id:0:32}"
    [ "${#id}" = 32 ] || id=""
  fi
  if [ -z "$id" ]; then
    if [ -r /dev/urandom ]; then id=$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')
    else id=$(printf '%08x%08x%08x%08x' "${RANDOM:-0}" "$$" "${RANDOM:-1}" "${RANDOM:-2}"); fi
    id=$(printf '%s' "$id" | tr -cd 'a-f0-9')
    id="${id:0:32}"
  fi
  [ "${#id}" = 32 ] || return 1
  INSTALL_ID="$id"
  if [ "$DRY" != 1 ]; then
    mkdir -p "$DIR"
    printf '%s\n' "$INSTALL_ID" > "$DIR/.install-id"
  fi
}
# 50/50 from sha256(install_id). XONESH_EXP=control|treatment overrides. readiness means treatment.
assign_arm(){
  case "${XONESH_EXP:-}" in
    control|treatment) ARM="${XONESH_EXP}"; return 0 ;;
    readiness) ARM=treatment; return 0 ;;
  esac
  if [ -z "${INSTALL_ID:-}" ] || [ "${#INSTALL_ID}" != 32 ]; then
    ensure_install_id || { ARM=control; return 0; }
  fi
  local hex
  if command -v sha256sum >/dev/null 2>&1; then hex=$(printf '%s' "$INSTALL_ID" | sha256sum | awk '{print $1}')
  elif command -v shasum >/dev/null 2>&1; then hex=$(printf '%s' "$INSTALL_ID" | shasum -a 256 | awk '{print $1}')
  elif command -v openssl >/dev/null 2>&1; then hex=$(printf '%s' "$INSTALL_ID" | openssl dgst -sha256 | awk '{print $NF}')
  else hex="$INSTALL_ID"; fi
  hex=$(printf '%s' "$hex" | tr -cd '0-9a-fA-F' | cut -c1)
  case "$hex" in
    [0-7]) ARM=control ;;
    *) ARM=treatment ;;
  esac
}
key_will_be_created(){
  [ "$KIND" = xdc ] || return 1
  [ "$VALIDATOR" = 1 ] || return 1
  [ -n "${USER_KS:-}" ] && return 1
  local ks="$DIR/validator/keystore" n=0
  [ -d "$ks" ] && n=$(find "$ks" -maxdepth 1 -type f 2>/dev/null | wc -l | tr -d ' ')
  [ "$n" = 1 ] && [ -f "$(validator_pw_file)" ] && return 1
  return 0
}
preflight_platform(){
  if [ "${RUNTIME:-}" = docker ]; then
    assert_default_image_arch
    if [ "${DRY:-0}" = 1 ]; then
      printf '   %s[dry-run]%s image manifest check: %s must include %s\n' "$Y" "$N" "$IMAGE" "$PLATFORM"
      return 0
    fi
    docker_ok || die "the docker runtime needs docker (installed, running, and usable by $(id -un))"
    local arch man
    case "$PLATFORM" in
      linux-amd64) arch=amd64 ;;
      linux-arm64|darwin-arm64) arch=arm64 ;;
      *) arch="" ;;
    esac
    man=$(docker manifest inspect "$IMAGE" 2>/dev/null || true)
    if [ -z "$man" ]; then
      warn "could not read the image manifest for $IMAGE. If the pull fails, the image may not include $PLATFORM."
      return 0
    fi
    if [ -n "$arch" ] && ! printf '%s' "$man" | grep -q "\"architecture\"[[:space:]]*:[[:space:]]*\"$arch\""; then
      telemetry_emit preflight_fail image_arch
      die "image $IMAGE has no $arch manifest. Fix: use a platform with a published binary (linux-amd64), or pass --image of a build that includes $arch."
    fi
    return 0
  fi
  if [ -z "${BIN_FILE:-}" ]; then
    telemetry_emit preflight_fail ""
    die "no xOneRS $XONE_RS_VERSION build for $PLATFORM yet (published: linux-amd64). Other platforms: build from source at https://github.com/xOneSH/xone-rs."
  fi
}
preflight_resources(){
  local avail kb target="${DIR:-$PWD}"
  [ -d "$target" ] || target="$PWD"
  avail=$(df -Pk "$target" 2>/dev/null | awk 'NR==2 {print $4}' || true)
  if [ -n "$avail" ] && [ "$avail" -lt 31457280 ]; then
    warn "Disk: about $((avail / 1024 / 1024)) GB free under $target. This does not block the directory you chose."
  elif [ -n "$avail" ]; then
    printf '   Disk: about %s GB free (measured, not a block).\n' "$((avail / 1024 / 1024))"
  else
    printf '   Disk: not measured.\n'
  fi
  kb=$(awk '/MemAvailable:/ {print $2}' /proc/meminfo 2>/dev/null || true)
  if [ -n "$kb" ] && [ "$kb" -lt 2097152 ]; then
    warn "RAM: about $((kb / 1024)) MB available. A full node wants more. This warning does not stop the install."
  elif [ -n "$kb" ]; then
    printf '   RAM: about %s MB available.\n' "$((kb / 1024))"
  else
    printf '   RAM: not measured on this OS.\n'
  fi
}
treatment_preflight(){
  printf '\n%s▶ Preflight (before download)%s\n' "$B" "$N"
  preflight_resources
  if key_will_be_created; then
    need openssl "to create the node key (install openssl, then re-run)" openssl_missing
  fi
  preflight_platform
  if [ "${DRY:-0}" != 1 ]; then telemetry_emit preflight_ok; fi
}
el_rpc(){
  local method="$1"
  if [ -n "${XONESH_RPC_FIXTURE:-}" ]; then
    [ -f "$XONESH_RPC_FIXTURE/$method" ] || return 0
    cat "$XONESH_RPC_FIXTURE/$method"
    return 0
  fi
  curl -s -m6 -X POST -H 'Content-Type: application/json' \
    --data "{\"jsonrpc\":\"2.0\",\"method\":\"${method}\",\"params\":[],\"id\":1}" \
    "http://127.0.0.1:${RPC_PORT}" || true
}
# Foreground wait for the first RPC answer: eth_syncing or eth_blockNumber. During snap sync
# eth_blockNumber returns an error (-32000) while eth_syncing already answers. Ctrl-C does not stop the node.
treatment_wait(){
  local cap="${XONESH_WAIT_CAP:-1200}" start now peers ph pn num sy stage
  if [ "${NO_WAIT:-0}" = 1 ]; then
    printf '   %sWait:%s skipped (--no-wait). The node keeps running. cd %s && ./one.sh status\n' "$B" "$N" "$DIR"
    return 0
  fi
  if [ "$TTY" != 1 ] && [ "${XONESH_SELFTEST_WAIT:-}" != 1 ]; then
    printf '   %sWait:%s no terminal, so this run does not wait for the first RPC answer. cd %s && ./one.sh status\n' "$B" "$N" "$DIR"
    return 0
  fi
  printf '   %sWait:%s process is up. Waiting for the first RPC answer: eth_syncing or eth_blockNumber (cap %ss). Ctrl-C leaves the node running.\n' "$B" "$N" "$cap"
  trap 'printf "\n   Left the node running. cd %s && ./one.sh status\n" "$DIR"; trap - INT; exit 0' INT
  start=$(date +%s)
  stage="process up, no peers and no RPC answer yet"
  while true; do
    now=$(date +%s)
    if [ $((now - start)) -ge "$cap" ]; then
      trap - INT
      err "Stuck at: $stage. Not answering eth_syncing or eth_blockNumber. This is not a successful start."
      printf '   Fix: cd %s && ./one.sh logs\n' "$DIR"
      printf '        cd %s && ./one.sh status\n' "$DIR"
      printf '   https://github.com/xOneSH/xOne.Sh/issues\n'
      return 1
    fi
    peers=$(el_rpc net_peerCount || true)
    ph=$(printf '%s' "$peers" | grep -m1 -oE '0x[0-9a-fA-F]+' || true)
    if [ -n "$ph" ]; then
      pn=$((ph))
      if [ "$pn" -gt 0 ]; then
        stage="peers $pn, no RPC answer yet"
        printf '   peers: %s\n' "$pn"
      fi
    fi
    num=$(el_rpc eth_blockNumber || true)
    if printf '%s' "$num" | grep -qE '"result"[[:space:]]*:[[:space:]]*"0x[0-9a-fA-F]+"'; then
      trap - INT
      ok "answering eth_blockNumber ($(el_desc)). Sync may still be running. cd $DIR && ./one.sh status"
      telemetry_emit first_rpc
      return 0
    fi
    # Snap sync: eth_syncing answers, eth_blockNumber errors until the state download ends. first_rpc stays tied to eth_blockNumber.
    sy=$(el_rpc eth_syncing || true)
    if printf '%s' "$sy" | grep -qE '"result"[[:space:]]*:[[:space:]]*(false|\{)'; then
      trap - INT
      ok "RPC is up ($(el_desc)): eth_syncing answers. eth_blockNumber can return an error until the snap state download finishes. cd $DIR && ./one.sh status"
      return 0
    fi
    if [ -z "${XONESH_RPC_FIXTURE:-}" ]; then sleep 5; fi
  done
}
telemetry_emit(){
  telemetry_on || return 0
  local stage="$1" code="${2:-}" elapsed t0 now payload stamp
  case "$stage" in
    install_start|preflight_ok|preflight_fail|binary_ok|download_fail|node_started|first_peer|first_rpc|synced|error) ;;
    *) return 0 ;;
  esac
  case "$code" in
    ""|curl_missing|download_failed|sha256_mismatch|node_exited|python3_missing|openssl_missing|image_pull_failed|image_arch) ;;
    *) code="" ;;
  esac
  stamp="$DIR/.telemetry-sent-$stage"
  [ -f "$stamp" ] && return 0
  ensure_install_id || return 0
  [ -n "${ARM:-}" ] || assign_arm
  if [ ! -s "$DIR/.install-started" ]; then
    mkdir -p "$DIR"
    date +%s > "$DIR/.install-started"
  fi
  IFS= read -r t0 < "$DIR/.install-started" || t0=""
  t0=$(printf '%s' "$t0" | tr -cd '0-9')
  now=$(date +%s)
  if [ -n "$t0" ]; then elapsed=$((now - t0)); else elapsed=0; fi
  [ "$elapsed" -lt 0 ] && elapsed=0
  payload=$(printf '{"install_id":"%s","stage":"%s","elapsed_s":%s,"installer_version":"%s","xone_rs_version":"%s","network":"%s","runtime":"%s","os_arch":"%s","mode":"%s","error_code":"%s","cohort":"%s","arm":"%s"}' \
    "$INSTALL_ID" "$stage" "$elapsed" "$XONE_SH_VERSION" "$XONE_RS_VERSION" "$NETWORK" "$RUNTIME" "$PLATFORM" "$MODE" "$code" "$COHORT" "${ARM:-}")
  if curl -fsS -m 5 -A xonesh-telemetry -H 'content-type: application/json' --data "$payload" "$XONESH_TELEMETRY_URL" >/dev/null 2>&1; then
    mkdir -p "$DIR"
    : > "$stamp"
  fi
  return 0
}
# Local RPC watcher. Polls 127.0.0.1 only. Stops at synced or 6h after install start.
# synced: eth_blockNumber answers, eth_syncing is false, head timestamp <= 60s old.
# first_rpc is the first eth_blockNumber. A_rpc_2h / A_synced_6h are counted by the collector.
write_watch_script(){
  cat > "$DIR/telemetry-watch.sh" <<'EOF'
#!/usr/bin/env bash
# Detached local-RPC watcher. Sends anonymous stage events. No hostname, no IP.
set -u
DIR="${XONESH_WATCH_DIR:?}"
RPC_PORT="${XONESH_WATCH_RPC_PORT:?}"
URL="${XONESH_TELEMETRY_URL:?}"
case "$RPC_PORT" in ''|*[!0-9]*) exit 0 ;; esac
case "$URL" in http://*|https://*) ;; *) exit 0 ;; esac
case "${XONESH_WATCH_NETWORK:-}" in
  mainnet|apothem|devnet|private|eth-mainnet|sepolia|hoodi) ;;
  *) exit 0 ;;
esac
case "${XONESH_WATCH_RUNTIME:-}" in binary|docker) ;; *) exit 0 ;; esac
case "${XONESH_WATCH_MODE:-}" in snap|full|minimal|archive) ;; *) exit 0 ;; esac
case "${XONESH_WATCH_COHORT:-}" in ""|internal) ;; *) exit 0 ;; esac
case "${XONESH_WATCH_ARM:-}" in control|treatment) ;; *) XONESH_WATCH_ARM="" ;; esac
case "${XONESH_WATCH_OS:-}" in [a-z0-9]*-[a-z0-9]*) ;; *) exit 0 ;; esac
post(){
  local stage="$1" stamp id t0 now elapsed payload
  stamp="$DIR/.telemetry-sent-$stage"
  [ -f "$stamp" ] && return 0
  IFS= read -r id < "$DIR/.install-id" || return 0
  id=$(printf '%s' "$id" | tr -cd 'a-f0-9'); id="${id:0:32}"
  [ "${#id}" = 32 ] || return 0
  IFS= read -r t0 < "$DIR/.install-started" || return 0
  t0=$(printf '%s' "$t0" | tr -cd '0-9')
  [ -n "$t0" ] || return 0
  now=$(date +%s)
  elapsed=$((now - t0))
  [ "$elapsed" -lt 0 ] && elapsed=0
  payload=$(printf '{"install_id":"%s","stage":"%s","elapsed_s":%s,"installer_version":"%s","xone_rs_version":"%s","network":"%s","runtime":"%s","os_arch":"%s","mode":"%s","error_code":"","cohort":"%s","arm":"%s"}' \
    "$id" "$stage" "$elapsed" "${XONESH_WATCH_INSTALLER:-}" "${XONESH_WATCH_XONE:-}" \
    "${XONESH_WATCH_NETWORK:-}" "${XONESH_WATCH_RUNTIME:-}" "${XONESH_WATCH_OS:-}" "${XONESH_WATCH_MODE:-}" \
    "${XONESH_WATCH_COHORT:-}" "${XONESH_WATCH_ARM:-}")
  if [ -n "${XONESH_WATCH_SINK:-}" ]; then
    printf '%s\n' "$payload" >> "$XONESH_WATCH_SINK"
    : > "$stamp"
    return 0
  fi
  if curl -fsS -m 5 -A xonesh-telemetry -H 'content-type: application/json' --data "$payload" "$URL" >/dev/null 2>&1; then
    : > "$stamp"
  fi
}
rpc(){
  local method="$1" params="$2"
  if [ -n "${XONESH_RPC_FIXTURE:-}" ]; then
    [ -f "$XONESH_RPC_FIXTURE/$method" ] || return 0
    printf '%s' "$(cat "$XONESH_RPC_FIXTURE/$method")"
    return 0
  fi
  curl -s -m6 -X POST -H 'Content-Type: application/json' \
    --data "{\"jsonrpc\":\"2.0\",\"method\":\"${method}\",\"params\":${params},\"id\":1}" \
    "http://127.0.0.1:${RPC_PORT}" || true
}
hex_result(){ printf '%s' "$1" | grep -m1 -oE '"result"[[:space:]]*:[[:space:]]*"0x[0-9a-fA-F]+"' || true; }
once=0
[ "${XONESH_WATCH_ONCE:-}" = 1 ] && once=1
while true; do
  now=$(date +%s)
  t0=$(tr -cd '0-9' < "$DIR/.install-started" || true)
  elapsed=0
  [ -n "$t0" ] && elapsed=$((now - t0))
  [ "$elapsed" -gt 21600 ] && exit 0
  peers=$(rpc net_peerCount '[]')
  ph=$(hex_result "$peers")
  ph=$(printf '%s' "$ph" | grep -m1 -oE '0x[0-9a-fA-F]+' || true)
  if [ -n "$ph" ]; then
    pn=$((ph))
    [ "$pn" -gt 0 ] && post first_peer
  fi
  num=$(rpc eth_blockNumber '[]')
  if printf '%s' "$(hex_result "$num")" | grep -q .; then
    post first_rpc
    sy=$(rpc eth_syncing '[]')
    if printf '%s' "$sy" | grep -qE '"result"[[:space:]]*:[[:space:]]*false'; then
      block=$(rpc eth_getBlockByNumber '["latest",false]')
      ts=$(printf '%s' "$block" | grep -m1 -oE '"timestamp"[[:space:]]*:[[:space:]]*"0x[0-9a-fA-F]+"' || true)
      ts=$(printf '%s' "$ts" | grep -m1 -oE '0x[0-9a-fA-F]+' || true)
      if [ -n "$ts" ]; then
        age=$((now - ts))
        if [ "$age" -ge 0 ] && [ "$age" -le 60 ] && [ "$elapsed" -le 21600 ]; then
          post synced && [ -f "$DIR/.telemetry-sent-synced" ] && exit 0
        fi
      fi
    fi
  fi
  [ "$once" = 1 ] && exit 0
  sleep 30
done
EOF
  chmod +x "$DIR/telemetry-watch.sh"
}
start_telemetry_watcher(){
  telemetry_on || return 0
  local pid=""
  if [ -f "$DIR/.telemetry-watch.pid" ]; then
    pid=$(tr -cd '0-9' < "$DIR/.telemetry-watch.pid" || true)
    if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then return 0; fi
  fi
  mkdir -p "$DIR"
  write_watch_script
  XONESH_WATCH_DIR="$DIR" \
    XONESH_WATCH_RPC_PORT="$RPC_PORT" \
    XONESH_TELEMETRY_URL="$XONESH_TELEMETRY_URL" \
    XONESH_WATCH_NETWORK="$NETWORK" \
    XONESH_WATCH_RUNTIME="$RUNTIME" \
    XONESH_WATCH_MODE="$MODE" \
    XONESH_WATCH_OS="$PLATFORM" \
    XONESH_WATCH_COHORT="$COHORT" \
    XONESH_WATCH_ARM="${ARM:-}" \
    XONESH_WATCH_INSTALLER="$XONE_SH_VERSION" \
    XONESH_WATCH_XONE="$XONE_RS_VERSION" \
    nohup bash "$DIR/telemetry-watch.sh" >/dev/null 2>&1 &
  echo "$!" > "$DIR/.telemetry-watch.pid"
  disown "$!" 2>/dev/null || true
}

# ----------------------------- COMMANDS -----------------------------------------------------
cmd_setup(){
  banner
  [ "$KIND" = eth ] && [ "$DRY" != 1 ] && { docker_ok || die "Ethereum networks need docker for Lighthouse: install and start docker first"; }
  save_marker
  ensure_binary
  resolve_private_genesis
  prepare_pq_network
  [ "$KIND" = eth ] && ensure_jwt
  if [ "$DRY" = 1 ]; then printf '   %s[dry-run]%s mkdir -p %s\n' "$Y" "$N" "$DATADIR"; else mkdir -p "$DATADIR" "$LOGDIR"; fi
  save_self
  ok "node directory ready: $DIR"
}

# Each port the node will listen on must be free. Uses ss (Linux); without ss the check is skipped.
check_ports(){
  command -v ss >/dev/null 2>&1 || { warn "ss not found: skipping the port check"; return 0; }
  local tcp udp spec port proto flag
  # ss can exist and still fail (WSL1, gVisor, restricted LXC: no netlink socket): skip as if missing
  if ! tcp="$(ss -ltn 2>/dev/null)" || ! udp="$(ss -lun 2>/dev/null)"; then warn "ss failed: skipping the port check"; return 0; fi
  tcp="$(printf '%s\n' "$tcp" | awk 'NR>1 {print $4}')"; udp="$(printf '%s\n' "$udp" | awk 'NR>1 {print $4}')"
  for spec in "$P2P_PORT tcp --port" "$P2P_PORT udp --port" "$RPC_PORT tcp --rpcport" "$WS_PORT tcp --wsport" "$AUTH_PORT tcp --authrpc-port"; do
    read -r port proto flag <<< "$spec"
    [ "$flag" != --authrpc-port ] || [ "$KIND" = eth ] || continue   # the auth RPC is opened only for Ethereum
    if [ "$proto" = tcp ]; then printf '%s\n' "$tcp"; else printf '%s\n' "$udp"; fi | grep -qE ":$port\$" || continue
    if [ "$DRY" = 1 ]; then warn "[dry-run] port $port/$proto is in use: a real start would stop here (change it with $flag N)"
    else die "port $port/$proto is already in use (another node?). Pick a free port with $flag N."; fi
  done
}
cmd_start(){
  recover_safety
  if [ "$DRY" != 1 ] && is_running; then
    banner; ethstats_note; telemetry_notice; ok "xOneRS already running ($(el_desc))."
    [ "$KIND" = eth ] && start_cl
    printf '\n   Status: %scd %s && ./one.sh status%s\n' "$G" "$DIR" "$N"; return 0
  fi
  check_ports
  assign_arm
  telemetry_notice
  if [ "$DRY" != 1 ]; then
    telemetry_emit install_start
    if ! command -v curl >/dev/null 2>&1; then
      telemetry_emit preflight_fail curl_missing
      die "curl is required"
    fi
    # Treatment sends preflight_ok only after the checks that run before the download.
    [ "$ARM" = treatment ] || telemetry_emit preflight_ok
  fi
  if [ "$ARM" = treatment ]; then treatment_preflight; fi
  cmd_setup
  ethstats_note
  prepare_node_key
  resolve_boot
  write_static_peers
  build_el_args
  if [ "$KIND" = eth ] && [ "$MODE" = snap ]; then
    start_cl
    if [ ! -s "$DATADIR/xone-chain.json" ]; then wait_for_beacon_finality; fi
  fi
  if [ "$DRY" = 1 ]; then
    if [ "$RUNTIME" = docker ]; then build_el_docker; printf '\n   %sexecution client (docker):%s\n   %s\n' "$B" "$N" "$(printf '%q ' "${EL_DOCKER[@]}")"
    else printf '\n   %sexecution client:%s\n   %s\n' "$B" "$N" "$(printf '%q ' "$BIN" "${EL_ARGS[@]}")"; fi
    if [ "$KIND" = eth ] && [ "$MODE" != snap ]; then start_cl; fi
    if [ "$ARM" = treatment ]; then
      if [ "$NO_WAIT" = 1 ]; then
        printf '   %s[dry-run]%s skipping the first-RPC wait (--no-wait). Ctrl-C during a real wait leaves the node running.\n' "$Y" "$N"
      else
        printf '   %s[dry-run]%s would wait for the first RPC answer: eth_syncing or eth_blockNumber (cap %ss). Ctrl-C leaves the node running. --no-wait skips the wait.\n' "$Y" "$N" "${XONESH_WAIT_CAP:-1200}"
      fi
    fi
    next_steps
    printf '\n   %sDRY RUN complete.%s Drop --dry-run to run it.\n' "$G" "$N"; return 0
  fi
  step "Starting xOneRS ($NET_LABEL, $MODE)"
  ulimit -n 65536 2>/dev/null || true
  # the binary warns about unknown XONE_* variables; none of the installer's own (XONESH_*) reach it
  if [ "$RUNTIME" = docker ]; then
    build_el_docker
    drop_old_el
    [ "$(ctr_state "$EL_CONTAINER")" = absent ] || docker rm -f "$EL_CONTAINER" >/dev/null 2>&1 || true
    "${EL_DOCKER[@]}" >/dev/null || die "docker could not start $EL_CONTAINER"
  else
    rotate_log
    nohup "$BIN" "${EL_ARGS[@]}" >> "$LOG" 2>&1 &
    echo $! > "$PIDFILE"
  fi
  if [ "$ARM" = treatment ]; then sleep 1; else sleep "${XONESH_START_WAIT:-6}"; fi
  if ! is_running; then
    telemetry_emit error node_exited
    err "xOneRS did not start. Last log lines:"
    if [ "$RUNTIME" = docker ]; then docker logs --tail 20 "$EL_CONTAINER" >&2 2>&1 || true; else tail -n 20 "$LOG" >&2 || true; fi
    exit 1
  fi
  if [ "$KIND" = eth ] && [ "$MODE" != snap ]; then start_cl; fi
  if [ "$ARM" = treatment ]; then
    treatment_wait
  else
    ok "xOneRS started ($(el_desc)), RPC http://127.0.0.1:$RPC_PORT"
  fi
  date +%s > "$DIR/.started_at"
  telemetry_emit node_started
  start_telemetry_watcher
  next_steps
}

next_steps(){
  printf '\n   %sManage:%s cd %s && ./one.sh status | logs | stop | update\n' "$B" "$N" "$DIR"
  printf '   %sDisk:%s %s\n' "$B" "$N" "$(disk_note)"
  [ "$KIND" = xdc ] || return 0
  if [ -n "${COINBASE:-}" ] && [ -z "${KS_FILE:-}" ]; then
    printf '   %sCoinbase:%s %s from %s (the key is not given to the node; add --validator to produce)\n' "$B" "$N" "$COINBASE" "$USER_KS"
  elif [ -n "${COINBASE:-}" ]; then
    printf '   %sNode key (coinbase):%s %s  -  keystore %s, password file %s (plaintext, 0600; back both up)\n' "$B" "$N" "$COINBASE" "$KS_FILE" "$PW_FILE"
    printf '      use your own key instead: --keystore DIR --password-file FILE on the next start\n'
  elif [ -d "$DIR/validator" ]; then
    printf '   %sNode key:%s not loaded. An earlier key is in %s/validator/ (see the note above).\n' "$B" "$N" "$DIR"
  else
    printf '   %sNode key:%s not created. Pass --validator (testnets) or --keystore DIR --password-file FILE if you need one.\n' "$B" "$N"
  fi
  if [ "$NETWORK" = mainnet ]; then
    printf '   %sMainnet:%s this node follows the chain. Release builds do not produce blocks on mainnet. Mainnet following is not yet qualified. https://xone.sh\n' "$B" "$N"
  fi
}
disk_note(){
  case "$NETWORK:$MODE" in
    mainnet:snap|apothem:snap) printf 'snap + pruned: about 30-100 GB, grows slowly with the state (estimate from the XDC one.sh)' ;;
    mainnet:full|apothem:full) printf 'full sync from genesis, pruned history: hundreds of GB while it replays; days to sync' ;;
    devnet:*|private:*) printf 'small test chain: a few GB' ;;
    *:minimal) printf 'Ethereum --prune minimal (state of the last 10064 blocks); xOneRS has not published a measured size yet' ;;
    *) printf 'see xOneRS docs for %s %s' "$NETWORK" "$MODE" ;;
  esac
}

cmd_stop(){
  banner
  stop_cl
  if [ "$DRY" = 1 ]; then printf '   %s[dry-run]%s kill the xOneRS pid in %s (SIGTERM, then SIGKILL after 60 s)\n' "$Y" "$N" "$PIDFILE"; return 0; fi
  if [ "$RUNTIME" = docker ]; then
    if [ "$(ctr_state "$EL_CONTAINER")" = absent ]; then ok "xOneRS already stopped."; return 0; fi
    step "Stopping xOneRS ($EL_CONTAINER), allowing a clean save"
    docker stop -t 120 "$EL_CONTAINER" >/dev/null 2>&1 || true; docker rm "$EL_CONTAINER" >/dev/null 2>&1 || true
    ok "stopped"; return 0
  fi
  if ! is_running; then ok "xOneRS already stopped."; rm -f "$PIDFILE"; return 0; fi
  local p i=0; p=$(cat "$PIDFILE"); step "Stopping xOneRS (pid $p), allowing a clean save"
  kill "$p" 2>/dev/null || true
  while [ "$i" -lt 60 ] && kill -0 "$p" 2>/dev/null; do sleep 1; i=$((i+1)); done
  if kill -0 "$p" 2>/dev/null; then kill -9 "$p" 2>/dev/null || true; warn "force-stopped"; else ok "stopped cleanly"; fi
  rm -f "$PIDFILE"
}

cmd_status(){
  banner
  if [ "$DRY" = 1 ]; then printf '   %s[dry-run]%s query eth_blockNumber, net_peerCount, eth_syncing on 127.0.0.1:%s\n' "$Y" "$N" "$RPC_PORT"; return 0; fi
  if ! is_running; then err "xOneRS is NOT running. Start: ./one.sh start"; else
    ok "xOneRS running ($(el_desc))"
    local head peers sy
    head=$(h2d "$(rpc eth_blockNumber)"); peers=$(h2d "$(rpc net_peerCount)"); sy=$(rpc eth_syncing)
    printf '   %sblock:%s %s   %speers:%s %s   %schain id:%s %s\n' "$B" "$N" "${head:-?}" "$B" "$N" "${peers:-?}" "$B" "$N" "$(h2d "$(rpc eth_chainId)")"
    if [ -z "$head" ] && [ "$MODE" = snap ]; then
      if printf '%s' "$sy" | grep -qE '"result"[[:space:]]*:[[:space:]]*(false|\{)'; then warn "RPC is up (eth_syncing answers) but eth_blockNumber has no block yet: the snap state download is still running, or the node is still starting. Read ./one.sh logs for peer and state progress."
      else warn "RPC is not answering yet. Read ./one.sh logs for peer and state progress."; fi
    elif printf '%s' "$sy" | grep -q '"result":false'; then ok "not syncing (at the tip, or waiting for peers / the consensus client)"
    elif [ -n "$sy" ]; then warn "syncing: $(printf '%s' "$sy" | grep -oE '"(currentBlock|highestBlock)":"0x[0-9a-fA-F]+"' | tr '\n' ' ')"; fi
  fi
  if [ "$KIND" = eth ]; then
    if docker_ok; then
      printf '   %sLighthouse:%s %s' "$B" "$N" "$(cl_state)"
      local s; s=$(curl -s -m5 "http://127.0.0.1:$CL_HTTP_PORT/eth/v1/node/syncing" 2>/dev/null) || s=""
      [ -n "$s" ] && printf '   %s' "$s"; echo
    else warn "docker not reachable: Lighthouse state unknown"; fi
  fi
  [ -d "$DATADIR" ] && printf '   %sdisk:%s %s (%s)\n' "$B" "$N" "$(du -sh "$DATADIR" 2>/dev/null | cut -f1)" "$DATADIR"
  [ -n "$COINBASE" ] || { [ -f "$DIR/validator/address.txt" ] && printf '   %snode key on disk (not loaded unless you pass --validator):%s 0x%s in %s/validator/\n' "$B" "$N" "$(grep -oiE '[0-9a-f]{40}' "$DIR/validator/address.txt" | head -1)" "$DIR"; }
  return 0
}

# binary mode: at start, move a node log over 100 MB to node.log.1 (keeps node.log.1-5)
rotate_log(){
  [ -f "$LOG" ] && [ "$(wc -c < "$LOG")" -gt 104857600 ] || return 0
  local i
  for i in 4 3 2 1; do [ ! -f "$LOG.$i" ] || mv -f "$LOG.$i" "$LOG.$((i+1))"; done
  mv -f "$LOG" "$LOG.1"
}
# logs [--tail N] [--since T]: --since is passed to docker logs; the binary log has no timestamps index
cmd_logs(){
  case "$LOG_LINES" in ""|*[!0-9]*) die "logs --tail needs a number of lines (got '$LOG_LINES')" ;; esac
  if [ "$RUNTIME" = docker ]; then
    [ "$KIND" = eth ] && warn "consensus client log: docker logs -f $CL_CONTAINER"
    docker logs --tail "$LOG_LINES" ${LOG_SINCE:+--since "$LOG_SINCE"} -f "$EL_CONTAINER"; return
  fi
  [ -f "$LOG" ] || die "no log yet at $LOG (start the node first)"
  [ "$KIND" = eth ] && warn "consensus client log: docker logs -f $CL_CONTAINER"
  [ -z "$LOG_SINCE" ] || warn "--since works with the docker runtime only; showing the last $LOG_LINES lines"
  tail -n "$LOG_LINES" -f "$LOG"
}

# A destructive step needs --yes, or "yes" typed on the terminal (also under curl | bash).
confirm(){
  [ "$YES" = 1 ] && return 0
  ( : < /dev/tty ) 2>/dev/null || die "$1: no terminal to confirm on. Re-run with --yes."
  local a=""
  printf '   %s Type yes to go on: ' "$1" > /dev/tty
  read -r a < /dev/tty || a=""
  [ "$a" = yes ] || die "not confirmed: nothing was changed"
}
# Canonical path for a delete decision. No lexical fallback: without realpath -m or readlink -f, stop.
_canon(){ realpath -m -- "$1" 2>/dev/null || readlink -f -- "$1" 2>/dev/null || die "cannot resolve $1 (needs realpath -m or readlink -f): nothing was deleted"; }
# true if canonical path $2 is $1 or inside it
_under(){ [ "$1" = / ] || [ "$2" = "$1" ] || case "$2" in "$1"/*) true ;; *) false ;; esac; }
# Refuse to remove a symlink, /, the home dir or the node dir (or anything above them), a path that holds keys,
# the JWT, the marker or key-like files, and a non-empty dir outside the node dir that does not look like the
# client's data ($2: xone = xOneRS datadir with xone/ or xone-chain.json, beacon = Lighthouse dir with beacon/).
# Sets RM_CANON to the canonical path to delete.
assert_removable(){
  local p="$1" c d h k kc found
  while [ "$p" != / ] && [ "${p%/}" != "$p" ]; do p="${p%/}"; done
  [ ! -L "$p" ] || die "refusing to remove $1: it is a symlink. Replace it with a directory, or remove it yourself."
  c="$(_canon "$p")"; d="$(_canon "$DIR")"; h="$(_canon "${HOME:-/}")"
  if _under "$c" "$d"; then die "refusing to remove $1: it is the node directory or above it"; fi
  if _under "$c" "$h"; then die "refusing to remove $1: it is your home directory or above it"; fi
  for k in "$DIR/validator" "$USER_KS" "$USER_PW" "$MK_KS" "$MK_PW" "$JWT" "$DIR/.one-node"; do
    [ -n "$k" ] && [ -e "$k" ] || continue
    kc="$(_canon "$k")"
    if _under "$c" "$kc"; then die "refusing to remove $1: it holds $k"; fi
  done
  found="$(find "$c" -maxdepth 5 \( -path '*/keystore/*' -o -name 'UTC--*' -o -iname '*password*' \) -print 2>/dev/null | head -1 || true)"
  [ -z "$found" ] || die "refusing to remove $1: it holds key material ($found). Move it out first."
  if ! _under "$d" "$c" && [ -n "$(ls -A "$c" 2>/dev/null)" ]; then
    case "$2" in
      xone) [ -d "$c/xone" ] || [ -f "$c/xone-chain.json" ] || die "refusing to remove $1: it is outside $DIR and does not look like an xOneRS datadir (no xone/ or xone-chain.json)" ;;
      beacon) [ -d "$c/beacon" ] || die "refusing to remove $1: it is outside $DIR and does not look like a Lighthouse dir (no beacon/)" ;;
    esac
  fi
  RM_CANON="$c"
}
# A safety record parked by an interrupted resync goes back before anything else runs.
SAFETY_PARK=""; SAFETY_HOME=""
restore_safety(){
  [ -n "$SAFETY_PARK" ] && [ -d "$SAFETY_PARK" ] || return 0
  mkdir -p "${SAFETY_HOME%/safety}" && mv "$SAFETY_PARK" "$SAFETY_HOME" && { SAFETY_PARK=""; ok "safety record kept: $SAFETY_HOME"; } \
    || err "the safety record is parked at $SAFETY_PARK: move it to $SAFETY_HOME before producing blocks"
}
recover_safety(){
  local f home="$DATADIR/xone/safety"
  for f in "$DIR"/.resync-safety.*; do
    [ -d "$f" ] || continue
    if [ -e "$home" ]; then
      [ "$VALIDATOR" != 1 ] || die "a safety record from an interrupted resync is parked at $f and $home also exists: merge them by hand before producing blocks"
      warn "a safety record from an interrupted resync is parked at $f ($home also exists): keep it for a validator"; continue
    fi
    if [ "$DRY" = 1 ]; then printf '   %s[dry-run]%s move the parked safety record %s back to %s\n' "$Y" "$N" "$f" "$home"; continue; fi
    SAFETY_PARK="$f"; SAFETY_HOME="$home"; restore_safety
    [ -z "$SAFETY_PARK" ] || die "could not move the parked safety record $f back to $home"
  done
}
# resync [el|cl|all]: stop, delete the chain data (EL datadir, Lighthouse dir, or both), keep keys/JWT/marker and
# the xOneRS safety record (anti-double-sign), start.
cmd_resync(){
  local what="${RESYNC_WHAT:-el}" p rm=() safety=""
  [ -f "$DIR/.one-node" ] || die "no node in $DIR (no .one-node marker): nothing to resync"
  recover_safety
  case "$what" in cl|all)
    if [ "$KIND" = eth ]; then assert_removable "$CL_DIR" beacon; rm+=("$RM_CANON"); elif [ "$what" = cl ]; then die "resync cl: $NETWORK has no consensus client"; fi ;;
  esac
  case "$what" in el|all)
    assert_removable "$DATADIR" xone; rm+=("$RM_CANON"); safety="$RM_CANON/xone/safety"
    if [ -d "$DIR/validator" ] || [ -n "$USER_KS$MK_KS" ] || [ -d "$safety" ]; then
      [ "$YES_VALIDATOR" = 1 ] || die "this node has a validator key or a safety record: resync needs --yes-validator (the safety record $safety is kept)"
    fi ;;
  esac
  # a container this run would not stop (docker node started without --docker) keeps writing to the data
  if [ "$RUNTIME" != docker ] && [ "$(ctr_state "$EL_CONTAINER")" != absent ]; then
    die "container $EL_CONTAINER runs this node, but this run uses the binary runtime: re-run with --docker"
  fi
  banner
  step "Resync plan ($what)"
  printf '   1. stop the node\n'
  for p in "${rm[@]}"; do printf '   2. delete everything in %s\n' "$p"; done
  [ ! -d "$safety" ] || printf '   kept: the safety record %s (moved aside and back)\n' "$safety"
  printf '   3. start again; it syncs from scratch\n   kept: keys, JWT, .one-node and the binary in %s\n' "$DIR"
  [ "$DRY" = 1 ] && { printf '   %s[dry-run]%s nothing was changed\n' "$Y" "$N"; return 0; }
  confirm "This deletes the chain data above."
  cmd_stop
  for p in "$EL_CONTAINER" "$CL_CONTAINER"; do
    [ "$(ctr_state "$p")" = absent ] || die "container $p is still present after stop: nothing was deleted"
  done
  if [ -d "$safety" ]; then
    SAFETY_PARK="$DIR/.resync-safety.$$"; SAFETY_HOME="$safety"
    trap 'restore_safety' EXIT; trap 'exit 130' INT; trap 'exit 143' TERM
    mv "$safety" "$SAFETY_PARK"
  fi
  # delete the contents, not the dir itself: a datadir can be a mount point
  for p in "${rm[@]}"; do [ ! -d "$p" ] || find "$p" -mindepth 1 -delete; ok "deleted everything in $p"; done
  restore_safety; trap - EXIT INT TERM
  [ -z "$SAFETY_PARK" ] || die "could not move the safety record back from $SAFETY_PARK"
  cmd_start
}
# uninstall: stop, remove the containers and the installer's files in the node dir. --purge (with a confirm)
# also deletes the node dir with its chain data and keys. Nothing outside the node dir is touched.
cmd_uninstall(){
  local f p files=()
  [ -f "$DIR/.one-node" ] || die "no node in $DIR (no .one-node marker): nothing to uninstall"
  local dc hc; dc="$(_canon "$DIR")"; hc="$(_canon "${HOME:-/}")"
  if _under "$dc" "$hc"; then die "refusing to uninstall from $DIR: it is your home directory or above it"; fi
  for f in "$PIDFILE" "$JWT" "$DIR/one.sh" "$DIR/.one-node" "$BIN" "$BIN.prev" "$DIR/.started_at" \
    "$DIR/telemetry-watch.sh" "$DIR/.telemetry-watch.pid"; do [ ! -e "$f" ] || files+=("$f"); done
  banner
  step "Uninstall plan"
  printf '   1. stop the node; remove the containers %s and %s if present
' "$EL_CONTAINER" "$CL_CONTAINER"
  for f in ${files[@]+"${files[@]}"}; do printf '   2. delete %s
' "$f"; done
  if [ "$PURGE" = 1 ]; then
    printf '   3. delete %s and everything in it: chain data, logs and keys (%s)
' "$DIR" "$(du -sh "$DIR" 2>/dev/null | cut -f1)"
  else
    printf '   kept: chain data, logs and keys in %s (add --purge to delete them)
' "$DIR"
  fi
  case "$DATADIR/" in "$DIR"/*) ;; *) printf '   kept: %s (outside the node dir)
' "$DATADIR" ;; esac
  [ "$DRY" = 1 ] && { printf '   %s[dry-run]%s nothing was changed
' "$Y" "$N"; return 0; }
  [ "$PURGE" = 1 ] && confirm "This deletes $DIR with its chain data and keys."
  cmd_stop
  if [ -f "$DIR/.telemetry-watch.pid" ]; then
    p="$(tr -cd '0-9' < "$DIR/.telemetry-watch.pid")"
    [ -n "$p" ] && ps -p "$p" -o args= 2>/dev/null | grep -q telemetry-watch.sh && kill "$p" 2>/dev/null || true
  fi
  if docker_ok; then docker rm -f "$EL_CONTAINER" "$CL_CONTAINER" >/dev/null 2>&1 || true; fi
  for f in ${files[@]+"${files[@]}"}; do rm -f -- "$f"; done
  if [ "$PURGE" = 1 ]; then rm -rf -- "$dc"; ok "deleted $DIR"; else ok "uninstalled; chain data and keys kept in $DIR"; fi
}
# rollback: binary mode swaps in $BIN.prev (kept by update). Not supported with docker.
# Manual only; rolling back twice undoes it.
cmd_rollback(){
  [ -f "$DIR/.one-node" ] || die "no node in $DIR (no .one-node marker): nothing to roll back"
  banner
  [ "$RUNTIME" != docker ] || die "rollback is not supported with the docker runtime. Start with --image <previous tag> instead."
  [ -x "$BIN.prev" ] || die "no previous binary at $BIN.prev: nothing to roll back to (update keeps one when it replaces the binary)"
  local was=0; is_running && was=1
  if [ "$DRY" = 1 ]; then printf '   %s[dry-run]%s stop if running, swap %s and %s, start again if it was running\n' "$Y" "$N" "$BIN" "$BIN.prev"; return 0; fi
  [ "$was" = 1 ] && cmd_stop
  [ ! -e "$BIN" ] || mv -f "$BIN" "$BIN.rollback"
  mv -f "$BIN.prev" "$BIN"
  [ ! -e "$BIN.rollback" ] || mv -f "$BIN.rollback" "$BIN.prev"
  ok "rolled back to: $("$BIN" --version 2>/dev/null | head -1). The replaced binary is $BIN.prev (rollback again to undo)."
  [ "$was" = 1 ] && cmd_start
  return 0
}
cmd_update(){
  banner
  local was=0; is_running && was=1
  if [ "$DRY" = 1 ]; then printf '   %s[dry-run]%s stop if running, replace %s with %s (sha256-verified), refresh %s/one.sh, start again if it was running\n' "$Y" "$N" "$BIN" "$BIN_FILE" "$DIR"; return 0; fi
  [ "$was" = 1 ] && cmd_stop
  XONESH_UPGRADE_BINARY=1 ensure_binary
  if fetch_script "$DIR/one.sh.new"; then mv "$DIR/one.sh.new" "$DIR/one.sh"; ok "script refreshed: $DIR/one.sh"; else warn "could not refresh $DIR/one.sh"; fi
  [ "$was" = 1 ] && cmd_start
  return 0
}

cmd_clients(){
  cat <<CLIENTS
   client    distribution                        networks                                      modes
   xone-rs   pinned binary $XONE_RS_VERSION, sha256-verified   XDC: mainnet apothem devnet private           snap full
             (linux-amd64: v0.2.11; linux-arm64 and darwin-arm64: v0.2.9 binary until listed in latest.json; image is linux/amd64 only)  ETH: eth-mainnet sepolia hoodi pq-devnet-1 (+ Lighthouse)  minimal full archive snap
   Validator: XDC apothem / devnet / private (release builds refuse block production on XDC mainnet).
CLIENTS
}

cmd_networks(){
  cat <<NETS
   network       chain id   status
   apothem       51         available (XDC testnet; alias: testnet; the default)
   mainnet       50         experimental (full by default; snap requires XDC_SNAP_PINS)
   net2040       2040       shut down 1 Dec 2026 (use apothem)
   devnet        5551       available (XDC; built into the binary)
   private       any        available with --genesis, --chainspec [--networkid --bootnodes]
   eth-mainnet   1          experimental (xOneRS Ethereum mode + Lighthouse)
   sepolia       11155111   experimental (xOneRS Ethereum mode + Lighthouse)
   hoodi         560048     experimental (xOneRS Ethereum mode + Lighthouse)
   holesky       17000      not available (deprecated upstream; use hoodi)
   ephemery      rotating   not available (no Ephemery chain in the pinned build)
   pq-devnet-1   701522068  experimental (PQ Lighthouse and snap sync by default)
NETS
}

cmd_version(){
  printf 'xone.sh installer %s\nxOneRS pinned %s (%s: %s)\n' "$XONE_SH_VERSION" "$XONE_RS_VERSION" "$PLATFORM" "${BIN_FILE:-no build}"
  [ -x "$BIN" ] && printf 'installed: %s\n' "$("$BIN" --version 2>/dev/null | head -1)"
  return 0
}

case "${XONESH_SELFTEST:-}" in
node-key)
  # create (or load) the --validator node key in XONESH_SELFTEST_DIR with the binary XONESH_SELFTEST_BIN,
  # then print the paths and the coinbase. No download, no node start, no network.
  DIR="${XONESH_SELFTEST_DIR:?}"
  BIN="${XONESH_SELFTEST_BIN:?}"
  KIND=xdc; VALIDATOR=1; DRY=0; USER_KS=""; USER_PW="${XONESH_SELFTEST_PW:-}"
  [ "${XONESH_SELFTEST_RUNTIME:-binary}" = docker ] && RUNTIME=docker || RUNTIME=binary
  [ "$IMAGE_USER" = 1 ] || IMAGE="$XONE_RS_IMAGE_DIGEST"
  mkdir -p "$DIR"
  prepare_node_key
  printf 'node-key coinbase=%s keystore=%s password=%s\n' "$COINBASE" "$KS_FILE" "$PW_FILE"
  exit 0 ;;
anon-id)
  DIR="${XONESH_SELFTEST_DIR:?}"
  NAME_ARG=""
  DRY=0
  NETWORK=mainnet
  mkdir -p "$DIR"
  rm -f "$DIR/.anon-id"
  resolve_node_name
  first="$NODE_NAME"
  persist_anon_id
  NAME_ARG=""
  resolve_node_name
  [ "$NODE_NAME" = "$first" ] || { printf 'anon id changed: %s %s\n' "$first" "$NODE_NAME" >&2; exit 1; }
  case "$NODE_NAME" in
    xone-rs-mainnet-[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]) ;;
    *) printf 'unexpected node name: %s\n' "$NODE_NAME" >&2; exit 1 ;;
  esac
  exit 0 ;;
telemetry-gates)
  printf 'telemetry=%s dry=%s action=%s\n' "$TELEMETRY" "$DRY" "$ACTION"
  exit 0 ;;
telemetry)
  DIR="${XONESH_SELFTEST_DIR:?}"
  log="${XONESH_CURL_LOG:?}"
  mkdir -p "$DIR"
  : > "$log"
  rm -f "$DIR"/.telemetry-sent-* "$DIR"/.install-id "$DIR"/.install-started
  curl(){ printf '%s\n' "$*" >> "$log"; return 0; }
  XONESH_TELEMETRY_URL=""
  TELEMETRY=1; DRY=0; ACTION=start
  telemetry_emit install_start
  [ ! -s "$log" ] || { printf 'empty URL still posted\n' >&2; exit 1; }
  XONESH_TELEMETRY_URL="http://collector.test/telemetry"
  TELEMETRY=0
  telemetry_emit install_start
  [ ! -s "$log" ] || { printf 'opt-out still posted\n' >&2; exit 1; }
  TELEMETRY=1; DRY=1
  telemetry_emit install_start
  [ ! -s "$log" ] || { printf 'dry-run still posted\n' >&2; exit 1; }
  DRY=0
  for ACTION in status stop logs update; do
    telemetry_emit install_start
    [ ! -s "$log" ] || { printf '%s still posted\n' "$ACTION" >&2; exit 1; }
  done
  ACTION=start
  telemetry_emit install_start
  grep -q 'collector.test/telemetry' "$log"
  grep -q '"stage":"install_start"' "$log"
  grep -qE '"arm":"(control|treatment)"' "$log"
  grep -qE '"install_id":"[0-9a-f]{32}"' "$log"
  _hn=$(hostname -s 2>/dev/null | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9' || true)
  if [ -n "$_hn" ] && grep -q "$_hn" "$log"; then printf 'hostname leaked into telemetry\n' >&2; exit 1; fi
  : > "$log"
  telemetry_emit install_start
  [ ! -s "$log" ] || { printf 'duplicate stage posted\n' >&2; exit 1; }
  rm -f "$DIR/.telemetry-sent-install_start"
  COHORT=internal
  telemetry_emit install_start
  grep -q '"cohort":"internal"' "$log"
  exit 0 ;;
watch)
  DIR="${XONESH_SELFTEST_DIR:?}"
  mkdir -p "$DIR/fix"
  printf '0123456789abcdef0123456789abcdef\n' > "$DIR/.install-id"
  now=$(date +%s)
  printf '%s\n' "$now" > "$DIR/.install-started"
  write_watch_script
  printf '%s' '{"result":"0x2"}' > "$DIR/fix/net_peerCount"
  printf '%s' '{"result":"0x10"}' > "$DIR/fix/eth_blockNumber"
  printf '%s' '{"result":false}' > "$DIR/fix/eth_syncing"
  printf '%s' "{\"result\":{\"timestamp\":\"$(printf '0x%x' $((now - 30)))\"}}" > "$DIR/fix/eth_getBlockByNumber"
  sink="$DIR/sink"
  run_watch(){
    : > "$sink"
    rm -f "$DIR"/.telemetry-sent-*
    XONESH_WATCH_ONCE=1 XONESH_WATCH_SINK="$sink" XONESH_RPC_FIXTURE="$DIR/fix" \
      XONESH_WATCH_DIR="$DIR" XONESH_WATCH_RPC_PORT=8625 \
      XONESH_TELEMETRY_URL="http://collector.test/telemetry" \
      XONESH_WATCH_NETWORK=mainnet XONESH_WATCH_RUNTIME=binary XONESH_WATCH_MODE=snap \
      XONESH_WATCH_OS=linux-amd64 XONESH_WATCH_COHORT="" \
      XONESH_WATCH_INSTALLER="$XONE_SH_VERSION" XONESH_WATCH_XONE="$XONE_RS_VERSION" \
      bash "$DIR/telemetry-watch.sh"
  }
  run_watch
  grep -q '"stage":"first_peer"' "$sink"
  grep -q '"stage":"first_rpc"' "$sink"
  grep -q '"stage":"synced"' "$sink"
  cp "$sink" "$DIR/sink-ok"
  printf '%s' "{\"result\":{\"timestamp\":\"$(printf '0x%x' $((now - 120)))\"}}" > "$DIR/fix/eth_getBlockByNumber"
  run_watch
  grep -q '"stage":"first_rpc"' "$sink"
  if grep -q '"stage":"synced"' "$sink"; then printf 'stale head counted as synced\n' >&2; exit 1; fi
  printf '%s' '{"result":{"startingBlock":"0x1"}}' > "$DIR/fix/eth_syncing"
  printf '%s' "{\"result\":{\"timestamp\":\"$(printf '0x%x' $((now - 10)))\"}}" > "$DIR/fix/eth_getBlockByNumber"
  run_watch
  if grep -q '"stage":"synced"' "$sink"; then printf 'syncing node counted as synced\n' >&2; exit 1; fi
  printf '%s' '{"result":false}' > "$DIR/fix/eth_syncing"
  printf '%s\n' "$((now - 10800))" > "$DIR/.install-started"
  run_watch
  grep -q '"stage":"first_rpc"' "$sink"
  grep -q '"stage":"synced"' "$sink"
  printf '%s\n' "$((now - 22000))" > "$DIR/.install-started"
  run_watch
  [ ! -s "$sink" ] || { printf 'watcher kept going after 6h\n' >&2; exit 1; }
  _hn=$(hostname -s 2>/dev/null | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9' || true)
  if [ -n "$_hn" ] && grep -q "$_hn" "$DIR/telemetry-watch.sh" "$sink" "$DIR/.install-id"; then
    printf 'hostname leaked into the watcher\n' >&2
    exit 1
  fi
  exit 0 ;;
arm)
  unset XONESH_EXP
  INSTALL_ID="00000000000000000000000000000000"
  ARM=""
  assign_arm
  first="$ARM"
  ARM=""
  assign_arm
  [ "$ARM" = "$first" ] || { printf 'arm changed\n' >&2; exit 1; }
  case "$ARM" in control|treatment) ;; *) printf 'bad arm %s\n' "$ARM" >&2; exit 1 ;; esac
  c=0; t=0; i=""
  for i in 0 1 2 3 4 5 6 7 8 9 a b c d e f; do
    INSTALL_ID="${i}0000000000000000000000000000000"
    ARM=""
    assign_arm
    case "$ARM" in control) c=$((c+1));; treatment) t=$((t+1));; *) exit 1;; esac
  done
  if [ "$c" -eq 0 ] || [ "$t" -eq 0 ]; then printf 'split %s/%s\n' "$c" "$t" >&2; exit 1; fi
  XONESH_EXP=control
  assign_arm
  [ "$ARM" = control ]
  XONESH_EXP=treatment
  assign_arm
  [ "$ARM" = treatment ]
  XONESH_EXP=readiness
  assign_arm
  [ "$ARM" = treatment ]
  TELEMETRY=0
  assign_arm
  [ "$ARM" = treatment ]
  printf 'arm-ok %s/%s\n' "$c" "$t"
  exit 0 ;;
preflight-arch)
  PLATFORM=linux-ppc64
  BIN_FILE=""
  RUNTIME=binary
  DRY=1
  DIR="${XONESH_SELFTEST_DIR:-/tmp}"
  preflight_platform
  printf 'unsupported arch was allowed\n' >&2
  exit 1 ;;
log-rotate)
  LOG="${XONESH_SELFTEST_DIR:?}/node.log"
  rotate_log
  exit 0 ;;
wait-ok)
  DIR="${XONESH_SELFTEST_DIR:?}"
  mkdir -p "$DIR/fix"
  printf '%s' '{"jsonrpc":"2.0","result":"0x10","id":1}' > "$DIR/fix/eth_blockNumber"
  printf '%s' '{"jsonrpc":"2.0","result":"0x2","id":1}' > "$DIR/fix/net_peerCount"
  XONESH_RPC_FIXTURE="$DIR/fix"
  XONESH_SELFTEST_WAIT=1
  XONESH_WAIT_CAP=30
  NO_WAIT=0
  TTY=0
  TELEMETRY=0
  ARM=treatment
  RUNTIME=binary
  treatment_wait
  exit 0 ;;
wait-syncing)
  # snap sync: eth_blockNumber returns an error, eth_syncing answers
  DIR="${XONESH_SELFTEST_DIR:?}"
  mkdir -p "$DIR/fix"
  printf '%s' '{"jsonrpc":"2.0","error":{"code":-32000,"message":"snap sync in progress"},"id":1}' > "$DIR/fix/eth_blockNumber"
  printf '%s' '{"jsonrpc":"2.0","result":{"startingBlock":"0x0","currentBlock":"0x0","highestBlock":"0x0"},"id":1}' > "$DIR/fix/eth_syncing"
  XONESH_RPC_FIXTURE="$DIR/fix"
  XONESH_SELFTEST_WAIT=1
  XONESH_WAIT_CAP=30
  NO_WAIT=0
  TTY=0
  TELEMETRY=0
  ARM=treatment
  RUNTIME=binary
  treatment_wait
  exit 0 ;;
wait-timeout)
  DIR="${XONESH_SELFTEST_DIR:?}"
  mkdir -p "$DIR/fix"
  printf '%s' '{"jsonrpc":"2.0","error":{"code":-32000,"message":"not ready"},"id":1}' > "$DIR/fix/eth_blockNumber"
  printf '%s' '{"jsonrpc":"2.0","error":{"code":-32601,"message":"not ready"},"id":1}' > "$DIR/fix/eth_syncing"
  XONESH_RPC_FIXTURE="$DIR/fix"
  XONESH_SELFTEST_WAIT=1
  XONESH_WAIT_CAP=0
  NO_WAIT=0
  TTY=0
  TELEMETRY=0
  ARM=treatment
  RUNTIME=binary
  if treatment_wait; then
    printf 'timeout reported success\n' >&2
    exit 1
  fi
  exit 0 ;;
esac

case "$ACTION" in
  setup)    cmd_setup ;;
  start)    cmd_start ;;
  stop)     cmd_stop ;;
  restart)  cmd_stop; cmd_start ;;
  status)   cmd_status ;;
  logs)     cmd_logs ;;
  update)   cmd_update ;;
  resync)   cmd_resync ;;
  rollback) cmd_rollback ;;
  uninstall) cmd_uninstall ;;
  clients)  cmd_clients ;;
  networks) cmd_networks ;;
  version)  cmd_version ;;
  attach)   die "attach opens the geth console; xOneRS has none. Use the JSON-RPC at http://127.0.0.1:$RPC_PORT" ;;
esac
exit 0
}
