Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .github/workflows/node-status-test.yml
Original file line number Diff line number Diff line change
@@ -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 (the shell of the Debian image)
run: sh test/node_status_test.sh
env:
NODE_STATUS_TOOLS: ${{ github.workspace }}/staker-package-scripts/scripts/node_status_tools.sh
- name: Test under dash with the jq of the image (Debian trixie)
run: >
docker run --rm -v "$PWD:/work" -w /work debian:trixie-slim sh -c
"apt-get update -qq && apt-get install -y -qq --no-install-recommends jq >/dev/null &&
NODE_STATUS_TOOLS=/work/staker-package-scripts/scripts/node_status_tools.sh sh test/node_status_test.sh"
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ by default BTC_TXINDEX is 0, but the installation of the DAppNodePackage will se
value larger than 550 (550Mb) , for example BTC_PRUNE=30000 to maintain only 30Gb of full blockchain data.
```

## Node status report

The package reports Bitcoin Core's sync status (start-up, header and block download, catching up, index building and assumeutxo background validation) through its Docker healthcheck, which the dappmanager reads to show the node's status. The healthcheck script is [`src/node-status.sh`](src/node-status.sh), installed in the image as `/usr/local/bin/node-status`; it calls the RPC on `127.0.0.1` with the `BTC_RPCUSER` / `BTC_RPCPASSWORD` credentials and 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`.

## License

This project is licensed under the GNU General Public License v3.0 - see the [LICENSE](LICENSE) file for details
Expand Down
11 changes: 11 additions & 0 deletions dappnode_package.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"architectures": [
"linux/amd64",
Expand Down Expand Up @@ -27,6 +27,17 @@
"homepage": "https://github.com/dappnode/DAppNodePackage-bitcoin#readme"
},
"name": "bitcoin.dnp.dappnode.eth",
"nodes": {
"bitcoin.dnp.dappnode.eth": {
"role": "node",
"network": "bitcoin",
"probe": {
"kind": "status-report",
"maxHeadAgeSeconds": 7200
},
"report": "healthcheck"
}
},
"repository": {
"type": "git",
"url": "https://github.com/dappnode/DAppNodePackage-bitcoin.git"
Expand Down
6 changes: 6 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,11 @@ services:
- BTC_RPCALLOWIP=172.33.0.0/16
- P2P_PORT=8340
restart: always
healthcheck:
test: ["CMD", "/usr/local/bin/node-status"]
interval: 30s
timeout: 10s
retries: 3
start_period: 60s
volumes:
bitcoin_data: {}
9 changes: 9 additions & 0 deletions src/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,15 @@ EXPOSE 8332 8333 18332 18333 28332 28333

COPY --from=binary /bitcoin/bin/bitcoind /usr/local/bin/

# Node status report printed by the healthcheck, with the shared helpers of dappnode/staker-package-scripts
ARG STAKER_SCRIPTS_VERSION=v0.1.3
ADD https://github.com/dappnode/staker-package-scripts/releases/download/${STAKER_SCRIPTS_VERSION}/node_status_tools.sh /etc/profile.d/node_status_tools.sh
COPY node-status.sh /usr/local/bin/node-status

RUN apt-get update && apt-get install -y --no-install-recommends curl jq && \
rm -rf /var/lib/apt/lists/* && \
chmod 0755 /usr/local/bin/node-status /etc/profile.d/node_status_tools.sh

ADD ./docker_entrypoint.sh /usr/local/bin/docker_entrypoint.sh
RUN chmod a+x /usr/local/bin/docker_entrypoint.sh

Expand Down
211 changes: 211 additions & 0 deletions src/node-status.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
#!/bin/sh

# Node status report of the Bitcoin package, run as the Docker healthcheck.
# Prints one JSON line (see the node status contract) telling whether Bitcoin
# Core is synced, which sync phase it is in and how far along. The package
# declares the node with the "status-report" probe, so the state printed here
# is the verdict the dappmanager shows.
#
# Bitcoin Core, as of v32.1:
# - The JSON-RPC needs the credentials the entrypoint writes to bitcoin.conf
# from BTC_RPCUSER and BTC_RPCPASSWORD (no cookie file is written when a
# password is set). They reach curl through its stdin, never its arguments.
# - Until the block index is loaded and the latest blocks are verified, every
# call fails with error -28 (RPC_IN_WARMUP) and a message saying what it does.
# - Initial block download fetches the headers first: blocks stay at 0 while
# the headers are pre-synchronised and downloaded. Then the blocks, whose
# progress verificationprogress estimates by transaction count.
# - initialblockdownload turns false once the tip is less than a day old and
# stays false until a restart, so a node that falls behind later is caught by
# the age of its tip and by the headers it knows ahead of it.
# - Work that goes on at the head: an index (txindex, enabled by this package,
# or one the user adds) building after being turned on, and the background
# validation of an assumeutxo snapshot (backgroundvalidation, v32+).
#
# Environment:
# NODE_STATUS_TOOLS: Path of the shared helpers (default /etc/profile.d/node_status_tools.sh)
# BTC_RPCUSER, BTC_RPCPASSWORD, BTC_RPCPORT: Read by the entrypoint too (defaults dappnode, dappnode, 8332)
# NS_TIMEOUT: Timeout in seconds of the single request (default 5)

# A single request, so it can wait a little longer than the helpers' default
# while Bitcoin Core holds its main lock to connect a block or flush its cache
NS_TIMEOUT=${NS_TIMEOUT:-5}

# shellcheck source=/dev/null
. "${NODE_STATUS_TOOLS:-/etc/profile.d/node_status_tools.sh}" || exit 1

# Same value as probe.maxHeadAgeSeconds in dappnode_package.json: blocks come
# every 10 minutes on average, gaps of more than 2 hours are very rare
MAX_HEAD_AGE=7200
# Headers known ahead of the tip that still count as at the head: about an hour
MAX_BLOCKS_BEHIND=6

RPC_URL="http://127.0.0.1:${BTC_RPCPORT:-8332}/"
REQUEST='[{"jsonrpc":"2.0","id":"chain","method":"getblockchaininfo"},'\
'{"jsonrpc":"2.0","id":"net","method":"getnetworkinfo"},'\
'{"jsonrpc":"2.0","id":"index","method":"getindexinfo"}]'

# Escape a value for a double-quoted string of a curl config file
curl_quote() {
printf '%s' "$1" | sed 's/[\\"]/\\&/g'
}

# Send the batch request and print the body followed by the HTTP status on its
# own line. The credentials go to curl as a config file on stdin (printf is a
# shell builtin), so they never show in the process list. Returns curl's exit code.
rpc_batch() {
printf 'user = "%s:%s"\n' "$(curl_quote "${BTC_RPCUSER:-dappnode}")" \
"$(curl_quote "${BTC_RPCPASSWORD:-dappnode}")" |
curl -sg -K - --noproxy '*' --proto '=http' \
--max-time "$NS_TIMEOUT" --connect-timeout "$NS_TIMEOUT" \
-H 'Content-Type: application/json' --data "$REQUEST" \
-w '\n%{http_code}' "$RPC_URL"
}

# Print the result (compact JSON) or the error of the reply with id $1
reply_field() {
printf '%s\n' "$body" | jq -c --arg id "$1" --arg f "$2" \
'first(.[] | select(type == "object" and .id == $id)) | .[$f] // empty' 2>/dev/null
}

# Print the integer value of $1 in the getblockchaininfo result, nothing when absent
chain_int() {
ns_json_get "$chain" ".$1 | select(type == \"number\") | floor"
}

set --

reply=$(rpc_batch)
rc=$?
if [ "$rc" -eq 28 ]; then
# Bitcoin Core accepts connections but does not answer in time: busy, nothing to tell
echo "[ERROR - node-status] Bitcoin Core did not answer within ${NS_TIMEOUT}s" >&2
exit 1
fi
if [ "$rc" -ne 0 ]; then
# Nothing listens on the RPC port yet: the node is starting
ns_emit starting
exit $?
fi

status=${reply##*[!0-9]}
body=${reply%"$status"}
case $status in
200) ;;
401)
ns_emit error issue="Bitcoin Core rejected the RPC credentials"
exit $?
;;
*)
# 503 when the RPC work queue is full, anything else is unexpected
echo "[ERROR - node-status] Bitcoin Core answered with HTTP status ${status:-none}" >&2
exit 1
;;
esac

chain=$(reply_field chain result)
if [ -z "$chain" ]; then
error=$(reply_field chain error)
if [ "$(ns_json_get "$error" .code)" = "-28" ]; then
# Warming up; the message says what it does, e.g. "Loading block index…"
phase=$(ns_json_get "$error" '.message | strings | sub("(…|[.])+$"; "")
| select(test("^[A-Za-z][A-Za-z0-9 ,/()-]{0,59}$"))')
ns_emit starting phase="$phase"
exit $?
fi
code=$(ns_json_get "$error" .code)
echo "[ERROR - node-status] getblockchaininfo failed: ${code:-no result}" >&2
exit 1
fi

# Issues Bitcoin Core reports about itself (an array since v28, a string with
# -deprecatedrpc=warnings)
warnings=$(ns_json_get "$chain" '.warnings | if type == "string" then [.] else . end
| .[] | strings | gsub("[[:cntrl:]]+"; " ") | select(test("[^ ]"))')
while IFS= read -r warning; do
[ -n "$warning" ] && set -- "$@" "issue=$warning"
done <<EOF
$warnings
EOF

net=$(reply_field net result)
peers=$(ns_json_get "$net" '.connections | numbers')
[ "$(ns_json_get "$net" .networkactive)" = "false" ] && set -- "$@" "issue=Network activity is disabled"

blocks=$(chain_int blocks)
headers=$(chain_int headers)
head_time=$(chain_int time)
ibd=$(ns_json_get "$chain" .initialblockdownload)
[ "$(ns_json_get "$chain" .pruned)" = "true" ] && set -- "$@" "detail=Pruned:yes"
network=$(ns_json_get "$chain" '.chain | strings')
[ -n "$network" ] && [ "$network" != "main" ] && set -- "$@" "detail=Network:$network"

if [ -z "$blocks" ] || [ -z "$head_time" ]; then
echo "[ERROR - node-status] getblockchaininfo has no blocks or time" >&2
exit 1
fi
[ -n "$headers" ] && [ "$headers" -lt 0 ] && headers=""
ahead=0
[ -n "$headers" ] && [ "$headers" -gt "$blocks" ] && ahead=$((headers - blocks))
age=$(($(date +%s) - head_time))

# Work going on next to the sync, most important first
background=""
snapshot=$(ns_json_get "$chain" '.backgroundvalidation | objects')
if [ -n "$snapshot" ]; then
background="Validating UTXO snapshot"
percent=$(ns_json_get "$snapshot" '.verificationprogress | numbers | [. * 1000 | floor / 10, 99.9] | min | tostring + "%"')
[ -n "$percent" ] && set -- "$@" "detail=Snapshot validated:$percent"
fi
indexes=$(ns_json_get "$(reply_field index result)" 'to_entries[]
| select(.value | type == "object" and .synced == false) | "\(.key):\(.value.best_block_height // 0)"')
if [ -n "$indexes" ]; then
count=0
while IFS=: read -r name height; do
count=$((count + 1))
case $name in
txindex) job="transaction index" ;;
coinstatsindex) job="coin statistics index" ;;
txospenderindex) job="spent outputs index" ;;
*"block filter index") job="block filter index" ;;
*) job="index" ;;
esac
set -- "$@" "detail=Building $job:at block $height"
done <<EOF
$indexes
EOF
if [ -z "$background" ]; then
background="Building $job"
[ "$count" -gt 1 ] && background="Building indexes"
fi
fi

target=""
[ "$ahead" -gt 0 ] && target=$headers

if [ "$ibd" = "true" ]; then
if [ "$blocks" -eq 0 ]; then
# Blocks wait until enough headers are known and checked
ns_emit syncing phase="Downloading block headers" height="$blocks" headTime="$head_time" \
target="$target" peers="$peers" background="$background" "$@"
exit $?
fi
progress=$(ns_json_get "$chain" '.verificationprogress | numbers | . * 100')
ns_emit syncing phase="Downloading blocks" progress="$progress" height="$blocks" \
headTime="$head_time" target="$target" peers="$peers" background="$background" "$@"
exit $?
fi

# Out of initial block download: synced only while the tip is recent and no
# more than a few known headers are ahead of it
if [ "$age" -gt "$MAX_HEAD_AGE" ] || [ "$ahead" -gt "$MAX_BLOCKS_BEHIND" ]; then
position=""
[ -n "$target" ] && position=$blocks
ns_emit syncing phase="Catching up" height="$blocks" headTime="$head_time" position="$position" \
target="$target" peers="$peers" background="$background" "$@"
exit $?
fi

ns_emit synced height="$blocks" headTime="$head_time" target="$target" peers="$peers" \
background="$background" "$@"
exit $?
Loading
Loading