diff --git a/.github/workflows/node-status-test.yml b/.github/workflows/node-status-test.yml new file mode 100644 index 0000000..7b02704 --- /dev/null +++ b/.github/workflows/node-status-test.yml @@ -0,0 +1,27 @@ +name: Node status test + +on: + pull_request: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/checkout@v4 + with: + repository: dappnode/staker-package-scripts + ref: v0.1.3 + path: staker-package-scripts + - name: Test under dash + run: sh test/node_status_test.sh + env: + NODE_STATUS_TOOLS: ${{ github.workspace }}/staker-package-scripts/scripts/node_status_tools.sh + - name: Test under the image's shell (Debian bookworm dash, jq 1.6) + run: > + docker run --rm -v "$PWD:/work" -w /work debian:bookworm-slim sh -c + "apt-get update -qq && apt-get install -qq -y jq >/dev/null && + NODE_STATUS_TOOLS=/work/staker-package-scripts/scripts/node_status_tools.sh sh test/node_status_test.sh" diff --git a/README.md b/README.md index d80fb27..0abf095 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,10 @@ curl -X POST \ - `RUST_LOG`: Logging level - `PATHFINDER_DB_DIR`: Database directory +### Node status report + +The package reports Pathfinder's sync status (snapshot download and extraction, blocks left to the head, synced, and the latest block verified on Ethereum) through its Docker healthcheck, which the DAppNode dashboard reads to show the node's status. The healthcheck script is [`pathfinder/node-status.sh`](pathfinder/node-status.sh), installed in the image as `/usr/local/bin/node-status`; it uses the shared helpers from `dappnode/staker-package-scripts`. Its test is [`test/node_status_test.sh`](test/node_status_test.sh): run `sh test/node_status_test.sh` with a clone of `staker-package-scripts` next to this repository, or point `NODE_STATUS_TOOLS` at its `scripts/node_status_tools.sh`. + ### Storage Requirements - **Initial Sync**: ~50GB+ (varies by network and state size) diff --git a/dappnode_package.json b/dappnode_package.json index 9862b89..2dd368b 100644 --- a/dappnode_package.json +++ b/dappnode_package.json @@ -21,5 +21,12 @@ "type": "git", "url": "https://github.com/dappnode/DAppNodePackage-pathfinder-generic" }, - "license": "GPL-3.0" + "license": "GPL-3.0", + "nodes": { + "pathfinder": { + "role": "node", + "probe": { "kind": "status-report", "maxHeadAgeSeconds": 300 }, + "report": "healthcheck" + } + } } diff --git a/docker-compose.yml b/docker-compose.yml index e3b5429..425404b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -17,5 +17,11 @@ services: PATHFINDER_MONITOR_ADDRESS: 0.0.0.0:9547 volumes: - pathfinder-data:/usr/share/pathfinder/data + healthcheck: + test: ["CMD", "/usr/local/bin/node-status"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 60s volumes: pathfinder-data: {} diff --git a/package_variants/mainnet/dappnode_package.json b/package_variants/mainnet/dappnode_package.json index c30cc11..08d4656 100644 --- a/package_variants/mainnet/dappnode_package.json +++ b/package_variants/mainnet/dappnode_package.json @@ -12,5 +12,11 @@ "description": "JSON RPC endpoint for Pathfinder", "port": 9555 } - ] + ], + "nodes": { + "pathfinder": { + "network": "starknet", + "requires": [{ "network": "mainnet", "role": "execution" }] + } + } } diff --git a/package_variants/sepolia/dappnode_package.json b/package_variants/sepolia/dappnode_package.json index 3ae592e..335efed 100644 --- a/package_variants/sepolia/dappnode_package.json +++ b/package_variants/sepolia/dappnode_package.json @@ -17,5 +17,11 @@ "description": "WebSocket RPC endpoint for StarkNet Sepolia", "port": 6061 } - ] + ], + "nodes": { + "pathfinder": { + "network": "starknet-sepolia", + "requires": [{ "network": "sepolia", "role": "execution" }] + } + } } diff --git a/pathfinder/Dockerfile b/pathfinder/Dockerfile index 0718b0b..1e4b77a 100644 --- a/pathfinder/Dockerfile +++ b/pathfinder/Dockerfile @@ -5,11 +5,15 @@ FROM eqlabs/pathfinder:${UPSTREAM_VERSION} # Stay as root for everything USER root -# Install rclone and zstd -RUN apt-get update && apt-get install -y curl zstd unzip && \ +# Install rclone and zstd, and jq for the healthcheck +RUN apt-get update && apt-get install -y curl zstd unzip jq && \ curl https://rclone.org/install.sh | bash && \ apt-get clean && rm -rf /var/lib/apt/lists/* +# Healthcheck: prints the node status report (helpers from dappnode/staker-package-scripts) +ADD --chmod=644 https://github.com/dappnode/staker-package-scripts/releases/download/v0.1.3/node_status_tools.sh /etc/profile.d/node_status_tools.sh +COPY --chmod=755 node-status.sh /usr/local/bin/node-status + COPY --chmod=755 entrypoint.sh /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"] diff --git a/pathfinder/entrypoint.sh b/pathfinder/entrypoint.sh index 9d487b1..3eb8c09 100755 --- a/pathfinder/entrypoint.sh +++ b/pathfinder/entrypoint.sh @@ -24,6 +24,24 @@ esac TARGET_DB="${DATA_DIR}/${BASE}.sqlite" +# Read by the healthcheck (node-status) to report the snapshot download and extraction before +# Pathfinder serves its RPC +NODE_STATUS_DIR=/tmp/node-status +SNAPSHOT_MARKER="${NODE_STATUS_DIR}/snapshot" + +# A marker left by a container that was killed mid-download must not outlive that run +rm -f "${SNAPSHOT_MARKER}" || true + +# Writes the snapshot marker atomically. It never fails, so it cannot stop this script (set -e). +# Arguments: PID of the rclone or zstd process, phase, size of the compressed snapshot in bytes +write_snapshot_marker() { + { + mkdir -p "${NODE_STATUS_DIR}" && + printf 'pid=%s\nphase=%s\nsize=%s\n' "$1" "$2" "$3" >"${SNAPSHOT_MARKER}.tmp" && + mv -f "${SNAPSHOT_MARKER}.tmp" "${SNAPSHOT_MARKER}" + } 2>/dev/null || true +} + # Check if database already exists if [ -f "$TARGET_DB" ] && [ -s "$TARGET_DB" ]; then echo "✅ Database already exists at $TARGET_DB, skipping download" @@ -48,35 +66,43 @@ EOF if [ "$NETWORK" = "mainnet" ]; then # For mainnet, find latest mainnet_ file - SNAPSHOT_FILE=$(rclone ls pathfinder-snapshots:pathfinder-snapshots/ | \ + SNAPSHOT_LINE=$(rclone ls pathfinder-snapshots:pathfinder-snapshots/ | \ grep "mainnet_.*\.sqlite\.zst" | \ grep -v "_archive" | \ sort -k2 | \ - tail -1 | \ - awk '{print $2}') + tail -1) else # For sepolia, find latest from both naming patterns - SNAPSHOT_FILE=$(rclone ls pathfinder-snapshots:pathfinder-snapshots/ | \ + SNAPSHOT_LINE=$(rclone ls pathfinder-snapshots:pathfinder-snapshots/ | \ grep -E "(sepolia-testnet_|testnet-sepolia_).*\.sqlite\.zst" | \ grep -v "_archive" | \ sort -k2 | \ - tail -1 | \ - awk '{print $2}') + tail -1) fi + # rclone ls prints " "; the size lets the healthcheck measure progress + SNAPSHOT_FILE=$(echo "$SNAPSHOT_LINE" | awk '{print $2}') + SNAPSHOT_SIZE=$(echo "$SNAPSHOT_LINE" | awk '{print $1}') if [ -z "$SNAPSHOT_FILE" ]; then echo "❌ No snapshot found for network: $NETWORK" echo "🚀 Starting Pathfinder without snapshot..." else echo "⏬ Downloading $SNAPSHOT_FILE..." - rclone copy -P "pathfinder-snapshots:pathfinder-snapshots/$SNAPSHOT_FILE" . + # In the background only so that its PID can vouch for the marker; set -e still stops on failure + rclone copy -P "pathfinder-snapshots:pathfinder-snapshots/$SNAPSHOT_FILE" . & + SNAPSHOT_PID=$! + write_snapshot_marker "$SNAPSHOT_PID" "Downloading snapshot" "$SNAPSHOT_SIZE" + wait "$SNAPSHOT_PID" # Verify download if [ ! -f "$SNAPSHOT_FILE" ] || [ ! -s "$SNAPSHOT_FILE" ]; then echo "❌ Download failed. Starting Pathfinder without snapshot..." else echo "⏳ Decompressing snapshot..." - zstd -T0 -d "$SNAPSHOT_FILE" -o "${BASE}.sqlite" + zstd -T0 -d "$SNAPSHOT_FILE" -o "${BASE}.sqlite" & + SNAPSHOT_PID=$! + write_snapshot_marker "$SNAPSHOT_PID" "Extracting snapshot" "$SNAPSHOT_SIZE" + wait "$SNAPSHOT_PID" # Move to target location mkdir -p "$DATA_DIR" @@ -88,5 +114,7 @@ EOF fi fi +rm -f "${SNAPSHOT_MARKER}" || true + echo "🚀 Starting Pathfinder..." exec pathfinder "$@" diff --git a/pathfinder/node-status.sh b/pathfinder/node-status.sh new file mode 100644 index 0000000..005029b --- /dev/null +++ b/pathfinder/node-status.sh @@ -0,0 +1,136 @@ +#!/bin/sh + +# Node status report of the Pathfinder package, run as the Docker healthcheck. +# Prints one JSON line (see node_status_tools.sh in dappnode/staker-package-scripts): +# what Pathfinder is doing, from its own JSON-RPC and the snapshot marker the entrypoint +# leaves. Pathfinder is not an Ethereum client, so the report carries the verdict: the +# manifest declares this node as a status-report probe. +# +# Environment: +# NODE_STATUS_TOOLS: Helper library to source (default /etc/profile.d/node_status_tools.sh) +# NODE_STATUS_DIR: Directory of the snapshot marker (default /tmp/node-status) +# NODE_STATUS_PROC: Process information directory (default /proc) +# PATHFINDER_HTTP_RPC_ADDRESS: Pathfinder's own setting; the JSON-RPC port is taken from it + +# Every call gets 2 s, so even a node that stops answering midway stays well inside the 10 s timeout +NS_TIMEOUT=${NS_TIMEOUT:-2} + +# shellcheck source=/dev/null +. "${NODE_STATUS_TOOLS:-/etc/profile.d/node_status_tools.sh}" || exit 1 + +SNAPSHOT_MARKER="${NODE_STATUS_DIR:-/tmp/node-status}/snapshot" +PROC_DIR=${NODE_STATUS_PROC:-/proc} + +# A block older than this is not the chain head, whatever starknet_syncing says. Same value as +# probe.maxHeadAgeSeconds in dappnode_package.json; Starknet blocks come every few seconds. +MAX_HEAD_AGE_SECONDS=300 + +NS_RPC_PORT=${PATHFINDER_HTTP_RPC_ADDRESS##*:} +case $NS_RPC_PORT in +'' | *[!0-9]*) NS_RPC_PORT=6060 ;; +esac +# Pathfinder's own methods are served under this path, not on the root +PATHFINDER_RPC_PATH=/rpc/pathfinder/v0_1 + +# The JSON-RPC does not answer: the entrypoint downloads or extracts a database snapshot, or +# Pathfinder is opening (and migrating) its database. The marker counts only while the +# process it names runs, so a marker left by a failed or killed run is never trusted. Progress +# is the share of the compressed snapshot that process has written (rclone) or read (zstd). +report_starting() { + pid="" + phase="" + size="" + if [ -f "$SNAPSHOT_MARKER" ]; then + while IFS='=' read -r key value; do + case $key in + pid) pid=$value ;; + phase) phase=$value ;; + size) size=$value ;; + esac + done <"$SNAPSHOT_MARKER" + fi + case $phase in + "Downloading snapshot") command=rclone counter=wchar ;; + "Extracting snapshot") command=zstd counter=rchar ;; + *) phase="" ;; + esac + case $pid in + '' | *[!0-9]*) phase="" ;; + esac + if [ -z "$phase" ] || [ "$(process_name "$pid")" != "$command" ]; then + ns_emit starting + return + fi + progress="" + bytes=$(sed -n "s/^$counter:[[:space:]]*//p" "$PROC_DIR/$pid/io" 2>/dev/null) + case $size$bytes in + *[!0-9]*) ;; + *) + if [ "${size:-0}" -gt 0 ] && [ -n "$bytes" ]; then + permille=$((bytes * 1000 / size)) + progress="$((permille / 10)).$((permille % 10))" + fi + ;; + esac + ns_emit starting phase="$phase" progress="$progress" +} + +# Prints the program name of a running process (basename of its first argument), nothing when +# it does not run +process_name() { + name=$(tr '\0' '\n' 2>/dev/null <"$PROC_DIR/$1/cmdline" | head -n 1) + printf '%s\n' "${name##*/}" +} + +if ! syncing=$(ns_rpc starknet_syncing); then + report_starting + exit $? +fi + +# Stop at the first call that fails: each one can take the full timeout. An empty database has +# no latest block yet (Pathfinder answers with an error). +height="" +head_time="" +set -- +if block=$(ns_rpc starknet_getBlockWithTxHashes '["latest"]'); then + height=$(ns_hex_to_dec "$(ns_json_get "$block" .block_number)") + head_time=$(ns_hex_to_dec "$(ns_json_get "$block" .timestamp)") + # Latest block whose state update Pathfinder has seen on Ethereum (L1). ns_rpc only calls the + # root path, so this one is a plain curl with the same discipline. + if l1=$(curl -sfg --noproxy '*' --proto '=http' --max-time "$NS_TIMEOUT" --connect-timeout "$NS_TIMEOUT" \ + -H 'Content-Type: application/json' \ + --data '{"jsonrpc":"2.0","id":1,"method":"pathfinder_lastL1AcceptedBlockHashAndNumber","params":[]}' \ + "http://127.0.0.1:$NS_RPC_PORT$PATHFINDER_RPC_PATH"); then + verified=$(ns_json_get "$l1" ' + def commas: tostring | if length > 3 then (.[:-3] | commas) + "," + .[-3:] else . end; + .result.block_number | numbers | floor | commas') + [ -n "$verified" ] && set -- detail="Verified on Ethereum:Block $verified" + fi +fi + +fresh=false +case $head_time in +'' | *[!0-9]*) ;; +*) [ $(($(date +%s) - head_time)) -le "$MAX_HEAD_AGE_SECONDS" ] && fresh=true ;; +esac + +# starknet_syncing is false when Pathfinder is fewer than 6 blocks behind the head it last saw, +# but also before it first asked the gateway for the head, so only a recent block makes it synced +if [ "$syncing" = "false" ] && [ "$fresh" = true ]; then + ns_emit synced height="$height" headTime="$head_time" "$@" + exit $? +fi + +# The object: Pathfinder downloads and applies blocks one by one up to the head of the gateway +current=$(ns_json_get "$syncing" 'objects | .current_block_num') +highest=$(ns_json_get "$syncing" 'objects | .highest_block_num') +if [ -n "$current" ] && [ -n "$highest" ]; then + ns_emit syncing phase="Downloading blocks" position="$current" target="$highest" \ + height="$height" headTime="$head_time" "$@" + exit $? +fi + +# Not reporting progress, but its latest block is old (or there is none): the head age shows how +# far behind it is +ns_emit syncing height="$height" headTime="$head_time" "$@" +exit $? diff --git a/test/node_status_test.sh b/test/node_status_test.sh new file mode 100644 index 0000000..5fe0db9 --- /dev/null +++ b/test/node_status_test.sh @@ -0,0 +1,491 @@ +#!/bin/sh + +# Tests for pathfinder/node-status.sh, the healthcheck that prints the node status report, and +# for the snapshot marker written by pathfinder/entrypoint.sh +# Run from anywhere with any POSIX sh: sh test/node_status_test.sh +# Needs jq and the shared helpers of dappnode/staker-package-scripts, by default from a clone +# next to this repository; set NODE_STATUS_TOOLS to use another path. The entrypoint tests also +# need bash (the entrypoint's shell) and are skipped without it. +# Pathfinder is stubbed by a curl function that answers per JSON-RPC method, the clock by a date +# function, and the processes the marker names by a fake /proc directory. + +cd "$(dirname "$0")/.." || exit 1 +REPO=$PWD +NODE_STATUS_TOOLS=${NODE_STATUS_TOOLS:-$REPO/../staker-package-scripts/scripts/node_status_tools.sh} +case $NODE_STATUS_TOOLS in +/*) ;; +*) NODE_STATUS_TOOLS=$REPO/$NODE_STATUS_TOOLS ;; +esac +export NODE_STATUS_TOOLS +if [ ! -r "$NODE_STATUS_TOOLS" ]; then + echo "Shared helpers not found at $NODE_STATUS_TOOLS (set NODE_STATUS_TOOLS)" >&2 + exit 1 +fi +SCRIPT=$REPO/pathfinder/node-status.sh +ENTRYPOINT=$REPO/pathfinder/entrypoint.sh + +PASS=0 +FAIL=0 +TMP=$(mktemp -d) || exit 1 +HELPER_PIDS="" +# shellcheck disable=SC2329 # called by the EXIT trap +cleanup() { + for pid in $HELPER_PIDS; do kill "$pid" 2>/dev/null; done + rm -rf "$TMP" +} +trap cleanup EXIT +NODE_STATUS_DIR=$TMP/status +NODE_STATUS_PROC=$TMP/proc +mkdir -p "$NODE_STATUS_DIR" "$NODE_STATUS_PROC" +MARKER=$NODE_STATUS_DIR/snapshot +unset PATHFINDER_HTTP_RPC_ADDRESS NS_TIMEOUT + +# check +check() { + if [ "$2" = "$3" ]; then + PASS=$((PASS + 1)) + else + FAIL=$((FAIL + 1)) + printf 'FAIL: %s\n expected: %s\n actual: %s\n' "$1" "$2" "$3" + fi +} + +# Stub curl: records the URL, method and timeout of each call, then answers with R_SYNCING, +# R_BLOCK or R_L1 (a JSON-RPC result). An empty reply fails like a refused connection; the +# reply "error" is a JSON-RPC error. +# shellcheck disable=SC2329 # called by the script under test +curl() { + _url="" _data="" _max_time="" + while [ $# -gt 0 ]; do + case $1 in + --data) _data=$2 && shift ;; + --max-time) _max_time=$2 && shift ;; + http://*) _url=$1 ;; + esac + shift + done + _method=$(printf '%s' "$_data" | jq -r .method) + echo "$_method" >>"$TMP/calls" + echo "$_url" >>"$TMP/urls" + echo "$_max_time" >>"$TMP/timeouts" + case $_url:$_method in + */rpc/pathfinder/v0_1:pathfinder_lastL1AcceptedBlockHashAndNumber) _result=$R_L1 ;; + */rpc/pathfinder/v0_1:*) _result="" ;; + *:starknet_syncing) _result=$R_SYNCING ;; + *:starknet_getBlockWithTxHashes) _result=$R_BLOCK ;; + *) _result=error ;; + esac + case $_result in + "") return 7 ;; + error) printf '{"jsonrpc":"2.0","id":1,"error":{"code":32,"message":"There are no blocks"}}' ;; + *) printf '{"jsonrpc":"2.0","id":1,"result":%s}' "$_result" ;; + esac +} + +# Stub clock +NOW=1796050000 +# shellcheck disable=SC2329 # called by the script under test +date() { + echo "$NOW" +} + +# block : starknet_getBlockWithTxHashes result +block() { + printf '{"status":"ACCEPTED_ON_L2","block_hash":"0x1a","parent_hash":"0x19","block_number":%s,"new_root":"0x2","timestamp":%s,"sequencer_address":"0x3","transactions":["0x4"]}' "$1" "$2" +} + +# syncing : starknet_syncing object +syncing() { + printf '{"starting_block_hash":"0xa","starting_block_num":%s,"current_block_hash":"0xb","current_block_num":%s,"highest_block_hash":"0xc","highest_block_num":%s}' "$1" "$2" "$3" +} + +# A node at the head of mainnet, its block 10 s old, the last 100 blocks not yet verified on L1 +reset_node() { + R_SYNCING=false + R_BLOCK=$(block 2500000 $((NOW - 10))) + R_L1='{"block_hash":"0x5","block_number":2499900}' + rm -f "$MARKER" +} + +# Source the script, so that it sees the stubs; its exit leaves only the subshell it runs in +source_script() { + # shellcheck source=/dev/null + . "$SCRIPT" +} + +# Run the script with the stubs: sets OUT (stdout), RC, CALLS (methods called, comma separated) +run_script() { + : >"$TMP/calls" + : >"$TMP/urls" + : >"$TMP/timeouts" + OUT=$(source_script 2>"$TMP/stderr") + RC=$? + CALLS=$(paste -s -d, "$TMP/calls") +} + +# Prints true when $1 is a status report that respects the contract +report_valid() { + printf '%s' "$1" | jq -r ' + def count: type == "number" and . >= 0 and . == floor; + def text($n): type == "string" and length > 0 and length <= $n; + type == "object" + and .version == 1 + and (.state as $s | ["starting", "syncing", "synced", "error"] | index($s) != null) + and ((keys - ["version", "state", "phase", "progress", "height", "headTime", "position", "target", + "unit", "peers", "awaitingTarget", "background", "issues", "details"]) == []) + and (.phase == null or (.phase | text(60) and (endswith(".") | not))) + and (.progress == null or (.progress | type == "number" and . >= 0) + and .progress <= (if .state == "synced" then 100 else 99.9 end)) + and all(.height, .headTime, .position, .target, .peers; . == null or count) + and (.awaitingTarget == null or .awaitingTarget == true) + and (.background == null or (.background | text(60))) + and (.issues == null or (.issues | length <= 5 and all(.[]; text(120)))) + and (.details == null or (.details | length <= 8 and all(.[]; (.label | text(40)) and (.value | text(120))))) + and ((has("progress") and has("position")) | not) + and (tojson | utf8bytelength <= 2048) + ' 2>/dev/null +} + +# The report must be a single JSON line that respects the contract +check_contract() { + check "$1: one line" "1" "$(printf '%s\n' "$OUT" | wc -l | tr -d ' ')" + check "$1: valid report" "true" "$(report_valid "$OUT")" + check "$1: nothing on stderr" "" "$(cat "$TMP/stderr")" + check "$1: only local calls" "" "$(grep -v '^http://127\.0\.0\.1:' "$TMP/urls")" + check "$1: short timeouts" "" "$(grep -vx 2 "$TMP/timeouts")" +} + +# expect_report +expect_report() { + run_script + check "$1: report" "$2" "$OUT" + check "$1: exit code" "0" "$RC" + check "$1: calls" "$3" "$CALLS" + check_contract "$1" +} + +echo "Contract check" +check "rejects an unknown state" "false" "$(report_valid '{"version":1,"state":"waiting"}')" +check "rejects 100% while starting" "false" "$(report_valid '{"version":1,"state":"starting","progress":100}')" +check "rejects an unknown field" "false" "$(report_valid '{"version":1,"state":"synced","percent":3}')" +check "rejects a trailing period" "false" "$(report_valid '{"version":1,"state":"syncing","phase":"Downloading blocks."}')" +check "rejects progress with position" "false" "$(report_valid '{"version":1,"state":"syncing","progress":1,"position":2}')" +check "accepts a full report" "true" "$(report_valid '{"version":1,"state":"syncing","phase":"Downloading blocks","position":1,"target":2,"details":[{"label":"A","value":"b"}]}')" + +RPC="starknet_syncing,starknet_getBlockWithTxHashes" +ALL="$RPC,pathfinder_lastL1AcceptedBlockHashAndNumber" +AT_HEAD='"height":2500000,"headTime":'$((NOW - 10)) +VERIFIED='"details":[{"label":"Verified on Ethereum","value":"Block 2,499,900"}]' + +echo "Pathfinder not answering" +reset_node +R_SYNCING="" +expect_report "connection refused" '{"version":1,"state":"starting"}' "starknet_syncing" +R_SYNCING=error +expect_report "JSON-RPC error" '{"version":1,"state":"starting"}' "starknet_syncing" + +echo "Synced" +reset_node +expect_report "at the head" '{"version":1,"state":"synced",'"$AT_HEAD,$VERIFIED"'}' "$ALL" +check "at the head: RPC paths" "http://127.0.0.1:6060 http://127.0.0.1:6060 http://127.0.0.1:6060/rpc/pathfinder/v0_1" \ + "$(paste -s -d ' ' "$TMP/urls")" +R_BLOCK=$(block 2500000 $((NOW - 300))) +expect_report "latest block exactly at the age limit" \ + '{"version":1,"state":"synced","height":2500000,"headTime":'$((NOW - 300))",$VERIFIED}" "$ALL" +R_BLOCK=$(block 2500000 $((NOW + 5))) +expect_report "latest block from the future (clock skew)" \ + '{"version":1,"state":"synced","height":2500000,"headTime":'$((NOW + 5))",$VERIFIED}" "$ALL" +reset_node +R_L1=error +expect_report "nothing verified on L1 yet" '{"version":1,"state":"synced",'"$AT_HEAD"'}' "$ALL" +R_L1="" +expect_report "L1 call refused" '{"version":1,"state":"synced",'"$AT_HEAD"'}' "$ALL" +R_L1='{"block_hash":"0x5"}' +expect_report "L1 reply without a number" '{"version":1,"state":"synced",'"$AT_HEAD"'}' "$ALL" +R_L1='{"block_hash":"0x5","block_number":7}' +expect_report "small L1 number" '{"version":1,"state":"synced",'"$AT_HEAD"',"details":[{"label":"Verified on Ethereum","value":"Block 7"}]}' "$ALL" +reset_node +R_BLOCK='{"block_number":"0x2625a0","timestamp":"0x'"$(printf '%x' $((NOW - 10)))"'"}' +expect_report "hex quantities" '{"version":1,"state":"synced",'"$AT_HEAD,$VERIFIED"'}' "$ALL" + +echo "Not synced although starknet_syncing is false" +reset_node +R_BLOCK=$(block 2500000 $((NOW - 301))) +expect_report "latest block just over the age limit" \ + '{"version":1,"state":"syncing","height":2500000,"headTime":'$((NOW - 301))",$VERIFIED}" "$ALL" +R_BLOCK=$(block 2400000 $((NOW - 86400))) +expect_report "a day behind, before the first gateway poll" \ + '{"version":1,"state":"syncing","height":2400000,"headTime":'$((NOW - 86400))",$VERIFIED}" "$ALL" +R_BLOCK=error +expect_report "empty database, stops after the latest block fails" '{"version":1,"state":"syncing"}' "$RPC" +R_BLOCK="" +expect_report "latest block refused" '{"version":1,"state":"syncing"}' "$RPC" +R_BLOCK='{"block_number":2500000}' +expect_report "block without a timestamp" '{"version":1,"state":"syncing","height":2500000,'"$VERIFIED"'}' "$ALL" +reset_node +R_SYNCING=true +expect_report "starknet_syncing neither false nor an object" '{"version":1,"state":"syncing",'"$AT_HEAD,$VERIFIED"'}' "$ALL" + +echo "Downloading blocks" +reset_node +R_SYNCING=$(syncing 0 1200000 2500000) +R_BLOCK=$(block 1199999 1700000000) +R_L1=error +expect_report "far behind" \ + '{"version":1,"state":"syncing","phase":"Downloading blocks","height":1199999,"headTime":1700000000,"position":1200000,"target":2500000}' "$ALL" +R_SYNCING=$(syncing 2499000 2499994 2500000) +R_BLOCK=$(block 2499994 $((NOW - 12))) +R_L1='{"block_hash":"0x5","block_number":2499900}' +expect_report "6 blocks behind with a recent block is not synced" \ + '{"version":1,"state":"syncing","phase":"Downloading blocks","height":2499994,"headTime":'$((NOW - 12))',"position":2499994,"target":2500000,'"$VERIFIED"'}' "$ALL" +R_BLOCK="" +expect_report "latest block failing" \ + '{"version":1,"state":"syncing","phase":"Downloading blocks","position":2499994,"target":2500000}' "$RPC" + +echo "RPC port" +reset_node +PATHFINDER_HTTP_RPC_ADDRESS='[::]:9545' +run_script +check "port from PATHFINDER_HTTP_RPC_ADDRESS" "http://127.0.0.1:9545 http://127.0.0.1:9545 http://127.0.0.1:9545/rpc/pathfinder/v0_1" \ + "$(paste -s -d ' ' "$TMP/urls")" +PATHFINDER_HTTP_RPC_ADDRESS=0.0.0.0:6060 +run_script +check "port of the package compose" "http://127.0.0.1:6060" "$(head -n 1 "$TMP/urls")" +# shellcheck disable=SC2034 # read by the sourced script +PATHFINDER_HTTP_RPC_ADDRESS=garbage +run_script +check "unusable address falls back to 6060" "http://127.0.0.1:6060" "$(head -n 1 "$TMP/urls")" +unset PATHFINDER_HTTP_RPC_ADDRESS + +echo "Snapshot marker" +# fake_process ...: a process in the fake /proc ("-" for no io file) +fake_process() { + _pid=$1 _io=$2 + shift 2 + rm -rf "${NODE_STATUS_PROC:?}/$_pid" + mkdir -p "$NODE_STATUS_PROC/$_pid" + printf '%s\0' "$@" >"$NODE_STATUS_PROC/$_pid/cmdline" + [ "$_io" = - ] || printf '%s\n' "$_io" >"$NODE_STATUS_PROC/$_pid/io" +} +# io : /proc//io as Linux prints it +io() { + printf 'rchar: %s\nwchar: %s\nsyscr: 10\nsyscw: 20\nread_bytes: 0\nwrite_bytes: 4096\ncancelled_write_bytes: 0' "$1" "$2" +} +# write_marker : marker as the entrypoint writes it +write_marker() { + printf 'pid=%s\nphase=%s\nsize=%s\n' "$1" "$2" "$3" >"$MARKER" +} +reset_node +R_SYNCING="" +fake_process 4242 "$(io 5000 123456789)" rclone copy -P pathfinder-snapshots:pathfinder-snapshots/mainnet_0.14.0_2400000.sqlite.zst . +write_marker 4242 "Downloading snapshot" 1000000000 +expect_report "downloading" '{"version":1,"state":"starting","phase":"Downloading snapshot","progress":12.3}' "starknet_syncing" +fake_process 4242 "$(io 5000 123456789)" /usr/bin/rclone copy -P x . +expect_report "rclone run by its path" '{"version":1,"state":"starting","phase":"Downloading snapshot","progress":12.3}' "starknet_syncing" +fake_process 4242 "$(io 5000 1000004096)" rclone copy -P x . +expect_report "progress never 100 while running" '{"version":1,"state":"starting","phase":"Downloading snapshot","progress":99.9}' "starknet_syncing" +fake_process 4242 - rclone copy -P x . +expect_report "io not readable" '{"version":1,"state":"starting","phase":"Downloading snapshot"}' "starknet_syncing" +fake_process 4242 "$(io 5000 123456789)" rclone copy -P x . +write_marker 4242 "Downloading snapshot" "" +expect_report "size unknown" '{"version":1,"state":"starting","phase":"Downloading snapshot"}' "starknet_syncing" +write_marker 4242 "Downloading snapshot" "0" +expect_report "size zero" '{"version":1,"state":"starting","phase":"Downloading snapshot"}' "starknet_syncing" +fake_process 4343 "$(io 500000000 7000000000)" zstd -T0 -d mainnet_0.14.0_2400000.sqlite.zst -o mainnet.sqlite +write_marker 4343 "Extracting snapshot" 1000000000 +expect_report "extracting, measured by what zstd read" \ + '{"version":1,"state":"starting","phase":"Extracting snapshot","progress":50}' "starknet_syncing" + +echo "Stale snapshot marker" +write_marker 4444 "Downloading snapshot" 1000000000 +expect_report "process no longer runs" '{"version":1,"state":"starting"}' "starknet_syncing" +write_marker 4343 "Downloading snapshot" 1000000000 +expect_report "phase does not match the process" '{"version":1,"state":"starting"}' "starknet_syncing" +fake_process 4545 "$(io 1 1)" sleep 60 rclone +write_marker 4545 "Downloading snapshot" 1000000000 +expect_report "process with another name" '{"version":1,"state":"starting"}' "starknet_syncing" +fake_process 4646 "$(io 1 1)" bash /entrypoint.sh +write_marker 4646 "Downloading snapshot" 1000000000 +expect_report "the entrypoint itself does not vouch" '{"version":1,"state":"starting"}' "starknet_syncing" +write_marker "" "Downloading snapshot" 1000000000 +expect_report "marker without pid" '{"version":1,"state":"starting"}' "starknet_syncing" +write_marker "../4242" "Downloading snapshot" 1000000000 +expect_report "pid that is not a number" '{"version":1,"state":"starting"}' "starknet_syncing" +write_marker 4242 "Unpacking everything" 1000000000 +expect_report "unknown phase" '{"version":1,"state":"starting"}' "starknet_syncing" +printf 'garbage\n' >"$MARKER" +expect_report "garbage marker" '{"version":1,"state":"starting"}' "starknet_syncing" +reset_node +write_marker 4242 "Downloading snapshot" 1000000000 +expect_report "ignored once the RPC answers" '{"version":1,"state":"synced",'"$AT_HEAD,$VERIFIED"'}' "$ALL" + +echo "Snapshot marker with real processes" +reset_node +R_SYNCING="" +mkdir -p "$TMP/fake" +cp "$(command -v sleep)" "$TMP/fake/rclone" +"$TMP/fake/rclone" 60 & +REAL_PID=$! +HELPER_PIDS="$HELPER_PIDS $REAL_PID" +write_marker "$REAL_PID" "Downloading snapshot" 1000000000 +NODE_STATUS_PROC=/proc +run_script +check "running rclone: phase" '"Downloading snapshot"' "$(printf '%s' "$OUT" | jq -c .phase)" +# A process that wrote nothing yet shows 0, or no progress where /proc//io is not readable +case $(printf '%s' "$OUT" | jq -c .progress) in +0 | null) check "running rclone: progress" ok ok ;; +*) check "running rclone: progress" "0 or null" "$(printf '%s' "$OUT" | jq -c .progress)" ;; +esac +check_contract "running rclone" +kill "$REAL_PID" 2>/dev/null +wait "$REAL_PID" 2>/dev/null +run_script +check "finished rclone: plain starting" '{"version":1,"state":"starting"}' "$OUT" +NODE_STATUS_PROC=$TMP/proc + +echo "Run as a command" +mkdir -p "$TMP/bin" +printf '#!/bin/sh\nexit 7\n' >"$TMP/bin/curl" +chmod +x "$TMP/bin/curl" +rm -f "$MARKER" +OUT=$(PATH="$TMP/bin:$PATH" NODE_STATUS_DIR=$NODE_STATUS_DIR sh "$SCRIPT" 2>"$TMP/stderr") +RC=$? +check "command: report" '{"version":1,"state":"starting"}' "$OUT" +check "command: exit code" "0" "$RC" +check "command: nothing on stderr" "" "$(cat "$TMP/stderr")" +OUT=$(NODE_STATUS_TOOLS=/nonexistent sh "$SCRIPT" 2>/dev/null) +RC=$? +check "command: missing helpers print nothing" "" "$OUT" +check "command: missing helpers fail" "true" "$([ "$RC" -ne 0 ] && echo true)" + +echo "Entrypoint snapshot marker" +if ! command -v bash >/dev/null 2>&1; then + echo "SKIP: bash not found (the entrypoint's shell)" +else + EP=$TMP/ep + mkdir -p "$EP/bin" "$EP/work" "$EP/data" "$EP/rclone-config" "$EP/status" + # The entrypoint with its fixed paths moved under $EP + sed -e "s|/root/.config/rclone|$EP/rclone-config|g" -e "s|^NODE_STATUS_DIR=/tmp/node-status$|NODE_STATUS_DIR=$EP/status|" \ + "$ENTRYPOINT" >"$EP/entrypoint.sh" + check "entrypoint: paths moved for the test" "3" "$(grep -c "$EP/" "$EP/entrypoint.sh")" + EP_MARKER=$EP/status/snapshot + + # Stubs. rclone ls prints STUB_LISTING; rclone copy and zstd wait for the marker of their + # phase, save it and their PID, create their output and exit with STUB_COPY_STATUS or + # STUB_ZSTD_STATUS. pathfinder prints its arguments and whether a marker is left. + cat >"$EP/bin/rclone" </dev/null && [ \$i -lt 50 ]; do sleep 0.1; i=\$((i + 1)); done + cp "$EP_MARKER" "$EP/marker-copy" 2>/dev/null + echo \$\$ >"$EP/pid-copy" + [ "\${STUB_COPY_STATUS:-0}" = 0 ] || exit "\$STUB_COPY_STATUS" + [ -n "\$STUB_COPY_NOFILE" ] || echo compressed >"\${3##*/}" + exit 0 ;; +esac +exit 1 +EOF + cat >"$EP/bin/zstd" </dev/null && [ \$i -lt 50 ]; do sleep 0.1; i=\$((i + 1)); done +cp "$EP_MARKER" "$EP/marker-zstd" 2>/dev/null +echo \$\$ >"$EP/pid-zstd" +[ "\${STUB_ZSTD_STATUS:-0}" = 0 ] || exit "\$STUB_ZSTD_STATUS" +echo database >"\$5" +EOF + cat >"$EP/bin/pathfinder" < [VAR=value ...]: sets OUT (stdout and stderr) and RC + run_entrypoint() { + rm -f "$EP"/marker-* "$EP"/pid-* + _network=$1 + shift + OUT=$(cd "$EP/work" && env PATH="$EP/bin:$PATH" PATHFINDER_NETWORK="$_network" DATA_DIR="$EP/data" \ + STUB_LISTING="$LISTING" "$@" bash "$EP/entrypoint.sh" --arg 2>&1) + RC=$? + } + marker_of() { + tr '\n' ' ' <"$1" 2>/dev/null | sed 's/ $//' + } + + run_entrypoint mainnet + check "fresh: exit code" "0" "$RC" + check "fresh: marker while downloading" "pid=$(cat "$EP/pid-copy" 2>/dev/null) phase=Downloading snapshot size=1000000000" \ + "$(marker_of "$EP/marker-copy")" + check "fresh: marker while extracting" "pid=$(cat "$EP/pid-zstd" 2>/dev/null) phase=Extracting snapshot size=1000000000" \ + "$(marker_of "$EP/marker-zstd")" + check "fresh: database restored" "database" "$(cat "$EP/data/mainnet.sqlite" 2>/dev/null)" + check "fresh: snapshot removed" "" "$(ls "$EP/work")" + check "fresh: Pathfinder started with the arguments, marker removed" "pathfinder --arg" "$(printf '%s\n' "$OUT" | tail -n 1)" + + printf 'pid=1\nphase=Downloading snapshot\nsize=1\n' >"$EP_MARKER" + run_entrypoint mainnet + check "database exists: exit code" "0" "$RC" + check "database exists: no download" "" "$(ls "$EP"/pid-* 2>/dev/null)" + check "database exists: an old marker is removed" "pathfinder --arg" "$(printf '%s\n' "$OUT" | tail -n 1)" + rm -f "$EP/data/mainnet.sqlite" + + run_entrypoint sepolia-testnet + check "sepolia: snapshot of its own network" "size=300000000" "$(sed -n 3p "$EP/marker-copy" 2>/dev/null)" + check "sepolia: database restored" "database" "$(cat "$EP/data/testnet-sepolia.sqlite" 2>/dev/null)" + check "sepolia: Pathfinder started" "pathfinder --arg" "$(printf '%s\n' "$OUT" | tail -n 1)" + rm -f "$EP/data/testnet-sepolia.sqlite" + + LISTING_SAVED=$LISTING + LISTING="" + run_entrypoint mainnet + check "no snapshot listed: exit code" "0" "$RC" + check "no snapshot listed: Pathfinder started without marker" "pathfinder --arg" "$(printf '%s\n' "$OUT" | tail -n 1)" + LISTING=$LISTING_SAVED + + run_entrypoint mainnet STUB_COPY_NOFILE=1 + check "download without file: Pathfinder started without snapshot" "pathfinder --arg" "$(printf '%s\n' "$OUT" | tail -n 1)" + + run_entrypoint mainnet STUB_COPY_STATUS=3 + check "download fails: exit status of rclone, as before" "3" "$RC" + check "download fails: Pathfinder not started, as before" "" "$(printf '%s\n' "$OUT" | grep '^pathfinder')" + # The marker stays, but names a process that is gone + reset_node + R_SYNCING="" + NODE_STATUS_DIR=$EP/status + NODE_STATUS_PROC=/proc + run_script + check "download fails: marker left behind" "true" "$([ -f "$EP_MARKER" ] && echo true)" + check "download fails: the marker left is not trusted" '{"version":1,"state":"starting"}' "$OUT" + NODE_STATUS_DIR=$TMP/status + NODE_STATUS_PROC=$TMP/proc + + run_entrypoint mainnet STUB_ZSTD_STATUS=1 + check "extraction fails: exit status of zstd, as before" "1" "$RC" + check "extraction fails: Pathfinder not started, as before" "" "$(printf '%s\n' "$OUT" | grep '^pathfinder')" + rm -f "$EP"/work/* + + # The marker writer never stops the entrypoint (set -e), even when it cannot write (a + # directory below a regular file cannot be created, not even by root) + : >"$EP/file" + OUT=$(bash -c 'set -e + eval "$(sed -n "/^write_snapshot_marker() {/,/^}/p" "$1")" + NODE_STATUS_DIR=$2/dir SNAPSHOT_MARKER=$2/dir/snapshot + write_snapshot_marker 1 "Downloading snapshot" 2 + echo continued' sh "$ENTRYPOINT" "$EP/file" 2>&1) + check "marker writer cannot fail" "continued" "$OUT" +fi + +echo +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ]