From 3bedf8754a9455c8896d1445b44e11fbdebdd2a2 Mon Sep 17 00:00:00 2001 From: TheTrunk Date: Wed, 21 Oct 2026 16:19:27 +0800 Subject: [PATCH 01/15] v3: pinned image, peer snapshots, fix data-wiping maintenance jobs Every new container built RocksDB and blockbook from trezor/blockbook master and downloaded whatever daemon master named, on Debian 11. Upstream moved on: Bitcoin Cash Node 29 needs glibc 2.34 and exits at once, Zcash moved to Zebra with no download URL, geth templates gained {{.Env.RPCBindHost}} (ETC started with "lookup null"), and instances of one app ran different versions. - Build blockbook, RocksDB and all coin configs into the image at a pinned commit on Debian 12; copy zebrad from zfnd/zebra. overrides.json pins fluxd 9.1.0, BCHN 29.2.0, DigiByte 8.26.2 and live addnodes for BTG, DGB and VIA (their shipped seeds are dead). Re-render configs and fetch the pinned daemon when the image changes. - corruption.sh wiped the whole backend on routine peer messages (invalid header received, InvalidChainFound); only real database errors now. - log_clean emptied LevelDB/RocksDB write-ahead logs (any *.log over 20 MB), which corrupts the databases; only named logs now. - The cron jobs looped forever on $HOME and piled up ~1,650 processes per container; one /etc/cron.d file with flock now. - -dbcache=500 gave RocksDB a 500 byte cache; default 512 MiB, 4 workers. - heal.sh: reconsiderblock when the daemon has marked the real chain invalid (blockbookflux instances stuck at 2263328 since January). - Peer snapshots: synced instances serve a hard-link snapshot on port 1337 to the app's other instances, which seed from it instead of block 0. - PRUNE_BACKEND=1: Bitcoin's blocks (886 GB) exceed the 820 GB Flux app limit, so bitcoind runs with manual pruning kept just behind blockbook (prune.sh). patches/0001 (blockbook -prunedbackend) gets a confirmed transaction from the block the index places it in and downloads a pruned block again from an archival peer (getblockfrompeer), so transactions, histories, tx-specific and blocks stay complete. History pages fetch in parallel, at most 8 downloads run at once, the tx cache is emptied past TXCACHE_MAX_GB (20), and the index stores vsizes for when no peer answers. Without the extended index (~245 GB of Trezor's 1.1 TB Bitcoin index) the index is ~640 GB and fits. New-block websocket notifications resolve inputs from the index instead of the backend. - corruption.sh also clears an index blockbook refuses to open (another coin, other index settings), and on a pruned backend rebuilds the backend with it when no peer can provide the index. - CI builds, runs an end-to-end regtest smoke test, and pushes v* tags to ghcr.io. --- .github/workflows/docker.yml | 64 ++ .gitignore | 1 + Dockerfile | 166 +++-- README.md | 35 ++ blockbook.sh | 41 +- build.sh | 175 ++---- consensus.sh | 29 +- corruption.sh | 89 ++- daemon.sh | 307 ++++------ heal.sh | 51 ++ overrides.json | 45 ++ patches/0001-pruned-backend.patch | 963 ++++++++++++++++++++++++++++++ prune.sh | 42 ++ snapshot.sh | 251 ++++++++ snapshot_server.py | 108 ++++ supervisord.conf | 91 +-- test/smoke.sh | 131 ++++ utils.sh | 10 +- 18 files changed, 2103 insertions(+), 496 deletions(-) create mode 100644 .github/workflows/docker.yml create mode 100644 .gitignore create mode 100755 heal.sh create mode 100644 overrides.json create mode 100644 patches/0001-pruned-backend.patch create mode 100755 prune.sh create mode 100755 snapshot.sh create mode 100755 snapshot_server.py create mode 100755 test/smoke.sh diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 0000000..9b59010 --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,64 @@ +name: image + +on: + push: + branches: ['**'] + tags: ['v*'] + pull_request: + workflow_dispatch: + +permissions: + contents: read + packages: write + +jobs: + build: + runs-on: ubuntu-latest + timeout-minutes: 120 + env: + GHCR_IMAGE: ghcr.io/runonflux/blockbook-docker + HUB_IMAGE: runonflux/blockbook-docker + HAS_HUB: ${{ secrets.DOCKERHUB_USERNAME != '' && secrets.DOCKERHUB_TOKEN != '' }} + steps: + - uses: actions/checkout@v4 + + - name: Shell syntax + run: for f in *.sh test/*.sh; do bash -n "$f"; done && python3 -m py_compile snapshot_server.py + + - uses: docker/setup-buildx-action@v3 + + - name: Build + uses: docker/build-push-action@v6 + with: + context: . + load: true + tags: blockbook-docker:test + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Smoke test + run: bash test/smoke.sh blockbook-docker:test + + - name: Log in to ghcr.io + if: startsWith(github.ref, 'refs/tags/v') + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Log in to Docker Hub + if: startsWith(github.ref, 'refs/tags/v') && env.HAS_HUB == 'true' + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Push + if: startsWith(github.ref, 'refs/tags/v') + run: | + TAG=${GITHUB_REF_NAME} + for image in $GHCR_IMAGE $([ "$HAS_HUB" = "true" ] && echo $HUB_IMAGE); do + docker tag blockbook-docker:test $image:$TAG + docker push $image:$TAG + done diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c18dd8d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__/ diff --git a/Dockerfile b/Dockerfile index 88f20ad..a8f7b34 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,72 +1,114 @@ -FROM debian:11 -ENV DEBIAN_FRONTEND noninteractive +# Blockbook + coin daemon launcher for Flux. +# +# Blockbook, RocksDB and every coin's config files are built into the image at +# a pinned upstream commit, so all instances of an app run the same code and a +# container starts in seconds instead of compiling for half an hour. Daemon +# binaries are still downloaded on first start, from the URL pinned in the +# coin config of that same commit (plus overrides.json). +ARG ZEBRA_VERSION=6.4.2 -RUN apt-get update && \ - apt-get upgrade -y && \ - apt-get install -y git wget autoconf automake jq bc supervisor procps curl \ - graphviz libsnappy-dev libzstd-dev zlib1g-dev libbz2-dev liblz4-dev libunwind-dev \ - bsdmainutils build-essential g++-multilib libc6-dev pv libarchive-tools cron unzip libtool \ - m4 ncurses-dev pkg-config python3 python3-zmq zlib1g-dev libzmq3-dev libgflags-dev +FROM zfnd/zebra:${ZEBRA_VERSION} AS zebra -ENV BLOCKBOOKGIT_URL=${BLOCKBOOKGIT_URL:-https://github.com/trezor/blockbook.git} -ENV TAG=${TAG:-master} -ENV RPC_USER=${RPC_USER:-user} -ENV RPC_PASS=${RPC_PASS:-pass} -ENV HOME=/opt -ENV BOOTSTRAP=${BOOTSTRAP:-0} -ENV DAEMON=${DAEMON:-1} -ENV CONFIG=${CONFIG:-AUTO} -ENV GOLANG_VERSION="go1.23.7" -ENV ROCKSDB_VERSION=${ROCKSDB_VERSION:-v9.10.0} -ENV DAEMON_CONFIG=${DAEMON_CONFIG:-AUTO} -ENV GOPATH=$HOME/go -ENV PATH=$PATH:$GOPATH/bin -ENV CGO_CFLAGS="-I$HOME/rocksdb/include -O -D__BLST_PORTABLE__" -ENV CGO_LDFLAGS="-L$HOME/rocksdb -lrocksdb -lstdc++ -lm -lz -ldl -lbz2 -lsnappy -llz4 -lzstd" -ENV CGO_CFLAGS_ALLOW="-O -D__BLST_PORTABLE__" +FROM debian:12 AS build +SHELL ["/bin/bash", "-o", "pipefail", "-c"] +ARG BLOCKBOOK_REPO=https://github.com/trezor/blockbook.git +ARG BLOCKBOOK_COMMIT=3e6a90a287fb4e6d597978baf0aceeec985b5e41 +ARG GOLANG_VERSION=go1.25.4 +ARG GOLANG_SHA256=9fa5ffeda4170de60f67f3aa0f824e426421ba724c21e133c1e35d6159ca1bec +ARG ROCKSDB_VERSION=v9.10.0 +ENV DEBIAN_FRONTEND=noninteractive -# Install GOLANG -RUN echo "Installing GOLANG [$GOLANG_VERSION]..." && \ - cd /opt && wget https://dl.google.com/go/$GOLANG_VERSION.linux-amd64.tar.gz && \ - tar xf $GOLANG_VERSION.linux-amd64.tar.gz && \ - rm $GOLANG_VERSION.linux-amd64.tar.gz -RUN ln -s /opt/go/bin/go /usr/bin/go -RUN mkdir -p $GOPATH -RUN echo -n "GO version: " && go version -RUN echo -n "GOPATH: " && echo $GOPATH +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential ca-certificates git wget jq pkg-config libzmq3-dev libgflags-dev \ + libsnappy-dev zlib1g-dev libbz2-dev libzstd-dev liblz4-dev libjemalloc-dev && \ + rm -rf /var/lib/apt/lists/* -# Install RocksDB -#RUN echo "Installing RocksDB [$ROCKSDB_VERSION]..." && \ -#cd $HOME && git clone -b $ROCKSDB_VERSION --depth 1 https://github.com/facebook/rocksdb.git && \ -#cd $HOME/rocksdb && CFLAGS=-fPIC CXXFLAGS='-fPIC -Wno-error=deprecated-copy -Wno-error=pessimizing-move -Wno-error=class-memaccess' PORTABLE=1 make -j 4 release +RUN cd /opt && wget -q https://dl.google.com/go/${GOLANG_VERSION}.linux-amd64.tar.gz && \ + echo "${GOLANG_SHA256} ${GOLANG_VERSION}.linux-amd64.tar.gz" | sha256sum -c - && \ + tar xf ${GOLANG_VERSION}.linux-amd64.tar.gz && rm ${GOLANG_VERSION}.linux-amd64.tar.gz +ENV PATH=$PATH:/opt/go/bin GOPATH=/go GOTOOLCHAIN=local -# Install BlockBook -#RUN echo "Installing BlockBook..." && \ -#REPO_UNCAT=${BLOCKBOOKGIT_URL##*/} && \ -#REPO=${REPO_UNCAT%%.*} && \ -#GIT_USER=$(echo "$BLOCKBOOKGIT_URL" | grep -oP "(?<=github.com.)\w+(?=.$REPO)"); \ -#VERSION=$(curl -ssL https://raw.githubusercontent.com/$GIT_USER/$REPO/$TAG/configs/environ.json | jq -r .version); \ -#echo -e "REPO: $REPO, VERSION: $VERSION" && \ -#cd $HOME && git clone $BLOCKBOOKGIT_URL && \ -#cd $HOME/blockbook && \ -#git checkout "$TAG" && \ -#go mod download && \ -#BUILDTIME=$(date --iso-8601=seconds); GITCOMMIT=$(git describe --always --dirty); \ -#LDFLAGS="-X github.com/trezor/blockbook/common.version=${VERSION}-${TAG} -X github.com/trezor/blockbook/common.gitcommit=${GITCOMMIT} -X github.com/trezor/blockbook/common.buildtime=${BUILDTIME}" && \ -#go build -tags rocksdb_6_16 -ldflags="-s -w ${LDFLAGS}" +# PORTABLE: Flux nodes run on every kind of CPU, and an instruction the build +# host has but the node lacks is a SIGILL at start. +RUN git clone -b ${ROCKSDB_VERSION} --depth 1 https://github.com/facebook/rocksdb.git /opt/rocksdb && \ + cd /opt/rocksdb && ROCKSDB_DISABLE_JEMALLOC=1 CFLAGS=-fPIC CXXFLAGS=-fPIC PORTABLE=1 \ + DISABLE_WARNING_AS_ERROR=1 make -j"$(nproc)" release && strip ldb -COPY build.sh /build.sh -COPY daemon.sh /daemon.sh -COPY blockbook.sh /blockbook.sh -COPY check-health.sh /check-health.sh -COPY consensus.sh /consensus.sh -COPY utils.sh /utils.sh -COPY corruption.sh /corruption.sh +RUN git clone ${BLOCKBOOK_REPO} /src/blockbook && cd /src/blockbook && git checkout ${BLOCKBOOK_COMMIT} +WORKDIR /src/blockbook +COPY patches /tmp/patches +RUN for p in /tmp/patches/*.patch; do git apply --verbose "$p" || exit 1; done +RUN go mod download +# patches/0001 against a fake pruned bitcoind +RUN go test -count=1 -run 'Pruned' ./bchain/coins/btc/ -RUN chmod 755 /blockbook.sh /daemon.sh /build.sh /check-health.sh /consensus.sh /utils.sh /corruption.sh -RUN mkdir -p /var/log/supervisor +ENV CGO_CFLAGS="-I/opt/rocksdb/include -O -D__BLST_PORTABLE__" \ + CGO_CFLAGS_ALLOW="-O -D__BLST_PORTABLE__" +RUN VERSION=$(jq -r .version configs/environ.json) && \ + export CGO_LDFLAGS="-L/opt/rocksdb -ldl -lrocksdb -lstdc++ -lm -lz -lbz2 -lsnappy -llz4 -lzstd $(gcc -print-file-name=libjemalloc_pic.a)" && \ + go build -o /out/blockbook -ldflags="-s -w \ + -X github.com/trezor/blockbook/common.version=${VERSION} \ + -X github.com/trezor/blockbook/common.gitcommit=$(git rev-parse --short HEAD) \ + -X github.com/trezor/blockbook/common.buildtime=$(date --iso-8601=seconds)" + +# Coin overrides (daemon versions we need ahead of upstream), then every coin's +# blockchaincfg.json and backend server.conf rendered with the container's +# paths, so nothing has to be compiled or fetched from GitHub at run time. +COPY overrides.json /tmp/overrides.json +RUN for coin in $(jq -r 'keys[]' /tmp/overrides.json); do \ + jq -s '.[0] * .[1]' configs/coins/$coin.json <(jq --arg c $coin '.[$c]' /tmp/overrides.json) > /tmp/c.json && \ + mv /tmp/c.json configs/coins/$coin.json; \ + done && \ + jq '.backend_install_path="/root" | .backend_data_path="/root"' configs/environ.json > /tmp/e.json && \ + mv /tmp/e.json configs/environ.json && \ + go build -o /tmp/generate build/templates/generate.go && \ + for f in configs/coins/*.json; do \ + coin=$(basename $f .json); rm -rf build/pkg-defs; \ + if BB_BUILD_ENV=prod /tmp/generate $coin > /dev/null 2>&1; then \ + mkdir -p /out/pkg/$coin; \ + cp build/pkg-defs/blockbook/blockchaincfg.json /out/pkg/$coin/ 2>/dev/null || true; \ + cp build/pkg-defs/backend/server.conf /out/pkg/$coin/ 2>/dev/null || true; \ + fi; \ + done && \ + echo "coins rendered: $(ls /out/pkg | wc -l)" && \ + test -f /out/pkg/flux/blockchaincfg.json && test -f /out/pkg/zcash/server.conf && \ + grep -q 'cache_dir = "/root/zcash/backend/zebra"' /out/pkg/zcash/server.conf && \ + mkdir -p /out/configs && cp -r configs/coins /out/configs/ && cp configs/environ.json /out/configs/ && \ + cp -r static /out/static && \ + echo "blockbook $(jq -r .version configs/environ.json) $(git rev-parse --short HEAD)" > /out/VERSION + +FROM debian:12-slim +# Links the ghcr.io package to this repository. +LABEL org.opencontainers.image.source=https://github.com/RunOnFlux/blockbook-docker +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates curl wget jq bc supervisor cron procps pv libarchive-tools unzip xz-utils \ + python3 libsnappy1v5 libzstd1 liblz4-1 libbz2-1.0 zlib1g libzmq5 libgflags2.2 libstdc++6 && \ + rm -rf /var/lib/apt/lists/* + +COPY --from=build /out/blockbook /opt/blockbook/blockbook +COPY --from=build /out/configs /opt/blockbook/configs +# blockbook loads its explorer templates from ./static (blockbook.sh runs it from /opt/blockbook) +COPY --from=build /out/static /opt/blockbook/static +COPY --from=build /out/pkg /opt/blockbook/pkg +COPY --from=build /out/VERSION /opt/blockbook/VERSION +COPY --from=build /opt/rocksdb/ldb /opt/rocksdb/ldb +COPY --from=zebra /usr/local/bin/zebrad /usr/local/bin/zebrad +RUN /opt/blockbook/blockbook -help > /dev/null 2>&1; test $? -le 2 && zebrad --version + +ENV HOME=/opt \ + RPC_USER=user \ + RPC_PASS=pass \ + BOOTSTRAP=0 \ + DAEMON=1 \ + CONFIG=AUTO \ + DAEMON_CONFIG=AUTO \ + PEER_BOOTSTRAP=1 + +COPY build.sh daemon.sh blockbook.sh check-health.sh consensus.sh utils.sh corruption.sh heal.sh snapshot.sh prune.sh snapshot_server.py / +RUN chmod 755 /*.sh /snapshot_server.py && mkdir -p /var/log/supervisor COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf VOLUME /root -EXPOSE $BLOCKBOOK_PORT 1337 -HEALTHCHECK --start-period=10m --interval=4m --retries=5 --timeout=40s CMD ./check-health.sh +EXPOSE 1337 +HEALTHCHECK --start-period=10m --interval=4m --retries=5 --timeout=40s CMD /check-health.sh ENTRYPOINT ["/usr/bin/supervisord"] diff --git a/README.md b/README.md index 462c4d8..345b59d 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,40 @@ # Multicoin Blockbook Explorer +### v3: pinned image +Images are published as `ghcr.io/runonflux/blockbook-docker:` from `v*` git tags (CI builds and +runs `test/smoke.sh` first). Pin app specs to a tag, never `latest`. + +- Blockbook, RocksDB and every coin's configs are built into the image from the trezor/blockbook + commit pinned in the `Dockerfile`; nothing is compiled or fetched from GitHub at container start. + Daemon versions come from that commit's coin configs, with `overrides.json` on top + (fluxd 9.1.0, zebrad for Zcash, which is copied in from `zfnd/zebra`). +- When the image changes, an existing container re-renders its configs and downloads the new + daemon; chain data is kept. +- **Peer snapshots** (`snapshot.sh`, `snapshot_server.py`): a synced instance keeps a hard-link + snapshot of its chain data and serves it on container port 1337 to the other instances of the same + Flux app. A new or far-behind instance seeds from the best peer instead of syncing from block 0. + Needs port 1337 mapped in the app spec. `PEER_BOOTSTRAP=0` disables seeding, + `SNAPSHOT_PEERS="ip:port ..."` seeds from given peers. +- `heal.sh` runs `reconsiderblock` when the daemon has marked the network's chain invalid and + stopped on its last good block. +- `corruption.sh` only wipes a database its own process reports as corrupt or refuses to open + (another coin, other index settings); `log_clean` only empties named log files (it used to empty + LevelDB/RocksDB write-ahead logs). +- `PRUNE_BACKEND=1` (Bitcoin): the daemon runs without txindex and with manual pruning, and + `prune.sh` keeps it `PRUNE_KEEP_BLOCKS` (2000) behind blockbook, pausing it at + `PRUNE_MAX_BLOCKS_GB` (80) of unindexed blocks. Blockbook (`-prunedbackend`, `patches/0001`) + gets a confirmed transaction from the block its index places it in, and downloads a pruned + block again from a peer that keeps every block (`getblockfrompeer`), so transactions, address + and xpub histories, `tx-specific` and blocks come back complete. The first request for an old + transaction waits for that download (about a second; a history page downloads up to 8 blocks + at once, and at most 8 run at a time overall); after that it is in the tx cache, which is + emptied when it passes `TXCACHE_MAX_GB` (20). Without `-extendedindex` Bitcoin needs ~640 GB + instead of ~1.1 TB plus 886 GB of blocks (2026); as on every other coin without it, a spent + output gets `spentTxId` only with `?spending=true`. If no peer sends a block, the transaction + comes from the index: fee and vsize included, scripts and input txids not. +- Zebra releases stop at an end-of-support height about 16 weeks after release: bump + `ZEBRA_VERSION` in time. + ### USAGE ``` bash -i <(curl -s https://raw.githubusercontent.com/RunOnFlux/blockbook-docker/master/blockbook-docker_manager.sh) diff --git a/blockbook.sh b/blockbook.sh index 72f20f1..19e5fc1 100644 --- a/blockbook.sh +++ b/blockbook.sh @@ -16,29 +16,20 @@ function trim() { printf '%s' "$var" } -echo -e "| BLOCKBOOK LUNCHER v2.0 [$(date '+%Y-%m-%d %H:%M:%S')]" +echo -e "| BLOCKBOOK LAUNCHER v3 [$(date '+%Y-%m-%d %H:%M:%S')] $(cat /opt/blockbook/VERSION)" echo -e "---------------------------------------------------------------------------" if [[ "$DAEMON_CONFIG" != "AUTO" ]]; then - echo -e "| Blockbook Settings: COIN=$COIN, RPC_USER=$RPC_USER, RPC_PASS=$RPC_PASS, RPC_PORT=$RPC_PORT, BLOCKBOOK_PORT=$BLOCKBOOK_PORT, RPC_HOST=$RPC_HOST, RPC_URL_PROTOCOL=$RPC_URL_PROTOCOL" + echo -e "| Blockbook Settings: COIN=$COIN, RPC_USER=$RPC_USER, RPC_PORT=$RPC_PORT, BLOCKBOOK_PORT=$BLOCKBOOK_PORT, RPC_HOST=$RPC_HOST, RPC_URL_PROTOCOL=$RPC_URL_PROTOCOL" else echo -e "| Blockbook Settings: COIN=$COIN, BLOCKBOOK_PORT=$BLOCKBOOK_PORT, DAEMON_CONFIG=AUTO" fi -echo -e "| Awaiting for Blockbook build..." -while true; do - if [[ -f $CFG_FILE && -f $HOME/blockbook/blockbook ]]; then - sleep 20 - break - fi - sleep 20 +until [[ -f /run/bb/prepared && -f /run/bb/bootstrapped && -f $CFG_FILE ]]; do + sleep 10 done -if [[ "$BOOTSTRAP" == "1" && ! -f /root/BOOTSTRAP_LOCKED ]]; then - echo -e "| Awaiting for bootstraping..." - while true; do - if [[ -f /root/BOOTSTRAP_LOCKED ]]; then - sleep 20 - break - fi - sleep 180 +if [[ "$BOOTSTRAP" == "1" && "$DAEMON" == "1" ]]; then + echo -e "| Awaiting the daemon's bootstrap step..." + until [[ -f /run/bb/daemon_bootstrap_done ]]; do + sleep 20 done fi if [[ ! -f /root/CONFIG_CRETED ]]; then @@ -59,7 +50,8 @@ if [[ ! -d /root/blockbook-db ]]; then mkdir -p /root/blockbook-db fi -exec_string="$HOME/blockbook/blockbook -sync -blockchaincfg=$CFG_FILE -datadir=/root/blockbook-db -debug -workers=${WORKERS:-1} -dbcache=${DBCACHE:-500} -public=:${BLOCKBOOK_PORT} -logtostderr" +# -dbcache is in bytes: the old default of 500 gave RocksDB a 500 byte cache. +exec_string="$HOME/blockbook/blockbook -sync -blockchaincfg=$CFG_FILE -datadir=/root/blockbook-db -workers=${WORKERS:-4} -dbcache=${DBCACHE:-536870912} -public=:${BLOCKBOOK_PORT} -logtostderr" args_to_remove=( -datadir -debug -log -blockchaincfg -sync -logtostderr -public ) additional_params_from_blockbook=$(jq -r .blockbook.additional_params $HOME/blockbook/configs/coins/${COIN}.json) additional_params_from_docker="${BLOCKBOOK_PARAMS}" @@ -92,6 +84,19 @@ else fi clean_variable=$(trim "${docker_clean} ${final_clean}") +# A pruned backend has no txindex: blockbook gets a confirmed transaction from +# its block and downloads a pruned block again from a peer (patches/0001). What +# it fetched stays in the tx cache, emptied past TXCACHE_MAX_GB. The extended +# index (every input's previous txid and every spent output's spender, ~245 GB +# of Bitcoin's index in 2026) does not fit next to the rest of the index in an +# 820 GB app. +if [[ "$PRUNE_BACKEND" == "1" ]]; then + kept="" + for arg in ${clean_variable}; do + [[ "$arg" =~ ^--?(extendedindex|notxcache)(=|$) ]] || kept="${kept} ${arg}" + done + clean_variable=$(trim "${kept} -prunedbackend -txcachemaxgb=${TXCACHE_MAX_GB:-20}") +fi if [[ "$clean_variable" != "" ]]; then getArgs "${clean_variable}" for arg in "${argsArray[@]}"; do diff --git a/build.sh b/build.sh index 3de407f..0a00195 100644 --- a/build.sh +++ b/build.sh @@ -1,133 +1,62 @@ #!/usr/bin/env bash +# Lays out this coin's config files. Blockbook, RocksDB and the rendered +# configs of every coin are built into the image (see Dockerfile), so this +# takes seconds; there is nothing to compile at run time any more. +# +# When the image changes, the generated files are rendered again from the new +# image: a config left over from an older blockbook or daemon is what kept +# instances on stale daemon versions. Chain data is never touched here. CONFIG_FILE=${CONFIG_FILE:-$COIN} CONFIG_DIR=${CONFIG_DIR:-$COIN} -BLOCKBOOKGIT_URL=${BLOCKBOOKGIT_URL:-https://github.com/trezor/blockbook.git} -re="^(https|git)(:\/\/|@)([^\/:]+)[\/:]([^\/:]+)\/(.+)(.git)*$" -if [[ $BLOCKBOOKGIT_URL =~ $re ]]; then - GIT_USER=${BASH_REMATCH[4]} - REPO=$(cut -d "." -f 1 <<< ${BASH_REMATCH[5]}) -fi -VERSION=$(curl -ssL https://raw.githubusercontent.com/$GIT_USER/$REPO/$TAG/configs/environ.json | jq -r .version) -start_build=`date +%s` +PKG=/opt/blockbook/pkg/$COIN +IMAGE_VERSION="$(cat /opt/blockbook/VERSION) $(md5sum /opt/blockbook/configs/coins/$COIN.json 2>/dev/null | cut -c1-8)" -function rocksdb_install(){ - if [[ -d $HOME/rocksdb ]]; then - return - fi - echo -e "| Installing RocksDB [$ROCKSDB_VERSION]..." - echo -e "| PATH: $HOME/rocksdb" - cd $HOME && git clone -b $ROCKSDB_VERSION --depth 1 https://github.com/facebook/rocksdb.git > /dev/null 2>&1 - cd $HOME/rocksdb && CFLAGS=-fPIC CXXFLAGS='-fPIC -Wno-error=deprecated-copy -Wno-error=pessimizing-move -Wno-error=class-memaccess' PORTABLE=1 DISABLE_WARNING_AS_ERROR=1 make -j 4 release > /dev/null 2>&1 - if [[ -f $HOME/rocksdb/librocksdb.a ]]; then - echo -e "| RocksDB BUILD [OK]..." - else - echo -e "| RocksDB BUILD [FAILED]..." - rm -rf $HOME/rocksdb - fi -} +mkdir -p /run/bb +rm -f /run/bb/prepared +export -p > /run/bb/env.sh -function blockbook_install() { - if [[ -d $HOME/blockbook ]]; then - return - fi - echo -e "| Installing Blockbook [v$VERSION]..." - echo -e "| GITHUB URL: $BLOCKBOOKGIT_URL, BRANCH: $TAG" - echo -e "| PATH: $HOME/blockbook" - cd $HOME && git clone $BLOCKBOOKGIT_URL - cd $HOME/blockbook - git checkout "$TAG" > /dev/null 2>&1 - go mod download - BUILDTIME=$(date --iso-8601=seconds) - GITCOMMIT=$(git describe --always --dirty) - LDFLAGS="-X github.com/trezor/blockbook/common.version=${VERSION} -X github.com/trezor/blockbook/common.gitcommit=${GITCOMMIT} -X github.com/trezor/blockbook/common.buildtime=${BUILDTIME}" - go build -tags rocksdb_6_16 -ldflags="-s -w ${LDFLAGS}" -} +echo -e "| BLOCKBOOK LAUNCHER v3 [$(date '+%Y-%m-%d %H:%M:%S')]" +echo -e "| Image: $IMAGE_VERSION, coin: $COIN" +if [[ -z "$COIN" || ! -f /opt/blockbook/configs/coins/$COIN.json ]]; then + echo -e "| Unknown coin '$COIN', nothing to start" + exit 1 +fi -function setup() { - echo -e "| BLOCKBOOK LUNCHER v2.0 [$(date '+%Y-%m-%d %H:%M:%S')]" - echo -e "-----------------------------------------------------" - if [[ -d $HOME/blockbook ]]; then - echo -e "| Installed GOLANG [$GOLANG_VERSION]..." - echo -e "| PATH: $HOME/go" - echo -e "| Installed RocksDB [$ROCKSDB_VERSION]..." - echo -e "| PATH: $HOME/rocksdb" - echo -e "| Installed Blockbook [v$VERSION]..." - echo -e "| PATH: $HOME/blockbook" - else - echo -e "| Installed GOLANG [$GOLANG_VERSION]..." - echo -e "| PATH: $HOME/go" - x=1 - while [ $x -le 4 ] - do - rocksdb_install - if [[ ! -f $HOME/rocksdb/librocksdb.a ]]; then - x=$(( $x + 1 )) - supervisorctl stop daemon - stopDaemon=1 - continue - fi - if [[ "$stopDaemon" == "1" ]]; then - stopDaemon=0 - supervisorctl start daemon - fi - blockbook_install - x=$(( $x + 1 )) - if [[ -f $HOME/blockbook/blockbook ]]; then - echo -e "| Blockbook BUILD [OK]..." - break - else - echo -e "| Blockbook BUILD [FAILED]..." - rm -rf $HOME/blockbook - rm -rf $HOME/rocksdb - fi - echo -e "| Duration: $((($(date +%s)-$start_build)/60)) min. $((($(date +%s)-$start_build) % 60)) sec." - done - fi - - if [[ ! -f $HOME/blockbook/blockbook ]]; then - echo -e "-----------------------------------------------------" - exit - fi -} -##### Install Process -setup -########################## -if [[ ! -f /root/blockchaincfg.json ]]; then - if [[ ! -d /root/$CONFIG_DIR ]]; then - echo -e "| Creating config directory..." - mkdir -p /root/$CONFIG_DIR +PREVIOUS=$(cat /root/.image_version 2>/dev/null) +if [[ -f /root/blockchaincfg.json && "$PREVIOUS" != "$IMAGE_VERSION" ]]; then + echo -e "| Image changed from [${PREVIOUS:-v2 launcher}], rendering configs again..." + rm -f /root/blockchaincfg.json /root/CONFIG_CRETED /root/daemon_config.json /root/blockbook.json + if [[ "$DAEMON_CONFIG" == "AUTO" && -f /root/$CONFIG_DIR/$CONFIG_FILE.conf ]]; then + mv /root/$CONFIG_DIR/$CONFIG_FILE.conf /root/$CONFIG_DIR/$CONFIG_FILE.conf.old fi - cd $HOME/blockbook - echo -e "| Generating config files for $COIN" - go run build/templates/generate.go $COIN > /dev/null - if [[ -f $HOME/blockbook/build/pkg-defs/blockbook/blockchaincfg.json ]]; then - echo -e "| Moving blockchaincfg.json" - mv $HOME/blockbook/build/pkg-defs/blockbook/blockchaincfg.json /root - fi - if [[ "$DAEMON_CONFIG" == "AUTO" ]]; then - if [[ -f $HOME/blockbook/build/pkg-defs/backend/server.conf ]]; then - echo -e "| Moving $CONFIG_FILE.conf" - mv $HOME/blockbook/build/pkg-defs/backend/server.conf /root/$CONFIG_DIR/$CONFIG_FILE.conf - fi - fi - rm -rf $HOME/blockbook/build/pkg-defs - echo -e "-----------------------------------------------------" -else - echo -e "-----------------------------------------------------" fi -echo -e "| CRON JOB CHECKING..." -[ -f /var/spool/cron/crontabs/root ] && crontab_check=$(cat /var/spool/cron/crontabs/root| grep -o utils | wc -l) || crontab_check=0 -if [[ "$crontab_check" == "0" ]]; then - echo -e "| ADDED CRONE JOB FOR LOG CLEANER..." - (crontab -l -u root 2>/dev/null; echo "0 0 1-30/5 * * /bin/bash /utils.sh log_clean > /tmp/clean_output.log 2>&1") | crontab - -else - echo -e "| CRONE JOB FOR LOG CLEANER ALREADY EXIST..." + +if [[ ! -f /root/blockchaincfg.json ]]; then + echo -e "| Installing blockchaincfg.json" + cp $PKG/blockchaincfg.json /root/blockchaincfg.json fi -[ -f /var/spool/cron/crontabs/root ] && crontab_check=$(cat /var/spool/cron/crontabs/root| grep -o corruption | wc -l) || crontab_check=0 -if [[ "$crontab_check" == "0" ]]; then - echo -e "| ADDED CRONE JOB FOR DB CORRUPTION..." - (crontab -l -u root 2>/dev/null; echo "0 */2 * * * /bin/bash /corruption.sh > /tmp/corruption_output.log 2>&1") | crontab - -else - echo -e "| CRONE JOB FOR DB CORRUPTION ALREADY EXIST..." +mkdir -p /root/$CONFIG_DIR /root/blockbook-db +if [[ "$DAEMON_CONFIG" == "AUTO" && -f $PKG/server.conf && ! -f /root/$CONFIG_DIR/$CONFIG_FILE.conf ]]; then + echo -e "| Installing $CONFIG_FILE.conf" + cp $PKG/server.conf /root/$CONFIG_DIR/$CONFIG_FILE.conf + touch /root/$CONFIG_DIR/.conf_fresh fi -echo -e "-----------------------------------------------------" +echo "$IMAGE_VERSION" > /root/.image_version + +# One file for all jobs, rewritten on every start: appending to a crontab, as +# the previous launcher did, kept old entries forever. flock keeps a slow run +# from stacking up behind the next one. +cat > /etc/cron.d/blockbook <<'EOF' +SHELL=/bin/bash +0 0 */5 * * root . /run/bb/env.sh; /utils.sh log_clean >> /root/maintenance.log 2>&1 +15 */2 * * * root . /run/bb/env.sh; flock -n /run/bb/corruption.lock /corruption.sh >> /root/maintenance.log 2>&1 +*/30 * * * * root . /run/bb/env.sh; flock -n /run/bb/heal.lock /heal.sh >> /root/maintenance.log 2>&1 +*/20 * * * * root . /run/bb/env.sh; flock -n /run/bb/snapshot.lock /snapshot.sh create >> /root/maintenance.log 2>&1 +*/5 * * * * root . /run/bb/env.sh; flock -n /run/bb/prune.lock /prune.sh >> /root/maintenance.log 2>&1 +47 * * * * root . /run/bb/env.sh; flock -n /run/bb/snapshot.lock /snapshot.sh reseed >> /root/maintenance.log 2>&1 +EOF +chmod 644 /etc/cron.d/blockbook +crontab -r 2>/dev/null + +touch /run/bb/prepared +echo -e "| Configs ready" diff --git a/consensus.sh b/consensus.sh index 71f19e7..6637e28 100644 --- a/consensus.sh +++ b/consensus.sh @@ -56,26 +56,17 @@ if [[ -f /usr/local/bin/beacon-chain ]]; then bash -c "$(jq -r .cmd_consensus /root/consensus.json)" exit fi -sleep 60 -echo -e "---------------------------------------------------" -echo -e "| Checking consensus client requriment ${COIN}..." -if [[ "$BLOCKBOOKGIT_URL" == "" ]]; then - BLOCKBOOKGIT_URL="https://github.com/trezor/blockbook.git" -fi -echo -e "| GITHUB URL: $BLOCKBOOKGIT_URL" -re="^(https|git)(:\/\/|@)([^\/:]+)[\/:]([^\/:]+)\/(.+)(.git)*$" -if [[ $BLOCKBOOKGIT_URL =~ $re ]]; then - GIT_USER=${BASH_REMATCH[4]} - REPO=$(cut -d "." -f 1 <<< ${BASH_REMATCH[5]}) +CONSENSUS_CONFIG=/opt/blockbook/configs/coins/${COIN}_consensus.json +if [[ ! -f $CONSENSUS_CONFIG ]]; then + # Most coins have no consensus client; exiting 0 is the expected outcome. + exit 0 fi -RAW_CONSENSUS_URL="https://raw.githubusercontent.com/$GIT_USER/$REPO/$TAG/configs/coins/${COIN}_consensus.json" -CLIENT_CONFIG=$(curl -SsL $RAW_CONSENSUS_URL 2>/dev/null | jq . 2>/dev/null) -if [[ $(jq -r . 2>/dev/null <<< "$CLIENT_CONFIG") == "" || $(jq -r . 2>/dev/null <<< "$CLIENT_CONFIG") == "null" ]]; then - echo -e "| CONSENSUS CLIENT: Not required (EXIT)" - echo -e "---------------------------------------------------" - exit -fi -echo -e "| CONSENSUS CONFIG: $RAW_CONSENSUS_URL" +until [[ -f /run/bb/prepared && -f /run/bb/bootstrapped ]]; do + sleep 10 +done +echo -e "---------------------------------------------------" +echo -e "| Consensus client required for ${COIN}: $CONSENSUS_CONFIG" +CLIENT_CONFIG=$(jq . $CONSENSUS_CONFIG) create_consensus_config parse_template "$CLIENT_CONFIG" "cmd_consensus" "consensus" "consensus" mkdir -p /root/${COIN}_consensus/backend 2>/dev/null diff --git a/corruption.sh b/corruption.sh index 2a8d19e..21817a8 100644 --- a/corruption.sh +++ b/corruption.sh @@ -1,56 +1,49 @@ #!/usr/bin/env bash +# Wipes a database only when its own process reports it unusable. +# +# The previous version also wiped the whole backend on "invalid header +# received" and "InvalidChainFound", which every node logs whenever a peer is +# on another fork. That kept instances re-syncing from block 0 forever, and +# left blockbook's index ahead of a backend that had just been emptied. CONFIG_DIR=${CONFIG_DIR:-$COIN} -CFG_FILE=/root/blockchaincfg.json CF_LOGS=/root/corrupion_events.log -#echo -e "| Awaiting for Blockbook build..." -#echo -e "| CONFIG_DIR: $CONFIG_DIR" -while true; do - if [[ -f $CFG_FILE && -f $HOME/blockbook/blockbook ]]; then - sleep 240 - break - fi - sleep 30 -done +# The "does not match" errors: an index built for another coin or with other +# settings (a testnet3 index after the switch to testnet4, a full node's index +# under PRUNE_BACKEND or the other way round), which blockbook refuses to open. +BLOCKBOOK_PATTERNS='rocksDB: Corruption|SST file is ahead of WALs|Coins do not match|ExtendedIndex setting does not match|PrunedBackend setting does not match|does not match the required version|BlockGolombFilterP does not match|BlockFilterScripts does not match|BlockFilterUseZeroedKey does not match' +BACKEND_PATTERNS='Corrupted block database detected|Error opening block database|Fatal LevelDB error|Error initializing block database|database corrupted' -echo -e "------------------------------------------ [$(date '+%Y-%m-%d %H:%M:%S')][START]" -echo -e "| Checking blockbook logs...." -if [[ -f /root/blockbook.log ]]; then - WALs_CHECK=$(grep -ao "rocksDB: Corruption" /root/blockbook.log) - if [[ "$WALs_CHECK" != "" ]]; then - echo "[$(date "+%d/%m/%y %H:%M:%S %Z %z")] - BlockBook Corruption detected" >> $CF_LOGS - echo -e "| RocksDB Corruption detected!..." - echo -e "| Stopping blockbook service..." - supervisorctl stop blockbook > /dev/null 2>&1 - echo -e "| Removing old log file..." - rm -rf /root/blockbook.log - echo -e "| Clean the database..." - rm -rf /root/blockbook-db/* - #./opt/blockbook/blockbook -repair -datadir=/root/blockbook-db - echo -e "| Starting blockbook service..." - supervisorctl start blockbook > /dev/null 2>&1 - else - echo -e "| Corruption NOT detected, all looks fine ;)" - fi -else - echo -e "| File does not exists, operation aborted...." -fi -echo -e "----------------------------------------------------------------" -echo -e "| Checking backend logs...." -if [[ -f /root/$CONFIG_DIR/backend/debug.log ]]; then - corruption=$(egrep -ao "Corrupted|Corruption|ERROR: VerifyDB|printcrashinfo|ERROR: invalid header received|InvalidChainFound: invalid" /root/$CONFIG_DIR/backend/debug.log) - if [[ "$corruption" != "" ]]; then - echo "[$(date "+%d/%m/%y %H:%M:%S %Z %z")] - Backend Corruption detected" >> $CF_LOGS - echo -e "| Backend Corruption detected!..." - echo -e "| Stopping backend service..." +[[ -f /run/bb/prepared && -f /run/bb/bootstrapped ]] || exit 0 +echo -e "------------------------------------------ [$(date '+%Y-%m-%d %H:%M:%S')] corruption check" + +if [[ -f /root/blockbook.log ]] && tail -n 5000 /root/blockbook.log | grep -aqE "$BLOCKBOOK_PATTERNS"; then + echo "[$(date "+%d/%m/%y %H:%M:%S %Z %z")] - BlockBook Corruption detected" >> $CF_LOGS + echo -e "| RocksDB corruption, cleaning the blockbook database" + supervisorctl stop blockbook > /dev/null 2>&1 + rm -rf /root/blockbook-db/* + : > /root/blockbook.log + # A synced peer's index is far quicker than indexing from block 0. + /snapshot.sh restore-blockbook + # A pruned backend no longer has the old blocks, so an index no peer could + # provide can only be rebuilt together with the backend. + if [[ "$PRUNE_BACKEND" == "1" && "$DAEMON" == "1" && ! -f /root/blockbook-db/CURRENT ]]; then + echo -e "| No peer index and the backend is pruned, starting the backend over too" supervisorctl stop daemon > /dev/null 2>&1 - echo -e "| Removing backend directory contents..." - rm -rf /root/$CONFIG_DIR/backend/* - echo -e "| Starting backend service..." + rm -rf "/root/${CONFIG_DIR:?}"/backend/* /root/BOOTSTRAP_LOCKED + /snapshot.sh restore supervisorctl start daemon > /dev/null 2>&1 - else - echo -e "| Corruption NOT detected, all looks fine ;)" fi -else - echo -e "| File does not exists, operation aborted...." + supervisorctl start blockbook > /dev/null 2>&1 +fi + +DEBUG_LOG=/root/$CONFIG_DIR/backend/debug.log +if [[ "$DAEMON" == "1" && -f $DEBUG_LOG ]] && tail -n 5000 $DEBUG_LOG | grep -aqE "$BACKEND_PATTERNS"; then + echo "[$(date "+%d/%m/%y %H:%M:%S %Z %z")] - Backend Corruption detected" >> $CF_LOGS + echo -e "| Backend database corruption, starting over from a peer snapshot or block 0" + supervisorctl stop blockbook daemon > /dev/null 2>&1 + # The index cannot be kept: it would be ahead of the emptied backend. + rm -rf "/root/${CONFIG_DIR:?}"/backend/* /root/blockbook-db/* /root/BOOTSTRAP_LOCKED + /snapshot.sh restore + supervisorctl start daemon blockbook > /dev/null 2>&1 fi -echo -e "----------------------------------------------------------------[END]" +echo -e "| corruption check done" diff --git a/daemon.sh b/daemon.sh index db76ddd..5a5a8e6 100644 --- a/daemon.sh +++ b/daemon.sh @@ -6,17 +6,21 @@ CONFIG_DIR=${CONFIG_DIR:-$COIN} RPC_PORT_KEY=${RPC_PORT_KEY:-rpcport} RPC_USER_KEY=${RPC_USER_KEY:-rpcuser} RPC_PASSWORD_KEY=${RPC_PASSWORD_KEY:-rpcpassword} +COIN_CONFIG=/opt/blockbook/configs/coins/$COIN.json +# Removes only the settings that would fork the daemon away from supervisord. +# The previous version deleted every line *containing* "mainnet" or "daemon", +# which breaks TOML configs such as zebra's (initial_mainnet_peers = [...]). function config_clean(){ - REMOVED_LIST=( "mainnet" "daemon" ) - REMOVED_LENGTH=${#REMOVED_LIST[@]} - for (( p=0; p<${REMOVED_LENGTH}; p++ )); - do - sed -i "/$(grep -e ${REMOVED_LIST[$p]} /root/${CONFIG_DIR}/${CONFIG_FILE}.conf)/d" /root/${CONFIG_DIR}/${CONFIG_FILE}.conf > /dev/null 2>&1 - done + sed -i -E '/^[[:space:]]*(daemon|mainnet)[[:space:]]*=/d' /root/${CONFIG_DIR}/${CONFIG_FILE}.conf if [ "$REMOVE_ADDNODES" = "true" ]; then sed -i '/^addnode=/d' /root/${CONFIG_DIR}/${CONFIG_FILE}.conf fi + # Pruned backend (see prune.sh): manual pruning, which rules out txindex. + if [ "$PRUNE_BACKEND" = "1" ]; then + sed -i -E '/^[[:space:]]*(txindex|prune)[[:space:]]*=/d' /root/${CONFIG_DIR}/${CONFIG_FILE}.conf + sed -i '1i prune=1' /root/${CONFIG_DIR}/${CONFIG_FILE}.conf + fi } function config_create(){ @@ -30,14 +34,10 @@ if [[ "$DAEMON_CONFIG" != "AUTO" ]]; then EOF else echo -e "| Awaiting for daemon config generate by blockbook..." - while true; do - if [[ -f /root/$CONFIG_DIR/$CONFIG_FILE.conf ]]; then - config_clean - sleep 5 - break - fi - sleep 180 + while [[ ! -f /root/$CONFIG_DIR/$CONFIG_FILE.conf ]]; do + sleep 10 done + config_clean fi } @@ -45,10 +45,7 @@ function parse_template(){ echo -e "| Parsing exec command template..." TEMPLATE=$(jq -r .backend.exec_command_template <<< "$1") BIN_PATH=($TEMPLATE) - DATA_PATH=${BIN_PATH[1]} - CONF_PATH=${BIN_PATH[2]} if [[ ! $(grep "/bin/sh -c" <<< $TEMPLATE) ]]; then - #TEMPLATE="$BIN_PATH $DATA_PATH $CONF_PATH" TEMPLATE=$(sed "s/${BIN_PATH//\//\\/}/$BINARY_NAME/g" <<< $TEMPLATE) else TEMPLATE=$(sed "s|/bin/sh -c '{{.Env.BackendInstallPath}}/{{.Coin.Alias}}/|""|" <<< $TEMPLATE) @@ -66,7 +63,8 @@ function parse_template(){ done TEMPLATE=$(sed "s/'/""/g" <<< $TEMPLATE) TEMPLATE=$(sed "s/\"/\'/g" <<< $TEMPLATE) - TEMPLATE=$(sed "s/run/root/g" <<< $TEMPLATE) + # -pid points at /run//, which does not exist in the container. + TEMPLATE=$(sed -E "s# -pid=[^ ]+##" <<< $TEMPLATE) if [[ ! -f /root/$3.json ]]; then echo "{}" > /root/$3.json fi @@ -75,13 +73,10 @@ function parse_template(){ } function extract_daemon() { - if [[ ! -d /tmp/backend ]]; then - echo -e "| Creating directory..." - mkdir -p /tmp/backend - fi + mkdir -p /tmp/backend cd /tmp echo -e "| Searching params script..." - PARAMS_CHECK=$(bsdtar -ztvf ${DAEMON_URL##*/} | grep '\-params' | head -n1) + PARAMS_CHECK=$(bsdtar -tvf ${DAEMON_URL##*/} | grep '\-params' | head -n1) if [[ "$PARAMS_CHECK" != "" ]]; then STRIP=$(bsdtar -tvf ${DAEMON_URL##*/} | egrep '\-params$|\-params.sh$' | head -n1 | awk '{ printf "%s\n", $9 }' | awk -F\/ '{print NF-1}') bsdtar -C backend --strip $STRIP -xf ${DAEMON_URL##*/} > /dev/null 2>&1 @@ -96,13 +91,12 @@ function extract_daemon() { fi rm -rf /tmp/backend/* fi - echo -e "| ${CYAN}Unpacking daemon bin archive file...${NC}" + echo -e "| Unpacking daemon bin archive file..." strip_lvl=$(bsdtar -tvf ${DAEMON_URL##*/} | grep ${BINARY_NAME}$ | awk '{ printf "%s\n", $9 }' | awk -F\/ '{print NF-1}') bsdtar --exclude="share" --exclude="lib" --exclude="include" -C backend --strip $strip_lvl -xf ${DAEMON_URL##*/} > /dev/null 2>&1 || return 1 return 0 } - function cli_search(){ if [[ "$CLI_NAME" == "" ]]; then echo -e "| Searching for CLI binary..." @@ -114,11 +108,10 @@ function cli_search(){ fi } - function tar_file_unpack() { - echo -e "| ${CYAN}Unpacking bootstrap archive file...${NC}" - pv $1 | tar -zx -C $2 + echo -e "| Unpacking bootstrap archive file..." + pv -f -i 60 $1 2>&1 | tar -zx -C $2 } function cdn_speedtest() { @@ -133,7 +126,7 @@ function cdn_speedtest() { dTime="$2" fi if [[ -z $3 || "$3" == "0" ]]; then - rand_by_domain=("5" "6" "7" "8" "9" "10" "11" "12") + rand_by_domain=("1" "2" "3" "4" "5" "6" "7") else msg="$3" shift @@ -144,23 +137,16 @@ function cdn_speedtest() { size_list=() i=0 len=${#rand_by_domain[@]} - echo -e "| ${CYAN}Running quick download speed test for ${BOOTSTRAP_FILE}, Servers: ${GREEN}$len${NC}" - start_test=`date +%s` - while [ $i -lt $len ]; - do + echo -e "| Running quick download speed test for ${BOOTSTRAP_FILE}, Servers: $len" + while [ $i -lt $len ]; do if [[ "$custom_url" == "1" ]]; then - testing=$(curl -m ${dTime} ${rand_by_domain[$i]}${BOOTSTRAP_FILE} --output testspeed -fail --silent --show-error 2>&1) + testing=$(curl -L -m ${dTime} ${rand_by_domain[$i]}${BOOTSTRAP_FILE} --output testspeed -fail --silent --show-error 2>&1) else - testing=$(curl -m ${dTime} http://cdn-${rand_by_domain[$i]}.runonflux.io/apps/fluxshare/getfile/${BOOTSTRAP_FILE} --output testspeed -fail --silent --show-error 2>&1) + testing=$(curl -L -m ${dTime} https://cdn-${rand_by_domain[$i]}.runonflux.io/apps/fluxshare/getfile/${BOOTSTRAP_FILE} --output testspeed -fail --silent --show-error 2>&1) fi testing_size=$(grep -Po "\d+" <<< "$testing" | paste - - - - | awk '{printf "%d\n",$3}') - mb=$(bc <<<"scale=2; $testing_size / 1048576 / $dTime" | awk '{printf "%2.2f\n", $1}') - if [[ "$custom_url" == "1" ]]; then - domain=$(sed -e 's|^[^/]*//||' -e 's|/.*$||' <<< ${rand_by_domain[$i]}) - echo -e "| - ${GREEN}URL - ${YELLOW}${domain}${GREEN} - Bits Downloaded: ${YELLOW}$testing_size${NC} ${GREEN}Average speed: ${YELLOW}$mb ${GREEN}MB/s${NC}" - else - echo -e "| - ${GREEN}cdn-${YELLOW}${rand_by_domain[$i]}${GREEN} - Bits Downloaded: ${YELLOW}$testing_size${NC} ${GREEN}Average speed: ${YELLOW}$mb ${GREEN}MB/s${NC}" - fi + testing_size=${testing_size:-0} + echo -e "| - server ${rand_by_domain[$i]} - bytes downloaded: $testing_size" size_list+=($testing_size) if [[ "$testing_size" == "0" ]]; then failed_counter=$(($failed_counter+1)) @@ -168,7 +154,6 @@ function cdn_speedtest() { i=$(($i+1)) done rServerList=$((${#size_list[@]}-$failed_counter)) - echo -e "| ${CYAN}Valid servers: ${GREEN}${rServerList} ${CYAN}- Duration: ${GREEN}$((($(date +%s)-$start_test)/60)) min. $((($(date +%s)-$start_test) % 60)) sec.${NC}" rm -rf testspeed > /dev/null 2>&1 if [[ "$rServerList" == "0" ]]; then server_offline="1" @@ -183,48 +168,52 @@ function cdn_speedtest() { if [[ "$custom_url" == "1" ]]; then BOOTSTRAP_URL="$server_index" else - BOOTSTRAP_URL="http://cdn-${server_index}.runonflux.io/apps/fluxshare/getfile/" + BOOTSTRAP_URL="https://cdn-${server_index}.runonflux.io/apps/fluxshare/getfile/" fi DOWNLOAD_URL="${BOOTSTRAP_URL}${BOOTSTRAP_FILE}" - mb=$(bc <<<"scale=2; $arr_max / 1048576 / $dTime" | awk '{printf "%2.2f\n", $1}') - if [[ "$custom_url" == "1" ]]; then - domain=$(sed -e 's|^[^/]*//||' -e 's|/.*$||' <<< ${server_index}) - echo -e "| ${CYAN}Best server is: ${YELLOW}${domain} ${GREEN}Average speed: ${YELLOW}$mb ${GREEN}MB/s${NC}" - else - echo -e "| ${CYAN}Best server is: ${GREEN}cdn-${YELLOW}${rand_by_domain[${max_indexes[0]}]} ${GREEN}Average speed: ${YELLOW}$mb ${GREEN}MB/s${NC}" - fi + echo -e "| Best server: $DOWNLOAD_URL" } stop_script() { echo -e "| Stopping daemon (EXIT)..." - if [[ "$CLI_NAME" != "" ]]; then - timeout 10 ${CLI_NAME} -rpcuser=${RPC_USER} -rpcpassword=${RPC_PASS} stop > /dev/null 2>&1 - timeout 10 ${CLI_NAME} -conf /root/$CONFIG_DIR/$CONFIG_FILE stop > /dev/null 2>&1 - fi if [[ "$BINARY_NAME" != "" ]]; then - kill -9 $(ps -ef | grep $BINARY_NAME | tr -s ' ' | cut -d ' ' -f2 | head -n1) + pkill -TERM -x "$BINARY_NAME" + for i in $(seq 1 280); do pgrep -x "$BINARY_NAME" > /dev/null || break; sleep 1; done fi exit 0 } trap stop_script SIGINT SIGTERM -if [[ "$DAEMON" == "1" ]]; then -echo -e "| DAEMON LUNCHER v1.0 [$(date '+%Y-%m-%d %H:%M:%S')]" +if [[ "$DAEMON" != "1" ]]; then + echo -e "| DAEMON LAUNCHER [DISABLED]..." + # Stay up so supervisord does not restart this every few seconds. + exec sleep infinity +fi + +echo -e "| DAEMON LAUNCHER v3 [$(date '+%Y-%m-%d %H:%M:%S')]" echo -e "---------------------------------------------------------------------------" +until [[ -f /run/bb/prepared && -f /run/bb/bootstrapped ]]; do + sleep 10 +done + +BLOCKBOOKCONFIG=$(jq . $COIN_CONFIG) if [[ -f /root/daemon_config.json ]]; then echo -e "| Loading daemon_config.json..." if [[ "$CLI_NAME" == "" ]]; then - CLI_NAME=$(jq -r .cli_name /root/daemon_config.json) + CLI_NAME=$(jq -r '.cli_name // empty' /root/daemon_config.json) fi if [[ "$BINARY_NAME" == "" ]]; then - BINARY_NAME=$(jq -r .binary_name /root/daemon_config.json) - fi - if [[ $(jq -r .daemon_url /root/daemon_config.jso) != "null" && $(jq -r .daemon_url /root/daemon_config.jso) != "" ]]; then - DAEMON_URL=$(jq -r .daemon_url /root/daemon_config.json) + BINARY_NAME=$(jq -r '.binary_name // empty' /root/daemon_config.json) fi fi +# The daemon version is the one pinned in the image's coin config unless the +# app spec sets DAEMON_URL. A URL saved by an older container is ignored on +# purpose: that is how instances stayed on old daemon versions. +if [[ "$DAEMON_URL" == "" ]]; then + DAEMON_URL=$(jq -r '.backend.binary_url // empty' <<< "$BLOCKBOOKCONFIG") +fi if [[ "$CONFIG" == "1" ]]; then if [[ ! -f /root/$CONFIG_DIR/$CONFIG_FILE.conf ]]; then @@ -237,71 +226,52 @@ if [[ "$CONFIG" == "1" ]]; then fi if [[ "$BOOTSTRAP" == "1" && ! -f /root/BOOTSTRAP_LOCKED ]]; then + if [[ "$CONFIG" == "AUTO" ]]; then BOOTSTRAP_DIR=/root/$CONFIG_DIR/backend; else BOOTSTRAP_DIR=/root/$CONFIG_DIR; fi + # Never unpack over a chain that is already there. + if [[ -d $BOOTSTRAP_DIR/blocks && $(du -sm $BOOTSTRAP_DIR/blocks | cut -f1) -gt 1024 ]]; then + echo -e "| Bootstrap skipped, $BOOTSTRAP_DIR already holds a chain" + echo -e "Bootstrap [LOCKED]" > /root/BOOTSTRAP_LOCKED + else B_FILE="${B_FILE:-0}" B_TIMEOUT="${B_TIMEOUT:-6}" B_SERVERS_LIST="${B_SERVERS_LIST:-0}" - cdn_speedtest "$B_FILE" "$B_TIMEOUT" "${B_SERVERS_LIST[@]}" if [[ "$server_offline" == "1" ]]; then - echo -e "| ${CYAN}All Bootstrap server offline, operation aborted.. ${NC}" && sleep 1 + echo -e "| All bootstrap servers offline, starting without bootstrap" else cd /root start_download=`date +%s` - echo -e "| ${YELLOW}Downloading File: ${GREEN}$DOWNLOAD_URL ${NC}" - wget --tries 5 -O $BOOTSTRAP_FILE $DOWNLOAD_URL -q --no-verbose --show-progress --progress=dot:giga > /dev/null 2>&1 - echo -e "| Download duration: $((($(date +%s)-$start_download)/60)) min. $((($(date +%s)-$start_download) % 60)) sec." - start_unzip=`date +%s` - if [[ "$CONFIG" == "AUTO" ]]; then - mkdir -p /root/$CONFIG_DIR/backend > /dev/null 2>&1 - tar_file_unpack "/root/$BOOTSTRAP_FILE" "/root/$CONFIG_DIR/backend" + echo -e "| Downloading file: $DOWNLOAD_URL" + if wget --tries 5 -O $BOOTSTRAP_FILE $DOWNLOAD_URL -q; then + mkdir -p $BOOTSTRAP_DIR + tar_file_unpack "/root/$BOOTSTRAP_FILE" "$BOOTSTRAP_DIR" && echo -e "Bootstrap [LOCKED]" > /root/BOOTSTRAP_LOCKED + echo -e "| Bootstrapping took $((($(date +%s)-$start_download)/60)) min." else - mkdir -p /root/$CONFIG_DIR > /dev/null 2>&1 - tar_file_unpack "/root/$BOOTSTRAP_FILE" "/root/$CONFIG_DIR" + echo -e "| Bootstrap download failed, starting without bootstrap" fi - echo -e "| Unzip duration: $((($(date +%s)-$start_unzip)/60)) min. $((($(date +%s)-$start_unzip) % 60)) sec." - echo -e "| Bootstraping duration: $((($(date +%s)-$start_download)/60)) min. $((($(date +%s)-$start_download) % 60)) sec." - echo -e "Bootstrap [LOCKED]" > BOOTSTRAP_LOCKED rm -rf /root/$BOOTSTRAP_FILE - sleep 2 fi fi +fi +touch /run/bb/daemon_bootstrap_done if [[ "$BINARY_NAME" != "" ]]; then echo -e "| Stopping daemon (START)..." - if [[ "$CLI_NAME" != "" ]]; then - timeout 10 ${CLI_NAME} -rpcuser=${RPC_USER} -rpcpassword=${RPC_PASS} stop > /dev/null 2>&1 - timeout 10 ${CLI_NAME} -conf=/root/$CONFIG_DIR/$CONFIG_FILE stop > /dev/null 2>&1 - fi - kill -9 $(ps -ef | grep $BINARY_NAME | tr -s ' ' | cut -d ' ' -f2 | head -n1) + pkill -9 -x "$BINARY_NAME" fi -if [[ ! -f /usr/local/bin/$BINARY_NAME ]]; then - echo -e "| Downloading daemon ($COIN)..." - cd /tmp - mkdir backend - echo -e "| Fetching Blockbook config for $COIN..." - if [[ "$BLOCKBOOKGIT_URL" == "" ]]; then - BLOCKBOOKGIT_URL="https://github.com/trezor/blockbook.git" - fi - echo -e "| GITHUB URL: $BLOCKBOOKGIT_URL" - re="^(https|git)(:\/\/|@)([^\/:]+)[\/:]([^\/:]+)\/(.+)(.git)*$" - if [[ $BLOCKBOOKGIT_URL =~ $re ]]; then - GIT_USER=${BASH_REMATCH[4]} - REPO=$(cut -d "." -f 1 <<< ${BASH_REMATCH[5]}) - fi - RAW_CONF_URL="https://raw.githubusercontent.com/$GIT_USER/$REPO/$TAG/configs/coins/$COIN.json" - echo -e "| CONFIG URL: $RAW_CONF_URL" - BLOCKBOOKCONFIG=$(curl -SsL $RAW_CONF_URL 2>/dev/null | jq .) - if [[ ! -f /root/blockbook.json ]]; then - echo -e "| Creating blockbook.json file..." - cat << EOF > /root/blockbook.json +if [[ ! -f /root/blockbook.json ]]; then + echo -e "| Creating blockbook.json file..." + cat << EOF > /root/blockbook.json { "coin": { "alias": "$COIN" }, "env": { "backenddatapath": "/root", - "backendinstallpath": "/root" + "backendinstallpath": "/root", + "rpcbindhost": "127.0.0.1", + "rpcallowip": "127.0.0.1" }, "ports": { "backendauthrpc": "${BACKEND_AUTHRPC:-$(jq -r .ports.backend_authrpc <<< $BLOCKBOOKCONFIG)}", @@ -315,93 +285,78 @@ if [[ ! -f /usr/local/bin/$BINARY_NAME ]]; then } } EOF - fi - if [[ "$DAEMON_URL" == "" ]]; then - DAEMON_URL=$(jq -r .backend.binary_url <<< "$BLOCKBOOKCONFIG") - fi - if [[ "$BINARY_NAME" == "" ]]; then - BINARY_NAME=$(jq -r .backend.exec_command_template 2>/dev/null <<< "$BLOCKBOOKCONFIG") - BINARY_NAME=($(sed "s|/bin/sh -c '{{.Env.BackendInstallPath}}/{{.Coin.Alias}}/|""|" <<< $BINARY_NAME)) - BINARY_NAME=${BINARY_NAME##*/} - if [[ ! -f /root/daemon_config.json ]]; then - echo "{}" > /root/daemon_config.json - echo "$(jq -r --arg key "binary_name" --arg value "$BINARY_NAME" '.[$key]=$value' /root/daemon_config.json)" > /root/daemon_config.json - echo "$(jq -r --arg key "daemon_url" --arg value "$DAEMON_URL" '.[$key]=$value' /root/daemon_config.json)" > /root/daemon_config.json - fi - fi - if [[ $(jq -r .cmd /root/daemon_config.json 2>/dev/null) == "null" && "$CONFIG" == "AUTO" ]]; then - ################ PARSE DAEMON EXEC TEMPLATE ###################### - parse_template "$BLOCKBOOKCONFIG" "cmd" "daemon_config" "blockbook" - ################################################################## - fi +fi +if [[ "$BINARY_NAME" == "" ]]; then + BINARY_NAME=$(jq -r .backend.exec_command_template 2>/dev/null <<< "$BLOCKBOOKCONFIG") + BINARY_NAME=($(sed "s|/bin/sh -c '{{.Env.BackendInstallPath}}/{{.Coin.Alias}}/|""|" <<< $BINARY_NAME)) + BINARY_NAME=${BINARY_NAME##*/} +fi +if [[ ! -f /root/daemon_config.json ]]; then + echo "{}" > /root/daemon_config.json +fi +echo "$(jq -r --arg b "$BINARY_NAME" --arg u "$DAEMON_URL" '.binary_name=$b | .daemon_url=$u' /root/daemon_config.json)" > /root/daemon_config.json +if [[ $(jq -r .cmd /root/daemon_config.json 2>/dev/null) == "null" && "$CONFIG" == "AUTO" ]]; then + parse_template "$BLOCKBOOKCONFIG" "cmd" "daemon_config" "blockbook" +fi + +if [[ ! -f /usr/local/bin/$BINARY_NAME ]]; then + if [[ "$DAEMON_URL" == "" || "$DAEMON_URL" == "null" ]]; then + echo -e "| No download URL for $COIN daemon ($BINARY_NAME) and it is not in the image, cannot start" + exec sleep infinity + fi + echo -e "| Downloading daemon ($COIN): $DAEMON_URL" + mkdir -p /tmp/backend && cd /tmp + wget -q -c -t 5 $DAEMON_URL + extract_daemon + echo -e "| Installing daemon ($COIN)..." + install -m 0755 -o root -g root -t /usr/local/bin backend/* + rm -rf /tmp/* if [[ ! -f /usr/local/bin/$BINARY_NAME ]]; then - echo -e "| BINARY URL: $DAEMON_URL" - wget -q --show-progress -c -t 5 $DAEMON_URL - extract_daemon - echo -e "| Installing daemon ($COIN)..." - install -m 0755 -o root -g root -t /usr/local/bin backend/* - rm -rf /tmp/* - if [[ "$CLI_NAME" == "" ]]; then - if [[ ! -f /root/daemon_config.json ]]; then - echo "{}" > /root/daemon_config.json - fi - cli_search - fi + echo -e "| $BINARY_NAME not found in $DAEMON_URL" + sleep 300 + exit 1 fi - fi +cli_search cd / sleep 5 -#if [[ "$FETCH_FILE" != "" ]]; then -# if [[ ! -d /root/.zcash-params ]]; then -# echo -e "| Installing fetch-params..." -# bash -c "$FETCH_FILE" > /dev/null 2>&1 && sleep 2 -# fi -#fi - if [[ "$CONFIG" == "0" || "$CONFIG" == "" ]]; then echo -e "| Starting $COIN daemon (Config: DISABLED)..." - ${BINARY_NAME} ${CLIFLAGS} + exec ${BINARY_NAME} ${CLIFLAGS} fi if [[ "$CONFIG" == "1" ]]; then echo -e "| Starting $COIN daemon (Config: ENABLED)..." - ${BINARY_NAME} -datadir="/root/${CONFIG_DIR}" -conf="/root/${CONFIG_DIR}/${CONFIG_FILE}.conf" + exec ${BINARY_NAME} -datadir="/root/${CONFIG_DIR}" -conf="/root/${CONFIG_DIR}/${CONFIG_FILE}.conf" fi if [[ "$CONFIG" == "AUTO" ]]; then - CLEAN_CHECK=$(grep 'daemon=' /root/${CONFIG_DIR}/${CONFIG_FILE}.conf) - if [[ ! -f /root/$CONFIG_DIR/$CONFIG_FILE.conf || "$CLEAN_CHECK" != "" ]]; then - mkdir -p /root/$CONFIG_DIR > /dev/null 2>&1 - config_create - if [[ "$EXTRACONFIG" != "" ]]; then - echo -e "$EXTRACONFIG" >> /root/$CONFIG_DIR/$CONFIG_FILE.conf - fi - fi + if [[ ! -f /root/$CONFIG_DIR/$CONFIG_FILE.conf || -f /root/$CONFIG_DIR/.conf_fresh ]]; then + mkdir -p /root/$CONFIG_DIR > /dev/null 2>&1 + config_create + if [[ "$EXTRACONFIG" != "" ]]; then + echo -e "$EXTRACONFIG" >> /root/$CONFIG_DIR/$CONFIG_FILE.conf + fi + rm -f /root/$CONFIG_DIR/.conf_fresh + fi echo -e "| Starting $COIN daemon (Config: AUTO)..." - if [[ ! -d /root/$CONFIG_DIR/backend ]]; then - mkdir -p /root/$CONFIG_DIR/backend > /dev/null 2>&1 + mkdir -p /root/$CONFIG_DIR/backend > /dev/null 2>&1 + init_url=$(jq -r .geth.init_url /root/blockbook.json) + if [[ "$init_url" != "" && "$init_url" != "null" ]]; then + if [[ ! -f /root/geth_init.json ]]; then + echo -e "| Downloading init file, URL: $init_url" + wget "$init_url" -O /root/geth_init.json > /dev/null 2>&1 + echo -e "| Tiggering geth init..." + geth --datadir /root/$COIN/backend init /root/geth_init.json + static_nodes_url=$(jq -r .geth.static_nodes_url /root/blockbook.json) + if [[ "$static_nodes_url" != "" && "$static_nodes_url" != "null" ]]; then + echo -e "| Downloading static node file, URL: $static_nodes_url" + wget "$static_nodes_url" -O /root/$COIN/backend/geth/static-nodes.json + fi + fi fi - - init_url=$(jq -r .geth.init_url /root/blockbook.json) - if [[ "$init_url" != "" && "$init_url" != "null" ]]; then - if [[ ! -f /root/geth_init.json ]]; then - echo -e "| Downloading init file, URL: $init_url" - wget "$init_url" -O /root/geth_init.json > /dev/null 2>&1 - echo -e "| Tiggering geth init..." - geth --datadir /root/$COIN/backend init /root/geth_init.json - static_nodes_url=$(jq -r .geth.static_nodes_url /root/blockbook.json) - if [[ "$static_nodes_url" != "" && "$static_nodes_url" != "null" ]]; then - echo -e "| Downloading static node file, URL: $static_nodes_url" - wget "$static_nodes_url" -O /root/$COIN/backend/geth/static-nodes.json - fi - fi - fi - bash -c "$(jq -r .cmd /root/daemon_config.json)" -fi -echo -e "---------------------------------------------------------------------------" -else - echo -e "| DAEMON LUNCHER [DISABLED]..." - echo -e "---------------------------------------------------------------------------" - exit + # Run in the background and wait, so the TERM trap above can stop the + # daemon cleanly instead of supervisord killing the whole group. + bash -c "$(jq -r .cmd /root/daemon_config.json)" & + wait $! fi diff --git a/heal.sh b/heal.sh new file mode 100755 index 0000000..3b81ed0 --- /dev/null +++ b/heal.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Frees a daemon that has marked the real chain invalid. +# +# A node that ran an older release across a consensus change (or hit a bug) +# flags the next block BLOCK_FAILED_VALID and stays on its last good block for +# good: the flag is persisted, so upgrading the binary does not clear it. Seen +# on blockbookflux: seven instances stuck at 2263328 for months while their +# getchaintips listed the network's chain as "invalid". +# +# reconsiderblock on that tip clears the flag on it and its ancestors and the +# node revalidates with the current binary. If the block really is invalid it +# is simply marked again, so trying once a day is harmless. +CONFIG_FILE=${CONFIG_FILE:-$COIN} +CONFIG_DIR=${CONFIG_DIR:-$COIN} +STATE=/root/heal_state.json +LOG=/root/heal_events.log +MIN_LEAD=${HEAL_MIN_LEAD:-12} + +[[ "$DAEMON" == "1" && -f /run/bb/bootstrapped ]] || exit 0 +CLI_NAME=${CLI_NAME:-$(jq -r '.cli_name // empty' /root/daemon_config.json 2>/dev/null)} +[[ -n "$CLI_NAME" ]] && command -v "$CLI_NAME" > /dev/null || exit 0 + +# Credentials from blockchaincfg.json: several backend configs only carry a +# hashed rpcauth line, which a CLI cannot log in with. +function cli() { + local user pass + user=$(jq -r '.rpc_user // empty' /root/blockchaincfg.json) + pass=$(jq -r '.rpc_pass // empty' /root/blockchaincfg.json) + if [[ -f /root/$CONFIG_DIR/$CONFIG_FILE.conf ]]; then + timeout 120 "$CLI_NAME" -conf="/root/$CONFIG_DIR/$CONFIG_FILE.conf" -rpcuser="$user" -rpcpassword="$pass" "$@" + else + timeout 120 "$CLI_NAME" -rpcuser="${user:-$RPC_USER}" -rpcpassword="${pass:-$RPC_PASS}" "$@" + fi +} + +TIPS=$(cli getchaintips 2>/dev/null) || exit 0 +ACTIVE=$(jq -r '[.[] | select(.status=="active")][0].height // 0' <<< "$TIPS") +CANDIDATE=$(jq -r --argjson a "$ACTIVE" --argjson lead "$MIN_LEAD" \ + '[.[] | select(.status=="invalid" and .height > ($a + $lead))] | max_by(.height) | .hash // empty' <<< "$TIPS") +[[ -n "$CANDIDATE" ]] || exit 0 + +[[ -f $STATE ]] || echo '{}' > $STATE +LAST=$(jq -r --arg h "$CANDIDATE" '.[$h] // 0' $STATE) +NOW=$(date +%s) +if (( NOW - LAST < 86400 )); then + exit 0 +fi +echo "[$(date '+%Y-%m-%d %H:%M:%S')] active tip at $ACTIVE, invalid tip $CANDIDATE is ahead: reconsiderblock" >> $LOG +OUT=$(cli reconsiderblock "$CANDIDATE" 2>&1) +echo "[$(date '+%Y-%m-%d %H:%M:%S')] reconsiderblock -> ${OUT:-ok}, height now $(cli getblockcount 2>/dev/null)" >> $LOG +echo "$(jq --arg h "$CANDIDATE" --argjson t "$NOW" '.[$h]=$t' $STATE)" > $STATE diff --git a/overrides.json b/overrides.json new file mode 100644 index 0000000..e8c7e29 --- /dev/null +++ b/overrides.json @@ -0,0 +1,45 @@ +{ + "flux": { + "backend": { + "version": "9.1.0", + "binary_url": "https://github.com/RunOnFlux/fluxd/releases/download/v9.1.0/Flux-amd64-v9.1.0.tar.gz" + } + }, + "zcash": { + "backend": { + "version": "6.4.2" + } + }, + "bcash": { + "backend": { + "version": "29.2.0", + "binary_url": "https://github.com/bitcoin-cash-node/bitcoin-cash-node/releases/download/v29.2.0/bitcoin-cash-node-29.2.0-x86_64-linux-gnu.tar.gz" + } + }, + "digibyte": { + "backend": { + "version": "8.26.2", + "binary_url": "https://github.com/DigiByte-Core/digibyte/releases/download/v8.26.2/digibyte-8.26.2-x86_64-linux-gnu.tar.gz", + "additional_params": { + "addnode": ["64.182.71.16:12024", "97.248.2.109:12024", "5.9.193.22:12024", "65.108.72.71:12024"], + "seednode": "seed.diginode.tools" + } + } + }, + "bgold": { + "backend": { + "additional_params": { + "addnode": ["162.19.139.182:8338", "162.19.139.181:8338", "92.218.61.167:8338", "13.115.32.229:8338"], + "seednode": "dnsseed.btgofficial.org" + } + } + }, + "viacoin": { + "backend": { + "additional_params": { + "addnode": ["204.168.233.210:5223"], + "seednode": "seed.viacoin.net" + } + } + } +} diff --git a/patches/0001-pruned-backend.patch b/patches/0001-pruned-backend.patch new file mode 100644 index 0000000..a969d52 --- /dev/null +++ b/patches/0001-pruned-backend.patch @@ -0,0 +1,963 @@ +diff --git a/api/worker.go b/api/worker.go +index f52ef3f3..2242e602 100644 +--- a/api/worker.go ++++ b/api/worker.go +@@ -288,6 +288,9 @@ func (w *Worker) GetRawTransaction(txid string) (string, error) { + func (w *Worker) getTransaction(txid string, spendingTxs bool, specificJSON bool, addresses map[string]struct{}) (*Tx, error) { + bchainTx, height, err := w.txCache.GetTransaction(txid) + if err != nil { ++ if tx := w.txFromIndex(txid, addresses); tx != nil { ++ return tx, nil ++ } + if err == bchain.ErrTxNotFound { + return nil, NewAPIError(fmt.Sprintf("Transaction '%v' not found", txid), true) + } +@@ -296,6 +299,29 @@ func (w *Worker) getTransaction(txid string, spendingTxs bool, specificJSON bool + return w.GetTransactionFromBchainTx(bchainTx, height, spendingTxs, specificJSON, addresses) + } + ++// txFromIndex builds a confirmed transaction from the index alone, for a pruned ++// backend that could not get the transaction's block from any peer. Inputs, ++// outputs, addresses, values, fee, vsize and block data come from txAddresses; ++// script hex, input txids, version, locktime and sequence numbers do not. ++func (w *Worker) txFromIndex(txid string, addresses map[string]struct{}) *Tx { ++ if w.chainType != bchain.ChainBitcoinType || !w.db.PrunedBackend() { ++ return nil ++ } ++ ta, err := w.db.GetTxAddresses(txid) ++ if err != nil || ta == nil { ++ return nil ++ } ++ bi, err := w.db.GetBlockInfo(ta.Height) ++ if err != nil || bi == nil { ++ return nil ++ } ++ bestheight, _, err := w.db.GetBestBlock() ++ if err != nil { ++ return nil ++ } ++ return w.txFromTxAddress(txid, ta, bi, bestheight, addresses) ++} ++ + func (w *Worker) getParsedEthereumInputData(data string) *bchain.EthereumParsedInputData { + var err error + var signatures *[]bchain.FourByteSignature +@@ -1758,6 +1784,9 @@ func (w *Worker) GetAddress(address string, page int, txsOnPage int, option Acco + } + // mempool txs take the first slots of the paged sequence, before confirmed history + appendMempoolTxs(mempoolFrom, mempoolTo) ++ if option == AccountDetailsTxHistory && from < to { ++ w.txCache.Prefetch(txc[from:to]) ++ } + for i := from; i < to; i++ { + txid := txc[i] + if option == AccountDetailsTxidHistory { +diff --git a/api/xpub.go b/api/xpub.go +index e55f3ba5..3cbf522b 100644 +--- a/api/xpub.go ++++ b/api/xpub.go +@@ -841,6 +841,13 @@ func (w *Worker) GetXpubAddress(xpub string, page int, txsOnPage int, option Acc + txs = append(txs, txmMap[entry.Txid]) + } + } ++ if option == AccountDetailsTxHistory && from < to { ++ prefetch := make([]string, 0, to-from) ++ for i := from; i < to; i++ { ++ prefetch = append(prefetch, txc[i].txid) ++ } ++ w.txCache.Prefetch(prefetch) ++ } + // get confirmed transactions + for i := from; i < to; i++ { + xpubTxid := &txc[i] +diff --git a/bchain/coins/blockchain.go b/bchain/coins/blockchain.go +index 9a92673d..55685e89 100644 +--- a/bchain/coins/blockchain.go ++++ b/bchain/coins/blockchain.go +@@ -292,6 +292,12 @@ func (c *blockChainWithMetrics) GetTransaction(txid string) (v *bchain.Tx, err e + return c.b.GetTransaction(txid) + } + ++func (c *blockChainWithMetrics) SetPrunedBackend(txBlock func(txid string) (string, error)) { ++ if p, ok := c.b.(bchain.PrunedBackendSetter); ok { ++ p.SetPrunedBackend(txBlock) ++ } ++} ++ + func (c *blockChainWithMetrics) GetTransactionSpecific(tx *bchain.Tx) (v json.RawMessage, err error) { + defer func(s time.Time) { c.observeRPCLatency("GetTransactionSpecific", s, err) }(time.Now()) + return c.b.GetTransactionSpecific(tx) +diff --git a/bchain/coins/btc/bitcoinrpc.go b/bchain/coins/btc/bitcoinrpc.go +index 1504f5fd..ac010a27 100644 +--- a/bchain/coins/btc/bitcoinrpc.go ++++ b/bchain/coins/btc/bitcoinrpc.go +@@ -6,8 +6,10 @@ import ( + "encoding/hex" + "encoding/json" + "math/big" ++ "math/rand" + "net" + "net/http" ++ "slices" + "strings" + "time" + +@@ -16,6 +18,7 @@ import ( + "github.com/martinboehm/btcd/wire" + "github.com/trezor/blockbook/bchain" + "github.com/trezor/blockbook/common" ++ "golang.org/x/sync/singleflight" + ) + + // BitcoinRPC is an interface to JSON-RPC bitcoind service. +@@ -41,6 +44,11 @@ type BitcoinRPC struct { + mempoolUseZeroedKey bool + alternativeFeeProvider alternativeFeeProviderInterface + metrics *common.Metrics ++ // txBlock is set for a pruned node without -txindex, see SetPrunedBackend ++ txBlock func(txid string) (string, error) ++ // blockFetches collapses concurrent downloads of one pruned block into one ++ blockFetches singleflight.Group ++ blockFetchSlots chan struct{} + } + + // SetMetrics sets prometheus metrics collector +@@ -512,6 +520,42 @@ type ResGetRawTransactionNonverbose struct { + Result string `json:"result"` + } + ++type CmdGetRawTransactionFromBlock struct { ++ Method string `json:"method"` ++ Params struct { ++ Txid string `json:"txid"` ++ Verbose bool `json:"verbose"` ++ Blockhash string `json:"blockhash"` ++ } `json:"params"` ++} ++ ++// getblockfrompeer, getpeerinfo ++ ++type CmdGetBlockFromPeer struct { ++ Method string `json:"method"` ++ Params struct { ++ Blockhash string `json:"blockhash"` ++ PeerID int `json:"peer_id"` ++ } `json:"params"` ++} ++ ++type ResGetBlockFromPeer struct { ++ Error *bchain.RPCError `json:"error"` ++ Result json.RawMessage `json:"result"` ++} ++ ++type CmdGetPeerInfo struct { ++ Method string `json:"method"` ++} ++ ++type ResGetPeerInfo struct { ++ Error *bchain.RPCError `json:"error"` ++ Result []struct { ++ ID int `json:"id"` ++ ServicesNames []string `json:"servicesnames"` ++ } `json:"result"` ++} ++ + type rpcBatchRequest struct { + JSONRPC string `json:"jsonrpc,omitempty"` + ID int `json:"id"` +@@ -739,6 +783,10 @@ func (b *BitcoinRPC) GetBlockInfo(hash string) (*bchain.BlockInfo, error) { + req.Params.BlockHash = hash + req.Params.Verbosity = 1 + err := b.Call(&req, &res) ++ if err == nil && res.Error != nil && b.refetchPrunedBlock(hash, res.Error) { ++ res = ResGetBlockInfo{} ++ err = b.Call(&req, &res) ++ } + + if err != nil { + return nil, errors.Annotatef(err, "hash %v", hash) +@@ -777,6 +825,10 @@ func (b *BitcoinRPC) GetBlockRaw(hash string) (string, error) { + req.Params.BlockHash = hash + req.Params.Verbosity = 0 + err := b.Call(&req, &res) ++ if err == nil && res.Error != nil && b.refetchPrunedBlock(hash, res.Error) { ++ res = ResGetBlockRaw{} ++ err = b.Call(&req, &res) ++ } + + if err != nil { + return "", errors.Annotatef(err, "hash %v", hash) +@@ -808,6 +860,10 @@ func (b *BitcoinRPC) GetBlockFull(hash string) (*bchain.Block, error) { + req.Params.BlockHash = hash + req.Params.Verbosity = 2 + err := b.Call(&req, &res) ++ if err == nil && res.Error != nil && b.refetchPrunedBlock(hash, res.Error) { ++ res = ResGetBlockFull{} ++ err = b.Call(&req, &res) ++ } + + if err != nil { + return nil, errors.Annotatef(err, "hash %v", hash) +@@ -1018,6 +1074,87 @@ func (b *BitcoinRPC) getRawTransaction(txid string) (json.RawMessage, error) { + return nil, errors.Annotatef(err, "txid %v", txid) + } + if res.Error != nil { ++ if IsMissingTx(res.Error) { ++ if b.txBlock != nil { ++ return b.getRawTransactionFromIndexedBlock(txid) ++ } ++ return nil, bchain.ErrTxNotFound ++ } ++ return nil, errors.Annotatef(res.Error, "txid %v", txid) ++ } ++ return res.Result, nil ++} ++ ++// SetPrunedBackend tells that the node is pruned and runs without -txindex, so ++// it can return a confirmed transaction only from its block: txBlock returns ++// the hash of that block from blockbook's index. A block the node has pruned ++// is downloaded again from a peer (getblockfrompeer, Bitcoin Core 24+) and ++// kept by the node until it prunes again. ++func (b *BitcoinRPC) SetPrunedBackend(txBlock func(txid string) (string, error)) { ++ b.txBlock = txBlock ++ b.blockFetchSlots = make(chan struct{}, maxBlockFetches) ++} ++ ++// blockFromPeerAttempts peers are asked for a pruned block in turn; one that ++// has not sent it within blockFromPeerTimeout is passed over ++const blockFromPeerAttempts = 3 ++ ++var blockFromPeerTimeout = 4 * time.Second ++ ++// At most maxBlockFetches pruned blocks are downloaded at once, which bounds ++// the bandwidth and tx cache growth that requests for old transactions cause; ++// a request that waits longer than blockFetchQueueTimeout for its turn fails. ++const maxBlockFetches = 8 ++ ++var blockFetchQueueTimeout = 30 * time.Second ++ ++var errBlockPruned = errors.New("block pruned") ++ ++// isBlockPruned reports the error of a node asked for data of a block it has ++// pruned: "Block not available" from getrawtransaction with a block hash, ++// "Block not available (pruned data)" from getblock ++func isBlockPruned(err *bchain.RPCError) bool { ++ return err.Code == -1 && strings.HasPrefix(err.Message, "Block not available") && !strings.Contains(err.Message, "not fully downloaded") ++} ++ ++func (b *BitcoinRPC) getRawTransactionFromIndexedBlock(txid string) (json.RawMessage, error) { ++ blockHash, err := b.txBlock(txid) ++ if err != nil { ++ return nil, errors.Annotatef(err, "txid %v", txid) ++ } ++ if blockHash == "" { ++ return nil, bchain.ErrTxNotFound ++ } ++ r, err := b.getRawTransactionFromBlock(txid, blockHash) ++ if err == errBlockPruned { ++ err = b.refetchBlock(blockHash, func() bool { ++ _, err := b.getRawTransactionFromBlock(txid, blockHash) ++ return err != errBlockPruned ++ }) ++ if err == nil { ++ r, err = b.getRawTransactionFromBlock(txid, blockHash) ++ } ++ } ++ return r, err ++} ++ ++func (b *BitcoinRPC) getRawTransactionFromBlock(txid string, blockHash string) (json.RawMessage, error) { ++ glog.V(1).Info("rpc: getrawtransaction ", txid, " in block ", blockHash) ++ ++ res := ResGetRawTransaction{} ++ req := CmdGetRawTransactionFromBlock{Method: "getrawtransaction"} ++ req.Params.Txid = txid ++ req.Params.Verbose = true ++ req.Params.Blockhash = blockHash ++ err := b.Call(&req, &res) ++ ++ if err != nil { ++ return nil, errors.Annotatef(err, "txid %v", txid) ++ } ++ if res.Error != nil { ++ if isBlockPruned(res.Error) { ++ return nil, errBlockPruned ++ } + if IsMissingTx(res.Error) { + return nil, bchain.ErrTxNotFound + } +@@ -1026,6 +1163,102 @@ func (b *BitcoinRPC) getRawTransaction(txid string) (json.RawMessage, error) { + return res.Result, nil + } + ++// refetchPrunedBlock downloads again a block that a getblock call was refused ++// because the node had pruned it, and reports whether to repeat the call ++func (b *BitcoinRPC) refetchPrunedBlock(blockHash string, rpcErr *bchain.RPCError) bool { ++ if b.txBlock == nil || !isBlockPruned(rpcErr) { ++ return false ++ } ++ if err := b.refetchBlock(blockHash, func() bool { return b.blockStored(blockHash) }); err != nil { ++ glog.Warning("rpc: ", err) ++ return false ++ } ++ return true ++} ++ ++// blockStored reports whether the node has the block's data ++func (b *BitcoinRPC) blockStored(blockHash string) bool { ++ res := ResGetBlockInfo{} ++ req := CmdGetBlock{Method: "getblock"} ++ req.Params.BlockHash = blockHash ++ req.Params.Verbosity = 1 ++ return b.Call(&req, &res) == nil && res.Error == nil ++} ++ ++// refetchBlock downloads a pruned block again; arrived reports whether the ++// node has stored it. Concurrent requests for one block share one download. ++func (b *BitcoinRPC) refetchBlock(blockHash string, arrived func() bool) error { ++ _, err, _ := b.blockFetches.Do(blockHash, func() (interface{}, error) { ++ return nil, b.fetchBlockFromPeers(blockHash, arrived) ++ }) ++ return err ++} ++ ++func (b *BitcoinRPC) fetchBlockFromPeers(blockHash string, arrived func() bool) error { ++ select { ++ case b.blockFetchSlots <- struct{}{}: ++ defer func() { <-b.blockFetchSlots }() ++ case <-time.After(blockFetchQueueTimeout): ++ return errors.Errorf("block %v is pruned and %d downloads are already running", blockHash, maxBlockFetches) ++ } ++ peers, err := b.archivalPeers() ++ if err != nil { ++ return errors.Annotatef(err, "block %v is pruned", blockHash) ++ } ++ for i, id := range peers { ++ if i == blockFromPeerAttempts { ++ break ++ } ++ glog.V(1).Info("rpc: getblockfrompeer ", blockHash, " peer ", id) ++ res := ResGetBlockFromPeer{} ++ req := CmdGetBlockFromPeer{Method: "getblockfrompeer"} ++ req.Params.Blockhash = blockHash ++ req.Params.PeerID = id ++ if err := b.Call(&req, &res); err != nil { ++ return errors.Annotatef(err, "getblockfrompeer %v", blockHash) ++ } ++ if res.Error != nil { ++ // another request stored it meanwhile ++ if strings.Contains(res.Error.Message, "already downloaded") { ++ return nil ++ } ++ glog.Warning("rpc: getblockfrompeer ", blockHash, " peer ", id, ": ", res.Error) ++ continue ++ } ++ for deadline := time.Now().Add(blockFromPeerTimeout); time.Now().Before(deadline); { ++ time.Sleep(100 * time.Millisecond) ++ if arrived() { ++ return nil ++ } ++ } ++ glog.Warning("rpc: getblockfrompeer ", blockHash, " peer ", id, ": no block in ", blockFromPeerTimeout) ++ } ++ return errors.Errorf("block %v is pruned and no peer sent it", blockHash) ++} ++ ++// archivalPeers returns the connected peers that serve every block (NODE_NETWORK, ++// not only the last 288 blocks of NODE_NETWORK_LIMITED), in random order ++func (b *BitcoinRPC) archivalPeers() ([]int, error) { ++ res := ResGetPeerInfo{} ++ if err := b.Call(&CmdGetPeerInfo{Method: "getpeerinfo"}, &res); err != nil { ++ return nil, errors.Annotatef(err, "getpeerinfo") ++ } ++ if res.Error != nil { ++ return nil, errors.Annotatef(res.Error, "getpeerinfo") ++ } ++ var peers []int ++ for _, p := range res.Result { ++ if slices.Contains(p.ServicesNames, "NETWORK") && slices.Contains(p.ServicesNames, "WITNESS") { ++ peers = append(peers, p.ID) ++ } ++ } ++ if len(peers) == 0 { ++ return nil, errors.New("no connected peer serves old blocks") ++ } ++ rand.Shuffle(len(peers), func(i, j int) { peers[i], peers[j] = peers[j], peers[i] }) ++ return peers, nil ++} ++ + func (b *BitcoinRPC) blockchainEstimateSmartFee(blocks int, conservative bool) (big.Int, error) { + // use EstimateFee if EstimateSmartFee is not supported + if !b.ChainConfig.SupportsEstimateSmartFee && b.ChainConfig.SupportsEstimateFee { +diff --git a/bchain/coins/btc/bitcoinrpc_pruned_test.go b/bchain/coins/btc/bitcoinrpc_pruned_test.go +new file mode 100644 +index 00000000..bd11a8e0 +--- /dev/null ++++ b/bchain/coins/btc/bitcoinrpc_pruned_test.go +@@ -0,0 +1,295 @@ ++package btc ++ ++import ( ++ "encoding/json" ++ "io" ++ "net/http" ++ "strings" ++ "sync" ++ "testing" ++ "time" ++ ++ "github.com/trezor/blockbook/bchain" ++) ++ ++const ( ++ prunedTxid = "8a4d7b8c6e2f0b5e3a1d9c7f6e5d4c3b2a19f8e7d6c5b4a39281706f5e4d3c2b" ++ prunedBlock = "00000000000000000002a7c4c1e48d76c5a37902165a270156b7a8d72728a054" ++ prunedTxRaw = `{"txid":"` + prunedTxid + `","hash":"` + prunedTxid + `","version":2,"size":191,"vsize":110,"weight":437,"locktime":0,` + ++ `"vin":[{"txid":"1f2e3d4c5b6a79881f2e3d4c5b6a79881f2e3d4c5b6a79881f2e3d4c5b6a7988","vout":1,"scriptSig":{"asm":"","hex":""},"txinwitness":["30","02"],"sequence":4294967293}],` + ++ `"vout":[{"value":0.0005,"n":0,"scriptPubKey":{"asm":"0 751e76e8199196d454941c45d1b3a323f1433bd6","hex":"0014751e76e8199196d454941c45d1b3a323f1433bd6","address":"bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4","type":"witness_v0_keyhash"}}],` + ++ `"hex":"02000000000101","blockhash":"` + prunedBlock + `","confirmations":10,"time":1700000000,"blocktime":1700000000,"in_active_chain":true}` ++ twoPeers = `[{"id":3,"servicesnames":["NETWORK_LIMITED","WITNESS"]},{"id":7,"servicesnames":["NETWORK","WITNESS","NETWORK_LIMITED","P2P_V2"]}]` ++) ++ ++// fakePrunedNode answers like Bitcoin Core 31 run with prune=1 and without ++// txindex. The block is pruned until a peer sends it, arriveAfter after ++// getblockfrompeer if sends is set. ++type fakePrunedNode struct { ++ mu sync.Mutex ++ pruned bool ++ peers string ++ sends bool ++ arriveAfter time.Duration ++ requested []int ++ methods []string ++} ++ ++func (f *fakePrunedNode) handle(body string) string { ++ var req struct { ++ Method string `json:"method"` ++ Params json.RawMessage `json:"params"` ++ } ++ if err := json.Unmarshal([]byte(body), &req); err != nil { ++ return `{"result":null,"error":{"code":-32700,"message":"Parse error"},"id":1}` ++ } ++ f.mu.Lock() ++ defer f.mu.Unlock() ++ f.methods = append(f.methods, req.Method) ++ switch req.Method { ++ case "getrawtransaction": ++ var p struct { ++ Txid string `json:"txid"` ++ Blockhash string `json:"blockhash"` ++ } ++ _ = json.Unmarshal(req.Params, &p) ++ if p.Blockhash == "" { ++ return `{"result":null,"error":{"code":-5,"message":"No such mempool transaction. Use -txindex or provide a block hash to enable blockchain transaction queries. Use gettransaction for wallet transactions."},"id":1}` ++ } ++ if f.pruned { ++ return `{"result":null,"error":{"code":-1,"message":"Block not available"},"id":1}` ++ } ++ if p.Txid != prunedTxid { ++ return `{"result":null,"error":{"code":-5,"message":"No such transaction found in the provided block. Use gettransaction for wallet transactions."},"id":1}` ++ } ++ return `{"result":` + prunedTxRaw + `,"error":null,"id":1}` ++ case "getblock": ++ var p struct { ++ Verbosity int `json:"verbosity"` ++ } ++ _ = json.Unmarshal(req.Params, &p) ++ if f.pruned { ++ return `{"result":null,"error":{"code":-1,"message":"Block not available (pruned data)"},"id":1}` ++ } ++ if p.Verbosity == 0 { ++ return `{"result":"00","error":null,"id":1}` ++ } ++ return `{"result":{"hash":"` + prunedBlock + `","height":5,"tx":["` + prunedTxid + `"]},"error":null,"id":1}` ++ case "getpeerinfo": ++ return `{"result":` + f.peers + `,"error":null,"id":1}` ++ case "getblockfrompeer": ++ var p struct { ++ PeerID int `json:"peer_id"` ++ } ++ _ = json.Unmarshal(req.Params, &p) ++ if !f.pruned { ++ return `{"result":null,"error":{"code":-1,"message":"Block already downloaded"},"id":1}` ++ } ++ f.requested = append(f.requested, p.PeerID) ++ if f.sends { ++ time.AfterFunc(f.arriveAfter, func() { ++ f.mu.Lock() ++ f.pruned = false ++ f.mu.Unlock() ++ }) ++ } ++ return `{"result":{},"error":null,"id":1}` ++ } ++ return `{"result":null,"error":{"code":-32601,"message":"Method not found"},"id":1}` ++} ++ ++func (f *fakePrunedNode) calls(method string) int { ++ f.mu.Lock() ++ defer f.mu.Unlock() ++ n := 0 ++ for _, m := range f.methods { ++ if m == method { ++ n++ ++ } ++ } ++ return n ++} ++ ++// newFakePrunedRPC wires a BitcoinRPC to f; the index places prunedTxid in ++// prunedBlock and knows no other transaction ++func newFakePrunedRPC(f *fakePrunedNode, pruned bool) *BitcoinRPC { ++ cfg := &Configuration{} ++ transport := roundTripFunc(func(r *http.Request) (*http.Response, error) { ++ body, _ := io.ReadAll(r.Body) ++ return &http.Response{ ++ StatusCode: 200, ++ Body: io.NopCloser(strings.NewReader(f.handle(string(body)))), ++ Header: http.Header{"Content-Type": []string{"application/json"}}, ++ }, nil ++ }) ++ b := &BitcoinRPC{ ++ BaseChain: &bchain.BaseChain{Parser: NewBitcoinParser(GetChainParams("main"), cfg)}, ++ client: http.Client{Transport: transport}, ++ rpcURL: "http://backend", ++ ChainConfig: cfg, ++ RPCMarshaler: JSONMarshalerV2{}, ++ } ++ if pruned { ++ b.SetPrunedBackend(func(txid string) (string, error) { ++ if txid == prunedTxid { ++ return prunedBlock, nil ++ } ++ return "", nil ++ }) ++ } ++ return b ++} ++ ++func checkPrunedTx(t *testing.T, tx *bchain.Tx) { ++ t.Helper() ++ if tx.Txid != prunedTxid || tx.VSize != 110 || tx.Hex == "" || tx.Confirmations != 10 || tx.Blocktime != 1700000000 || tx.Version != 2 { ++ t.Fatalf("unexpected tx %+v", tx) ++ } ++ if len(tx.Vin) != 1 || tx.Vin[0].Txid == "" || tx.Vin[0].Vout != 1 || tx.Vin[0].Sequence != 4294967293 { ++ t.Fatalf("unexpected vin %+v", tx.Vin) ++ } ++} ++ ++func TestPrunedTxFromBlockOnDisk(t *testing.T) { ++ f := &fakePrunedNode{peers: twoPeers} ++ tx, err := newFakePrunedRPC(f, true).GetTransaction(prunedTxid) ++ if err != nil { ++ t.Fatal(err) ++ } ++ checkPrunedTx(t, tx) ++ if f.calls("getpeerinfo") != 0 || f.calls("getblockfrompeer") != 0 { ++ t.Fatalf("a block on disk must not be downloaded, calls %v", f.methods) ++ } ++} ++ ++func TestPrunedTxBlockDownloadedFromArchivalPeer(t *testing.T) { ++ f := &fakePrunedNode{peers: twoPeers, pruned: true, sends: true, arriveAfter: 300 * time.Millisecond} ++ tx, err := newFakePrunedRPC(f, true).GetTransaction(prunedTxid) ++ if err != nil { ++ t.Fatal(err) ++ } ++ checkPrunedTx(t, tx) ++ if len(f.requested) != 1 || f.requested[0] != 7 { ++ t.Fatalf("expected one request to the archival peer 7, got %v", f.requested) ++ } ++} ++ ++// tx-specific of a cached transaction has no backend JSON and asks the node again ++func TestPrunedTxSpecific(t *testing.T) { ++ f := &fakePrunedNode{peers: twoPeers, pruned: true, sends: true, arriveAfter: 100 * time.Millisecond} ++ sj, err := newFakePrunedRPC(f, true).GetTransactionSpecific(&bchain.Tx{Txid: prunedTxid}) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if !strings.Contains(string(sj), `"vsize":110`) { ++ t.Fatalf("unexpected tx-specific %s", sj) ++ } ++} ++ ++func TestPrunedTxConcurrentRequestsShareOneDownload(t *testing.T) { ++ f := &fakePrunedNode{peers: twoPeers, pruned: true, sends: true, arriveAfter: 500 * time.Millisecond} ++ b := newFakePrunedRPC(f, true) ++ var wg sync.WaitGroup ++ errs := make([]error, 5) ++ for i := range errs { ++ wg.Add(1) ++ go func(i int) { ++ defer wg.Done() ++ _, errs[i] = b.GetTransaction(prunedTxid) ++ }(i) ++ } ++ wg.Wait() ++ for _, err := range errs { ++ if err != nil { ++ t.Fatal(err) ++ } ++ } ++ if len(f.requested) != 1 { ++ t.Fatalf("expected one download for concurrent requests, got %v", f.requested) ++ } ++} ++ ++func TestPrunedTxNoPeerSends(t *testing.T) { ++ saved := blockFromPeerTimeout ++ blockFromPeerTimeout = 200 * time.Millisecond ++ defer func() { blockFromPeerTimeout = saved }() ++ peers := `[{"id":1,"servicesnames":["NETWORK","WITNESS"]},{"id":2,"servicesnames":["NETWORK","WITNESS"]},` + ++ `{"id":4,"servicesnames":["NETWORK","WITNESS"]},{"id":5,"servicesnames":["NETWORK","WITNESS"]}]` ++ f := &fakePrunedNode{peers: peers, pruned: true} ++ _, err := newFakePrunedRPC(f, true).GetTransaction(prunedTxid) ++ if err == nil || err == bchain.ErrTxNotFound { ++ t.Fatalf("expected a download error, got %v", err) ++ } ++ if len(f.requested) != blockFromPeerAttempts { ++ t.Fatalf("expected %d peers asked, got %v", blockFromPeerAttempts, f.requested) ++ } ++} ++ ++func TestPrunedTxNoArchivalPeer(t *testing.T) { ++ f := &fakePrunedNode{peers: `[{"id":3,"servicesnames":["NETWORK_LIMITED","WITNESS"]}]`, pruned: true, sends: true} ++ if _, err := newFakePrunedRPC(f, true).GetTransaction(prunedTxid); err == nil { ++ t.Fatal("expected an error without a peer that serves old blocks") ++ } ++ if f.calls("getblockfrompeer") != 0 { ++ t.Fatalf("a limited peer must not be asked, calls %v", f.methods) ++ } ++} ++ ++func TestPrunedTxUnknownToIndex(t *testing.T) { ++ f := &fakePrunedNode{peers: twoPeers} ++ if _, err := newFakePrunedRPC(f, true).GetTransaction(strings.Repeat("0", 64)); err != bchain.ErrTxNotFound { ++ t.Fatalf("expected ErrTxNotFound, got %v", err) ++ } ++ if f.calls("getrawtransaction") != 1 { ++ t.Fatalf("a transaction the index does not know must not be looked up in a block, calls %v", f.methods) ++ } ++} ++ ++func TestNotPrunedBackendUnchanged(t *testing.T) { ++ f := &fakePrunedNode{peers: twoPeers, pruned: true, sends: true} ++ b := newFakePrunedRPC(f, false) ++ if _, err := b.GetTransaction(prunedTxid); err != bchain.ErrTxNotFound { ++ t.Fatalf("expected ErrTxNotFound, got %v", err) ++ } ++ if _, err := b.GetBlockRaw(prunedBlock); err == nil { ++ t.Fatal("expected the getblock error") ++ } ++ if f.calls("getblockfrompeer") != 0 || f.calls("getpeerinfo") != 0 { ++ t.Fatalf("only a pruned backend downloads blocks again, calls %v", f.methods) ++ } ++} ++ ++func TestPrunedBlockDownloadedFromArchivalPeer(t *testing.T) { ++ f := &fakePrunedNode{peers: twoPeers, pruned: true, sends: true, arriveAfter: 100 * time.Millisecond} ++ b := newFakePrunedRPC(f, true) ++ bi, err := b.GetBlockInfo(prunedBlock) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if len(bi.Txids) != 1 || bi.Txids[0] != prunedTxid { ++ t.Fatalf("unexpected block info %+v", bi) ++ } ++ if raw, err := b.GetBlockRaw(prunedBlock); err != nil || raw != "00" { ++ t.Fatalf("unexpected raw block %q, %v", raw, err) ++ } ++ if len(f.requested) != 1 || f.requested[0] != 7 { ++ t.Fatalf("expected one request to the archival peer 7, got %v", f.requested) ++ } ++} ++ ++func TestPrunedBlockDownloadsAreBounded(t *testing.T) { ++ saved := blockFetchQueueTimeout ++ blockFetchQueueTimeout = 100 * time.Millisecond ++ defer func() { blockFetchQueueTimeout = saved }() ++ f := &fakePrunedNode{peers: twoPeers, pruned: true, sends: true} ++ b := newFakePrunedRPC(f, true) ++ for i := 0; i < maxBlockFetches; i++ { ++ b.blockFetchSlots <- struct{}{} ++ } ++ if _, err := b.GetTransaction(prunedTxid); err == nil || err == bchain.ErrTxNotFound { ++ t.Fatalf("expected a busy error, got %v", err) ++ } ++ if f.calls("getblockfrompeer") != 0 { ++ t.Fatalf("no download may start while all slots are taken, calls %v", f.methods) ++ } ++} +diff --git a/bchain/types.go b/bchain/types.go +index dfb9e38e..e83cd69d 100644 +--- a/bchain/types.go ++++ b/bchain/types.go +@@ -299,6 +299,15 @@ type MempoolBatcher interface { + GetRawTransactionsForMempoolBatch(txids []string) (map[string]*Tx, error) + } + ++// PrunedBackendSetter is implemented by a backend that still returns confirmed ++// transactions and old blocks when it is pruned and runs without a transaction ++// index: txBlock, backed by blockbook's index, returns the hash of the block ++// holding a transaction ("" if unknown), and pruned blocks are downloaded ++// again from peers. ++type PrunedBackendSetter interface { ++ SetPrunedBackend(txBlock func(txid string) (string, error)) ++} ++ + // BlockChain defines common interface to block chain daemon + type BlockChain interface { + // life-cycle methods +diff --git a/blockbook.go b/blockbook.go +index 0854364c..6d43f5d1 100644 +--- a/blockbook.go ++++ b/blockbook.go +@@ -95,6 +95,10 @@ var ( + resyncMempoolPeriodMs = flag.Int("resyncmempoolperiod", 60017, "resync mempool period in milliseconds") + + extendedIndex = flag.Bool("extendedindex", false, "if true, create index of input txids and spending transactions") ++ ++ prunedBackend = flag.Bool("prunedbackend", false, "the backend is pruned and runs without -txindex: get confirmed transactions from their blocks, download pruned blocks again from peers, store vsizes in the index") ++ ++ txCacheMaxGB = flag.Int("txcachemaxgb", 0, "empty the tx cache when it takes more than this many GB, 0 = never") + ) + + var ( +@@ -225,6 +229,14 @@ func mainWithExitCode() int { + glog.Error("rocksDB: ", err) + return exitCodeFatal + } ++ index.SetPrunedBackend(*prunedBackend) ++ if *prunedBackend { ++ if p, ok := chain.(bchain.PrunedBackendSetter); ok { ++ p.SetPrunedBackend(index.TxBlockHash) ++ } else { ++ glog.Warning("prunedbackend: this backend cannot return old transactions") ++ } ++ } + defer func() { + glog.Info("shutdown: rocksdb close start") + if err := index.Close(); err != nil { +@@ -810,6 +822,7 @@ func storeInternalStateLoop() { + lastCompute := time.Now() + lastAppInfo := time.Now() + logAppInfoPeriod := 15 * time.Minute ++ var lastTxCacheTrim time.Time + // randomize the duration between ComputeInternalStateColumnStats to avoid peaks after reboot of machine with multiple blockbooks + computePeriod := time.Duration(*dbStatsPeriodHours)*time.Hour + time.Duration(rand.Float64()*float64((4*time.Hour).Nanoseconds())) + if (*dbStatsPeriodHours) > 0 { +@@ -838,6 +851,12 @@ func storeInternalStateLoop() { + if err := index.StoreInternalState(internalState); err != nil { + glog.Error("storeInternalStateLoop ", errors.ErrorStack(err)) + } ++ if *txCacheMaxGB > 0 && time.Since(lastTxCacheTrim) > time.Hour { ++ lastTxCacheTrim = time.Now() ++ if err := index.TrimTxCache(uint64(*txCacheMaxGB) << 30); err != nil { ++ glog.Error("trimTxCache ", err) ++ } ++ } + if lastAppInfo.Add(logAppInfoPeriod).Before(time.Now()) { + if glog.V(1) { + glog.Info(index.GetMemoryStats()) +diff --git a/common/internalstate.go b/common/internalstate.go +index 77674c13..819d1d1b 100644 +--- a/common/internalstate.go ++++ b/common/internalstate.go +@@ -63,6 +63,7 @@ type InternalState struct { + + DbState uint32 `json:"dbState" ts_doc:"State of the database (closed=0, open=1, inconsistent=2)."` + ExtendedIndex bool `json:"extendedIndex" ts_doc:"Indicates if an extended indexing strategy is used."` ++ PrunedBackend bool `json:"prunedBackend,omitempty" ts_doc:"Indicates that the backend is pruned and the index stores transaction vsizes."` + + LastStore time.Time `json:"lastStore" ts_doc:"Time when the internal state was last stored/persisted."` + +diff --git a/db/rocksdb.go b/db/rocksdb.go +index 7637534a..366f7d1c 100644 +--- a/db/rocksdb.go ++++ b/db/rocksdb.go +@@ -296,6 +296,7 @@ type RocksDB struct { + maxOpenFiles int + cbs connectBlockStats + extendedIndex bool ++ prunedBackend bool + connectBlockMux sync.Mutex + // reorgGen advances on every successful Ethereum-type disconnect; embed + // in cache keys so a same-height reorg invalidates them lazily. +@@ -521,6 +522,33 @@ func (d *RocksDB) HasExtendedIndex() bool { + return d.extendedIndex + } + ++// SetPrunedBackend marks the backend as pruned and without -txindex. The index ++// then also stores each transaction's vsize, for when no peer sends the block ++// of an old transaction. It must be called before LoadInternalState. ++func (d *RocksDB) SetPrunedBackend(pruned bool) { ++ d.prunedBackend = pruned ++} ++ ++// PrunedBackend returns true if the backend is pruned and runs without -txindex ++func (d *RocksDB) PrunedBackend() bool { ++ return d.prunedBackend ++} ++ ++// storesVSize returns true if TxAddresses records carry the transaction's vsize ++func (d *RocksDB) storesVSize() bool { ++ return d.extendedIndex || d.prunedBackend ++} ++ ++// TxBlockHash returns the hash of the block holding a confirmed transaction, ++// or "" if the index does not know the transaction ++func (d *RocksDB) TxBlockHash(txid string) (string, error) { ++ ta, err := d.GetTxAddresses(txid) ++ if err != nil || ta == nil { ++ return "", err ++ } ++ return d.GetBlockHash(ta.Height) ++} ++ + // GetMemoryStats returns memory usage statistics as reported by RocksDB + func (d *RocksDB) GetMemoryStats() string { + var total, indexAndFilter, memtable uint64 +@@ -990,7 +1018,7 @@ func (d *RocksDB) processAddressesBitcoinType(block *bchain.Block, addresses add + } + blockTxIDs[txi] = btxID + ta := TxAddresses{Height: block.Height} +- if d.extendedIndex { ++ if d.storesVSize() { + if tx.VSize > 0 { + ta.VSize = uint32(tx.VSize) + } else { +@@ -1379,7 +1407,7 @@ func (d *RocksDB) GetTxAddressesOutput(txid string, vout uint32) (*TxOutput, err + return nil, nil + } + _, l := unpackVaruint(buf) // height +- if d.extendedIndex { ++ if d.storesVSize() { + _, n := unpackVaruint(buf[l:]) // vsize + l += n + } +@@ -1424,7 +1452,7 @@ func (d *RocksDB) packTxAddresses(ta *TxAddresses, buf []byte, varBuf []byte) [] + buf = buf[:0] + l := packVaruint(uint(ta.Height), varBuf) + buf = append(buf, varBuf[:l]...) +- if d.extendedIndex { ++ if d.storesVSize() { + l = packVaruint(uint(ta.VSize), varBuf) + buf = append(buf, varBuf[:l]...) + } +@@ -1569,7 +1597,7 @@ func (d *RocksDB) unpackTxAddresses(buf []byte) (*TxAddresses, error) { + ta := TxAddresses{} + height, l := unpackVaruint(buf) + ta.Height = uint32(height) +- if d.extendedIndex { ++ if d.storesVSize() { + vsize, ll := unpackVaruint(buf[l:]) + ta.VSize = uint32(vsize) + l += ll +@@ -2244,6 +2272,24 @@ func (d *RocksDB) PutTx(tx *bchain.Tx, height uint32, blockTime int64) error { + return err + } + ++// TrimTxCache empties the tx cache once its files take more than maxBytes. ++// Nothing is ever evicted from it, and with a pruned backend it receives every ++// old transaction anyone asks for. ++func (d *RocksDB) TrimTxCache(maxBytes uint64) error { ++ size, _ := d.db.GetIntPropertyCF("rocksdb.live-sst-files-size", d.cfh[cfTransactions]) ++ if size <= maxBytes { ++ return nil ++ } ++ glog.Infof("rocksdb: tx cache takes %d bytes, more than %d, emptying it", size, maxBytes) ++ end := bytes.Repeat([]byte{0xff}, d.chainParser.PackedTxidLen()+1) ++ if err := d.db.DeleteRangeCF(d.wo, d.cfh[cfTransactions], []byte{}, end); err != nil { ++ return err ++ } ++ d.is.SetDBColumnStats(cfTransactions, 0, 0, 0) ++ d.db.CompactRangeCF(d.cfh[cfTransactions], grocksdb.Range{}) ++ return nil ++} ++ + // DeleteTx removes transactions from db + func (d *RocksDB) DeleteTx(txid string) error { + key, err := d.chainParser.PackTxid(txid) +@@ -2448,6 +2494,7 @@ func (d *RocksDB) LoadInternalState(config *common.Config) (*common.InternalStat + UtxoChecked: true, + SortedAddressContracts: true, + ExtendedIndex: d.extendedIndex, ++ PrunedBackend: d.prunedBackend, + BlockGolombFilterP: config.BlockGolombFilterP, + BlockFilterScripts: config.BlockFilterScripts, + BlockFilterUseZeroedKey: config.BlockFilterUseZeroedKey, +@@ -2467,6 +2514,9 @@ func (d *RocksDB) LoadInternalState(config *common.Config) (*common.InternalStat + if is.ExtendedIndex != d.extendedIndex { + return nil, errors.Errorf("ExtendedIndex setting does not match. DB extendedIndex %v, extendedIndex in options %v", is.ExtendedIndex, d.extendedIndex) + } ++ if is.PrunedBackend != d.prunedBackend { ++ return nil, errors.Errorf("PrunedBackend setting does not match. DB prunedBackend %v, prunedBackend in options %v", is.PrunedBackend, d.prunedBackend) ++ } + if is.BlockGolombFilterP != config.BlockGolombFilterP { + return nil, errors.Errorf("BlockGolombFilterP does not match. DB BlockGolombFilterP %v, config BlockGolombFilterP %v", is.BlockGolombFilterP, config.BlockGolombFilterP) + } +diff --git a/db/txcache.go b/db/txcache.go +index 26f0da83..69ada6fc 100644 +--- a/db/txcache.go ++++ b/db/txcache.go +@@ -1,6 +1,8 @@ + package db + + import ( ++ "sync" ++ + "github.com/golang/glog" + "github.com/juju/errors" + "github.com/trezor/blockbook/bchain" +@@ -106,3 +108,31 @@ func (c *TxCache) GetTransaction(txid string) (*bchain.Tx, int, error) { + } + return tx, int(h), nil + } ++ ++// prefetchParallelism bounds the transactions of one history page fetched at once ++const prefetchParallelism = 8 ++ ++// Prefetch puts the given transactions into the cache concurrently. With a ++// pruned backend an old transaction may need its block from a peer, and a ++// history page would otherwise wait for those downloads one after another. ++func (c *TxCache) Prefetch(txids []string) { ++ if !c.enabled || !c.db.PrunedBackend() || len(txids) < 2 { ++ return ++ } ++ sem := make(chan struct{}, prefetchParallelism) ++ var wg sync.WaitGroup ++ for _, txid := range txids { ++ wg.Add(1) ++ sem <- struct{}{} ++ go func(txid string) { ++ defer func() { ++ <-sem ++ wg.Done() ++ }() ++ if _, _, err := c.GetTransaction(txid); err != nil { ++ glog.V(1).Info("txcache: prefetch ", txid, ": ", err) ++ } ++ }(txid) ++ } ++ wg.Wait() ++} +diff --git a/server/websocket.go b/server/websocket.go +index a5a89bc9..bc5a8580 100644 +--- a/server/websocket.go ++++ b/server/websocket.go +@@ -1779,6 +1779,13 @@ func populateBitcoinVinAddrDescs(vins []bchain.MempoolVin, getAddrDesc func(stri + // getBitcoinVinAddrDesc resolves an input outpoint to an address descriptor + // using txCache. It is best-effort and can return chain-level not-found errors. + func (s *WebsocketServer) getBitcoinVinAddrDesc(txid string, vout uint32) (bchain.AddressDescriptor, error) { ++ // The index has every confirmed output. The backend may not: a pruned one ++ // would download the previous transaction's block for every input. ++ if s.db != nil { ++ if addrDesc, _ := s.db.AddrDescForOutpoint(bchain.Outpoint{Txid: txid, Vout: int32(vout)}); len(addrDesc) > 0 { ++ return addrDesc, nil ++ } ++ } + if s.txCache == nil { + return nil, bchain.ErrTxNotFound + } diff --git a/prune.sh b/prune.sh new file mode 100755 index 0000000..2fc0902 --- /dev/null +++ b/prune.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Keeps a pruned backend just ahead of blockbook (PRUNE_BACKEND=1). +# +# A Bitcoin node that keeps every block no longer fits in a Flux app: 886 GB +# of blocks in October 2026 against an app limit of 820 GB, before txindex. +# Blockbook only needs a block until it has indexed it, so the daemon runs +# with prune=1 (manual pruning) and this job prunes what blockbook has +# indexed, minus a reorg margin. While blockbook indexes slower than the +# daemon downloads, the daemon is taken off the network so blocks waiting to +# be indexed cannot fill the disk. Blockbook gets old transactions from their +# blocks, downloading pruned ones again from peers (patches/0001). +CONFIG_FILE=${CONFIG_FILE:-$COIN} +CONFIG_DIR=${CONFIG_DIR:-$COIN} +KEEP=${PRUNE_KEEP_BLOCKS:-2000} +MAX_GB=${PRUNE_MAX_BLOCKS_GB:-80} +LOG=/root/prune_events.log + +[[ "$PRUNE_BACKEND" == "1" && "$DAEMON" == "1" && -f /run/bb/bootstrapped ]] || exit 0 +CLI_NAME=${CLI_NAME:-$(jq -r '.cli_name // empty' /root/daemon_config.json 2>/dev/null)} +[[ -n "$CLI_NAME" ]] && command -v "$CLI_NAME" > /dev/null || exit 0 + +function cli() { + timeout 300 "$CLI_NAME" -conf="/root/$CONFIG_DIR/$CONFIG_FILE.conf" \ + -rpcuser="$(jq -r .rpc_user /root/blockchaincfg.json)" -rpcpassword="$(jq -r .rpc_pass /root/blockchaincfg.json)" "$@" +} + +INDEXED=$(curl -s -m 20 http://127.0.0.1:${BLOCKBOOK_PORT}/api | jq -r '.blockbook.bestHeight // 0' 2>/dev/null) +INDEXED=${INDEXED:-0} +if (( INDEXED > KEEP + 288 )); then + cli pruneblockchain $((INDEXED - KEEP)) > /dev/null 2>&1 +fi + +BLOCKS_GB=$(du -s --block-size=1G /root/$CONFIG_DIR/backend/blocks 2>/dev/null | cut -f1) +BLOCKS_GB=${BLOCKS_GB:-0} +ACTIVE=$(cli getnetworkinfo 2>/dev/null | jq -r '.networkactive') +if (( BLOCKS_GB > MAX_GB )) && [[ "$ACTIVE" == "true" ]]; then + cli setnetworkactive false > /dev/null + echo "[$(date '+%Y-%m-%d %H:%M:%S')] ${BLOCKS_GB} GB of blocks waiting for blockbook (indexed $INDEXED), network paused" >> $LOG +elif (( BLOCKS_GB < MAX_GB * 3 / 4 )) && [[ "$ACTIVE" == "false" ]]; then + cli setnetworkactive true > /dev/null + echo "[$(date '+%Y-%m-%d %H:%M:%S')] blocks down to ${BLOCKS_GB} GB (indexed $INDEXED), network resumed" >> $LOG +fi diff --git a/snapshot.sh b/snapshot.sh new file mode 100755 index 0000000..7c8f76c --- /dev/null +++ b/snapshot.sh @@ -0,0 +1,251 @@ +#!/usr/bin/env bash +# Peer snapshots: instances of one Flux app seed each other. +# +# Flux moves instances between nodes all the time, and a new instance used to +# sync its daemon and index its chain from block 0 - days to weeks - so a large +# share of every blockbook app was always in initial sync. Now a synced +# instance keeps a snapshot of its chain data (create), snapshot_server.py +# serves it on container port 1337 to the other instances of the same app, and +# a new or far-behind instance downloads it before starting (restore). +# +# A snapshot costs almost no disk: database files that are never rewritten +# (LevelDB/RocksDB tables, blk/rev files) are hard links, only the small +# mutable files are copied, and the daemon and blockbook are stopped for the +# few seconds that takes so the copy is consistent. +# +# snapshot.sh create take a snapshot if this instance is synced +# snapshot.sh restore seed backend + index from the best peer +# snapshot.sh restore-blockbook seed only the index (backend is synced) +# snapshot.sh reseed reseed an instance that is far behind +CONFIG_FILE=${CONFIG_FILE:-$COIN} +CONFIG_DIR=${CONFIG_DIR:-$COIN} +SNAP=/root/snapshot +BACKEND=/root/$CONFIG_DIR/backend +BBDB=/root/blockbook-db +TMP=/root/restore.tmp +INTERVAL=${SNAPSHOT_INTERVAL:-86400} +MIN_FREE=${SNAPSHOT_MIN_FREE_PCT:-15} +API=https://api.runonflux.io + +function log() { echo "| $(date '+%Y-%m-%d %H:%M:%S') $*"; } +function free_pct() { df -P /root | awk 'NR==2 { sub("%", "", $5); print 100 - $5 }'; } +function free_bytes() { df -P -B1 /root | awk 'NR==2 { print $4 }'; } +function bytes() { du -sb "$@" 2>/dev/null | awk '{ s += $1 } END { print s + 0 }'; } + +# Hard links for files a database never rewrites, copies for the rest. +# $3=1 includes files at the top of $1 (blockbook-db); the backend's top level +# holds wallet.dat, configs and logs, which are never shared. +function link_tree() { + local src=$1 dst=$2 top=$3 + mkdir -p "$dst" + (cd "$src" && find . -mindepth 1 -type d ! -path './database' ! -path './database/*') | while read -r d; do + mkdir -p "$dst/$d" + done + local depth=2 + [[ "$top" == "1" ]] && depth=1 + (cd "$src" && find . -mindepth $depth -type f ! -path './database/*' \ + ! -name 'wallet.dat' ! -name 'LOCK' ! -name '*.lock' ! -name '.lock' \ + ! -name 'LOG' ! -name 'LOG.old*' ! -name 'debug.log' ! -name '*.conf' ! -name '*.pid') | while read -r f; do + case "${f##*/}" in + *.ldb|*.sst|*.blob|blk*.dat|rev*.dat) ln "$src/$f" "$dst/$f" || return 1 ;; + *) cp -p "$src/$f" "$dst/$f" || return 1 ;; + esac + done +} + +function bb_status() { + curl -s -m 20 http://127.0.0.1:${BLOCKBOOK_PORT}/api +} + +function create() { + [[ "$DAEMON" == "1" && -f /run/bb/bootstrapped ]] || return 0 + # A snapshot pins files the databases have since replaced, so it is the + # first thing to give back when the disk fills up. + if [[ -d $SNAP && $(free_pct) -lt $((MIN_FREE / 2)) ]]; then + log "snapshot: only $(free_pct)% free, dropping the snapshot" + rm -rf $SNAP + fi + if ls /run/bb/serving.* > /dev/null 2>&1; then + return 0 + fi + if [[ -f $SNAP/info.json ]]; then + local created=$(jq -r .created $SNAP/info.json) + local jitter=$(( $(cksum <<< "$FLUX_NODE_HOST_IP" | cut -d' ' -f1) % 7200 )) + (( $(date +%s) - created < INTERVAL + jitter )) && return 0 + fi + local status=$(bb_status) + local insync=$(jq -r '.blockbook.inSync' <<< "$status" 2>/dev/null) + local initial=$(jq -r '.blockbook.initialSync // false' <<< "$status" 2>/dev/null) + local bbh=$(jq -r '.blockbook.bestHeight // 0' <<< "$status" 2>/dev/null) + local beh=$(jq -r '.backend.blocks // 0' <<< "$status" 2>/dev/null) + local hdr=$(jq -r '.backend.headers // .backend.blocks // 0' <<< "$status" 2>/dev/null) + if [[ "$insync" != "true" || "$initial" == "true" ]] || (( bbh < 1 || beh < hdr - 2 || bbh < beh - 2 )); then + return 0 + fi + rm -rf $SNAP ${SNAP}.new + if (( $(free_pct) < MIN_FREE )); then + log "snapshot: only $(free_pct)% free, not keeping a snapshot" + return 0 + fi + log "snapshot: synced at $bbh, taking a snapshot" + supervisorctl stop blockbook > /dev/null + supervisorctl stop daemon > /dev/null + local ok=1 + link_tree $BACKEND ${SNAP}.new/backend 0 && link_tree $BBDB ${SNAP}.new/blockbook-db 1 || ok=0 + supervisorctl start daemon > /dev/null + supervisorctl start blockbook > /dev/null + if [[ "$ok" != "1" ]]; then + log "snapshot: copy failed, dropped" + rm -rf ${SNAP}.new + return 1 + fi + jq -n --arg coin "$COIN" --arg app "$FLUX_APP_NAME" --arg image "$(cat /opt/blockbook/VERSION)" \ + --argjson created "$(date +%s)" --argjson height "$bbh" --argjson backend "$beh" \ + --argjson backend_bytes "$(bytes ${SNAP}.new/backend)" --argjson blockbook_bytes "$(bytes ${SNAP}.new/blockbook-db)" \ + '{coin: $coin, app: $app, image: $image, created: $created, height: $height, backend_height: $backend, + backend_bytes: $backend_bytes, blockbook_bytes: $blockbook_bytes, bytes: ($backend_bytes + $blockbook_bytes)}' \ + > ${SNAP}.new/info.json + mv ${SNAP}.new $SNAP + log "snapshot: ready, $(jq -r .bytes $SNAP/info.json) bytes at height $bbh" +} + +# Prints "ip:port bytes backend_bytes blockbook_bytes height" for each peer with +# a snapshot of this coin, best first; peers within 100 blocks of the best are +# shuffled so new instances do not all queue on the same one. +function peers() { + local spec port endpoints + if [[ -n "$SNAPSHOT_PEERS" ]]; then + # "ip:port ip:port": seed from these instead of the app's other instances. + endpoints=$SNAPSHOT_PEERS + else + spec=$(curl -sf -m 20 $API/apps/appspecifications/$FLUX_APP_NAME) || return 1 + port=${SNAPSHOT_PORT:-$(jq -r '(.data.compose // [.data]) | map(select(((.containerPorts // []) | map(tostring) | index("1337")) != null)) + | .[0] | .ports[((.containerPorts | map(tostring) | index("1337")))] // empty' <<< "$spec")} + [[ -n "$port" ]] || { log "bootstrap: the app spec maps no port to 1337, no peer snapshots"; return 2; } + endpoints=$(curl -sf -m 20 $API/apps/location/$FLUX_APP_NAME | jq -r '.data[].ip' | cut -d: -f1 | sort -u \ + | grep -vxF "$FLUX_NODE_HOST_IP" | sed "s/\$/:$port/") + fi + { + for endpoint in $endpoints; do + curl -sf -m 8 http://$endpoint/snapshot/info.json 2>/dev/null \ + | jq -r --arg p "$endpoint" --arg coin "$COIN" 'select(.coin == $coin) | "\($p) \(.bytes) \(.backend_bytes) \(.blockbook_bytes) \(.height)"' & + done + wait + } | sort -k5 -n -r \ + | awk -v seed=$RANDOM 'BEGIN { srand(seed) } NR == 1 { best = $5 } { print ($5 >= best - 100 ? rand() : 1 + NR), $0 }' \ + | sort -n | cut -d' ' -f2- +} + +# $1 = peer ip:port, $2 = path on the peer, $3 = members expected in the tar +function download() { + local peer=$1 path=$2 + shift 2 + rm -rf $TMP && mkdir -p $TMP + log "bootstrap: downloading http://$peer$path" + curl -sf --connect-timeout 15 --speed-limit 51200 --speed-time 600 http://$peer$path | tar -x -C $TMP + local rc=("${PIPESTATUS[@]}") + if [[ "${rc[0]}" != "0" || "${rc[1]}" != "0" ]]; then + log "bootstrap: download from $peer failed (curl ${rc[0]}, tar ${rc[1]})" + return 1 + fi + for m in "$@"; do + [[ -e $TMP/$m ]] || { log "bootstrap: $peer sent no $m"; return 1; } + done +} + +# $1=1 restores only the index; $2=1 replaces local data even if it is close. +function restore() { + local only_blockbook=$1 force=$2 + mkdir -p /run/bb $BACKEND $BBDB + [[ "$only_blockbook" == "1" || "$force" == "1" ]] || trap 'touch /run/bb/bootstrapped' EXIT + until [[ -f /run/bb/prepared ]]; do sleep 5; done + if [[ "$PEER_BOOTSTRAP" != "1" || "$DAEMON" != "1" || ( -z "$FLUX_APP_NAME" && -z "$SNAPSHOT_PEERS" ) ]]; then + return 0 + fi + local candidates rc attempts=1 + local local_backend=$(bytes $BACKEND) local_bb=$(bytes $BBDB) + # An empty instance waits a while for a peer to have a snapshot; one with a + # chain only checks whether it is far behind, so a restart is not delayed. + (( local_backend < 1000000000 )) && [[ "$only_blockbook" != "1" ]] && attempts=6 + for (( attempt = 1; attempt <= attempts; attempt++ )); do + candidates=$(peers); rc=$? + [[ -n "$candidates" || $rc == 2 ]] && break + log "bootstrap: no peer snapshot found (attempt $attempt of $attempts)" + (( attempt < attempts )) && sleep 300 + done + [[ -n "$candidates" ]] || { log "bootstrap: no peer snapshot, syncing on our own"; return 0; } + # Peers serve the download only to addresses that run the app, and a new + # instance is listed a few minutes after it starts. + if [[ -z "$SNAPSHOT_PEERS" && -n "$FLUX_NODE_HOST_IP" ]]; then + for _ in $(seq 1 30); do + curl -sf -m 20 $API/apps/location/$FLUX_APP_NAME | jq -e --arg ip "$FLUX_NODE_HOST_IP" \ + 'any(.data[]; (.ip | split(":")[0]) == $ip)' > /dev/null && break + sleep 30 + done + fi + + local tried=0 + while read -r peer total backend_bytes bb_bytes height; do + (( tried++ >= 3 )) && break + if [[ "$only_blockbook" == "1" ]]; then + (( $(free_bytes) > bb_bytes * 11 / 10 )) || { log "bootstrap: not enough disk for $bb_bytes bytes"; return 0; } + download $peer /snapshot-blockbook.tar blockbook-db/CURRENT || continue + rm -rf $BBDB && mv $TMP/blockbook-db $BBDB && rm -rf $TMP + log "bootstrap: index restored from $peer at height $height" + return 0 + fi + # Keep what is here unless it is far behind the peer. + if [[ "$force" != "1" ]] && (( local_backend * 2 >= backend_bytes && local_bb * 2 >= bb_bytes )); then + log "bootstrap: local data ($local_backend + $local_bb bytes) is close to $peer's snapshot, keeping it" + return 0 + fi + if [[ "$force" != "1" ]] && (( local_backend * 10 >= backend_bytes * 9 )); then + log "bootstrap: backend is synced but the index is far behind, taking only the index from $peer" + (( $(free_bytes) + local_bb > bb_bytes * 11 / 10 )) || { log "bootstrap: not enough disk"; return 0; } + rm -rf "${BBDB:?}"/* + download $peer /snapshot-blockbook.tar blockbook-db/CURRENT || continue + rm -rf $BBDB && mv $TMP/blockbook-db $BBDB && rm -rf $TMP + log "bootstrap: index restored from $peer at height $height" + return 0 + fi + (( $(free_bytes) + local_backend + local_bb > total * 11 / 10 )) || { log "bootstrap: not enough disk for $total bytes"; return 0; } + rm -rf "${BACKEND:?}"/* $BBDB/* + local_backend=0 local_bb=0 + download $peer /snapshot.tar backend blockbook-db/CURRENT || continue + # Only the chain data is replaced; configs, wallet and logs stay. + cp -al $TMP/backend/. $BACKEND/ && rm -rf $BBDB && mv $TMP/blockbook-db $BBDB && rm -rf $TMP + echo -e "Bootstrap [LOCKED] from peer $peer" > /root/BOOTSTRAP_LOCKED + log "bootstrap: restored from $peer at height $height" + return 0 + done <<< "$candidates" + rm -rf $TMP + log "bootstrap: every peer download failed, syncing on our own" +} + +# Hourly. An instance indexed below 90% of the best peer's snapshot (it came +# up while no peer had a snapshot yet, or was stuck) takes the snapshot rather +# than catching up block by block. +function reseed() { + [[ "$PEER_BOOTSTRAP" == "1" && "$DAEMON" == "1" && -f /run/bb/bootstrapped && -n "$FLUX_APP_NAME" ]] || return 0 + ls /run/bb/serving.* > /dev/null 2>&1 && return 0 + local status indexed best height + status=$(bb_status) + [[ -n "$status" ]] || return 0 + indexed=$(jq -r '.blockbook.bestHeight // 0' <<< "$status" 2>/dev/null) + best=$(peers | head -n 1) + [[ -n "$best" ]] || return 0 + height=$(awk '{ print $5 }' <<< "$best") + (( ${indexed:-0} * 10 < height * 9 )) || return 0 + log "reseed: indexed ${indexed:-0}, a peer has a snapshot at $height, reseeding" + supervisorctl stop blockbook daemon > /dev/null + restore 0 1 + supervisorctl start daemon blockbook > /dev/null +} + +case "$1" in + create) create ;; + restore) restore 0 0 ;; + restore-blockbook) restore 1 0 ;; + reseed) reseed ;; + *) echo "usage: $0 create|restore|restore-blockbook|reseed"; exit 1 ;; +esac diff --git a/snapshot_server.py b/snapshot_server.py new file mode 100755 index 0000000..e86fcb5 --- /dev/null +++ b/snapshot_server.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Serves this instance's peer snapshot (see snapshot.sh) on container port 1337. + +GET /snapshot/info.json what the snapshot holds, for anyone +GET /snapshot.tar backend + blockbook-db, streamed as a tar +GET /snapshot-blockbook.tar blockbook-db only + +The tar downloads are only for addresses that run the same Flux app (they are +tens to hundreds of GB of the node operator's bandwidth), and only a couple +at a time. +""" +import http.server +import json +import os +import shutil +import socketserver +import subprocess +import threading +import time +import urllib.request + +SNAP = '/root/snapshot' +APP = os.environ.get('FLUX_APP_NAME', '') +PORT = int(os.environ.get('SNAPSHOT_SERVER_PORT', '1337')) +PUBLIC = os.environ.get('SNAPSHOT_PUBLIC') == '1' +slots = threading.BoundedSemaphore(int(os.environ.get('SNAPSHOT_MAX_DOWNLOADS', '2'))) +_peers = {'at': 0.0, 'ips': set()} +_peers_lock = threading.Lock() + + +def app_ips(): + with _peers_lock: + if time.time() - _peers['at'] > 120: + try: + url = f'https://api.runonflux.io/apps/location/{APP}' + with urllib.request.urlopen(url, timeout=20) as response: + data = json.load(response)['data'] + _peers['ips'] = {entry['ip'].split(':')[0] for entry in data} + _peers['at'] = time.time() + except Exception as error: # keep the last list when the API is down + print(f'peer list refresh failed: {error}', flush=True) + return _peers['ips'] + + +class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + if self.path == '/snapshot/info.json': + return self.send_file(os.path.join(SNAP, 'info.json')) + if self.path == '/snapshot.tar': + return self.send_tar(['info.json', 'backend', 'blockbook-db']) + if self.path == '/snapshot-blockbook.tar': + return self.send_tar(['info.json', 'blockbook-db']) + self.send_error(404) + + def send_file(self, path): + try: + with open(path, 'rb') as f: + body = f.read() + except OSError: + return self.send_error(404) + self.send_response(200) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + + def send_tar(self, members): + client = self.client_address[0] + if not PUBLIC and client not in app_ips(): + return self.send_error(403, f'{client} does not run {APP}') + if not os.path.exists(os.path.join(SNAP, 'info.json')): + return self.send_error(404, 'no snapshot') + if not slots.acquire(blocking=False): + return self.send_error(503, 'busy, try another peer') + # snapshot.sh create does not replace a snapshot while this exists. + marker = f'/run/bb/serving.{threading.get_ident()}' + open(marker, 'w').close() + tar = None + try: + print(f'{client} downloading {self.path}', flush=True) + self.send_response(200) + self.send_header('Content-Type', 'application/x-tar') + self.end_headers() + tar = subprocess.Popen(['tar', '-C', SNAP, '-cf', '-', *members], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + shutil.copyfileobj(tar.stdout, self.wfile, 1 << 20) + tar.wait() + print(f'{client} finished {self.path}', flush=True) + except (BrokenPipeError, ConnectionResetError): + print(f'{client} dropped {self.path}', flush=True) + finally: + if tar and tar.poll() is None: + tar.kill() + os.remove(marker) + slots.release() + + def log_message(self, fmt, *args): + pass + + +class Server(socketserver.ThreadingMixIn, http.server.HTTPServer): + daemon_threads = True + allow_reuse_address = True + + +if __name__ == '__main__': + os.makedirs('/run/bb', exist_ok=True) + Server(('', PORT), Handler).serve_forever() diff --git a/supervisord.conf b/supervisord.conf index c8a4eef..4cea4ea 100644 --- a/supervisord.conf +++ b/supervisord.conf @@ -5,82 +5,83 @@ pidfile=/var/run/supervisord.pid nodaemon=true user=root +; build: lays out this coin's config files (blockbook itself is in the image). +; bootstrap: seeds an empty or far-behind instance from a synced peer of the +; same Flux app. daemon and blockbook wait for both before starting. +[program:build] +command=bash -c "/build.sh" +user=root +priority=1 +autostart=true +autorestart=false +startsecs=0 +stdout_logfile=/root/build.log +stdout_logfile_maxbytes=5MB +redirect_stderr=true + +[program:bootstrap] +command=bash -c "/snapshot.sh restore" +user=root +priority=2 +autostart=true +autorestart=false +startsecs=0 +stdout_logfile=/root/bootstrap.log +stdout_logfile_maxbytes=5MB +redirect_stderr=true + [program:daemon] command=bash -c "/daemon.sh" user=root stdout_logfile=/root/backend.log -stderr_logfile_maxbytes=30MB -stderr_logfile_backups=0 stdout_logfile_maxbytes=30MB stdout_logfile_backups=0 +redirect_stderr=true autostart=true autorestart=true stopasgroup=true -stopwaitsecs=120 +stopwaitsecs=300 startsecs=5 -startretries=3 +startretries=1000 -[program:db_corruption] -command=bash -c "sleep 300 && /corruption.sh" +[program:blockbook] +command=bash -c "/blockbook.sh" user=root -stderr_logfile_maxbytes=30MB -stderr_logfile_backups=0 +stopasgroup=true +stopwaitsecs=120 +stdout_logfile=/root/blockbook.log stdout_logfile_maxbytes=30MB stdout_logfile_backups=0 +redirect_stderr=true autostart=true -autorestart=false - -[program:backup_share] -command=bash -c "/utils.sh backup_share" -user=root -stderr_logfile_maxbytes=30MB -stderr_logfile_backups=0 -stdout_logfile_maxbytes=30MB -stdout_logfile_backups=0 -autostart=false -autorestart=false -stopasgroup=true +autorestart=true startsecs=5 +startretries=1000 [program:consensus] command=bash -c "/consensus.sh" user=root -stderr_logfile_maxbytes=30MB -stderr_logfile_backups=0 stdout_logfile_maxbytes=30MB stdout_logfile_backups=0 autostart=true -autorestart=true -startsecs=70 -startretries=3 - -[program:build] -command=bash -c "/build.sh" -user=root -autostart=true -autorestart=false +autorestart=unexpected +exitcodes=0 +startsecs=0 -[program:blockbook] -command=bash -c "/blockbook.sh" +[program:snapshot_server] +command=python3 /snapshot_server.py user=root -stopasgroup=true -stopwaitsecs=120 -stdout_logfile_maxbytes=30MB +stdout_logfile=/root/snapshot_server.log +stdout_logfile_maxbytes=5MB stdout_logfile_backups=0 -stderr_logfile=/root/blockbook.log -stderr_logfile_maxbytes=30MB -stderr_logfile_backups=0 +redirect_stderr=true autostart=true autorestart=true -logfile_maxbytes=20MB -startsecs=5 [program:crond] -command=bash -c "printenv > /etc/environment && /usr/sbin/cron -f" +command=bash -c "printenv | grep -v '^_=' > /etc/environment && /usr/sbin/cron -f" user=root -stderr_logfile_maxbytes=30MB -stderr_logfile_backups=0 -stdout_logfile_maxbytes=30MB +stdout_logfile_maxbytes=1MB stdout_logfile_backups=0 autostart=true autorestart=true diff --git a/test/smoke.sh b/test/smoke.sh new file mode 100755 index 0000000..9bf2d10 --- /dev/null +++ b/test/smoke.sh @@ -0,0 +1,131 @@ +#!/usr/bin/env bash +# End-to-end test of an image on a private regtest chain: +# 1. instance A starts bitcoind + blockbook, mines 150 blocks, indexes them +# 2. A takes a peer snapshot and serves it on port 1337 +# 3. instance B, with an empty volume, seeds from A and starts at height 150 +# 4. A's chain is marked invalid, heal.sh brings it back +# 5. instance P runs a pruned backend and gets pruned blocks again from A +# plus start-up checks for the daemons that broke in production. +# +# test/smoke.sh +set -euo pipefail +IMAGE=$1 +NET=bbtest +COIN=bitcoin_regtest +CONF=/root/$COIN/$COIN.conf + +cleanup() { + for c in bb-a bb-b bb-p bb-bcash bb-flux; do + echo "::group::logs $c"; docker exec $c bash -c 'tail -n 40 /root/*.log' 2>/dev/null || true; echo "::endgroup::" + done + docker rm -f bb-a bb-b bb-p bb-bcash bb-flux > /dev/null 2>&1 || true + docker network rm $NET > /dev/null 2>&1 || true +} +trap cleanup EXIT + +wait_for() { # seconds description command... + local t=$1 what=$2; shift 2 + for _ in $(seq 1 "$t"); do + if "$@" > /dev/null 2>&1; then echo "ok: $what"; return 0; fi + sleep 1 + done + echo "FAILED: $what"; return 1 +} +# set -e ignores a failing "! cmd", so negative checks go through this. +refute() { if "$@" > /dev/null 2>&1; then echo "FAILED: expected to fail: $*"; exit 1; fi; } +api() { docker exec "$1" curl -sf http://127.0.0.1:19121/api; } +height_is() { [[ "$(api "$1" | jq -r .blockbook.bestHeight)" == "$2" ]]; } +cli() { local c=$1; shift; docker exec "$c" bitcoin-cli -conf=$CONF -rpcuser=rpc -rpcpassword=rpc "$@"; } + +docker network create $NET > /dev/null +run() { # name extra-args... + local name=$1; shift + docker run -d --name "$name" --network $NET -e COIN=$COIN -e BLOCKBOOK_PORT=19121 "$@" "$IMAGE" > /dev/null +} + +run bb-a -e SNAPSHOT_PUBLIC=1 -e PEER_BOOTSTRAP=0 -e HEAL_MIN_LEAD=5 -e EXTRACONFIG=listen=1 +wait_for 300 "A: bitcoind answers" cli bb-a getblockcount +cli bb-a generatetodescriptor 150 'raw(51)' > /dev/null +wait_for 300 "A: blockbook indexed 150 blocks" height_is bb-a 150 +[[ "$(api bb-a | jq -r .blockbook.inSync)" == "true" ]] +docker exec bb-a cat /opt/blockbook/VERSION + +docker exec bb-a bash -c '. /run/bb/env.sh; /snapshot.sh create' +docker exec bb-a cat /root/snapshot/info.json | jq -e '.height == 150 and .bytes > 0' +wait_for 120 "A: blockbook back after the snapshot" height_is bb-a 150 +docker exec bb-a test ! -e /root/snapshot/backend/wallet.dat +docker exec bb-a bash -c "test -z \"\$(find /root/snapshot -name '*.conf')\"" + +A_IP=$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NET\").IPAddress}}" bb-a) +run bb-b -e PEER_BOOTSTRAP=1 -e SNAPSHOT_PEERS="$A_IP:1337" +wait_for 300 "B: seeded from A and serving height 150" height_is bb-b 150 +docker exec bb-b grep -q "restored from $A_IP" /root/bootstrap.log +[[ "$(cli bb-b getblockcount)" == "150" ]] + +TIP=$(cli bb-a getblockhash 140) +cli bb-a invalidateblock "$TIP" +[[ "$(cli bb-a getblockcount)" == "139" ]] +docker exec bb-a bash -c '. /run/bb/env.sh; /heal.sh' +wait_for 60 "A: heal.sh reconsidered the invalid chain" bash -c "[[ \$(docker exec bb-a bitcoin-cli -conf=$CONF -rpcuser=rpc -rpcpassword=rpc getblockcount) == 150 ]]" + +# Pruned backend: no txindex and manual pruning. Blockbook gets a confirmed +# transaction from its block and downloads a pruned block again from a peer +# (A keeps every block), or with no peer answers from its index (patches/0001). +# fastprune makes regtest block files small enough to be pruned. +# -extendedindex stands in for bitcoin.json's, which PRUNE_BACKEND must drop. +run bb-p -e PEER_BOOTSTRAP=0 -e PRUNE_BACKEND=1 -e PRUNE_KEEP_BLOCKS=10 -e BLOCKBOOK_PARAMS=-extendedindex \ + -e EXTRACONFIG="fastprune=1\naddnode=$A_IP:18444" +wait_for 300 "P: bitcoind answers" cli bb-p getblockcount +docker exec bb-p grep -q '^prune=1' $CONF +refute docker exec bb-p grep -q '^txindex' $CONF +wait_for 120 "P: blockbook running" docker exec bb-p pgrep -x blockbook +P_ARGS=$(docker exec bb-p bash -c 'tr "\0" " " < /proc/$(pgrep -x blockbook)/cmdline') +[[ "$P_ARGS" == *-prunedbackend* && "$P_ARGS" == *-txcachemaxgb=20* && "$P_ARGS" != *-extendedindex* && "$P_ARGS" != *-notxcache* ]] || { echo "FAILED: pruned blockbook args: $P_ARGS"; exit 1; } +wait_for 300 "P: synced A's 150 blocks" bash -c "[[ \$(docker exec bb-p bitcoin-cli -conf=$CONF -rpcuser=rpc -rpcpassword=rpc getblockcount) == 150 ]]" +# Two coinbases to an address, then enough blocks for the first files to be pruned +ADDR=$(cli bb-p deriveaddresses "$(cli bb-p getdescriptorinfo 'wpkh(0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798)' | jq -r .descriptor)" | jq -r '.[0]') +cli bb-p generatetoaddress 2 "$ADDR" > /dev/null +cli bb-p generatetodescriptor 850 'raw(51)' > /dev/null +wait_for 300 "P: blockbook indexed 1002 blocks" height_is bb-p 1002 +TX5=$(cli bb-p getblock "$(cli bb-p getblockhash 5)" | jq -r '.tx[0]') +TX6=$(cli bb-p getblock "$(cli bb-p getblockhash 6)" | jq -r '.tx[0]') +docker exec bb-p bash -c '. /run/bb/env.sh; /prune.sh' +cli bb-p getblockchaininfo | jq -e '.pruned == true and .pruneheight > 152' +refute cli bb-p getblock "$(cli bb-p getblockhash 151)" +refute cli bb-p getrawtransaction "$TX5" +P_API=http://127.0.0.1:19121/api/v2 +# A history page of pruned blocks, a transaction, its backend JSON and a block +# all come back complete, the blocks downloaded from A again. +docker exec bb-p curl -sf "$P_API/address/$ADDR?details=txs" | jq -e '.txs == 2 and ([.transactions[] | select(.hex != null and .vsize > 0 and .vin[0].coinbase != null)] | length) == 2' +cli bb-p getblock "$(cli bb-p getblockhash 151)" > /dev/null +docker exec bb-p curl -sf "$P_API/tx/$TX5" | jq -e '.blockHeight == 5 and .hex != null and .vsize > 0' +docker exec bb-p curl -sf "$P_API/tx-specific/$TX5" | jq -e '.vsize > 0 and .blockhash != null' +docker exec bb-p curl -sf "$P_API/block/7" | jq -e '.height == 7 and .txCount == 1' +# With no peer an old transaction comes from the index, fee rate included. +cli bb-p addnode "$A_IP:18444" remove +cli bb-p disconnectnode "$A_IP:18444" +wait_for 60 "P: no peers" bash -c "[[ \$(docker exec bb-p bitcoin-cli -conf=$CONF -rpcuser=rpc -rpcpassword=rpc getconnectioncount) == 0 ]]" +docker exec bb-p curl -sf "$P_API/tx/$TX6" | jq -e '.blockHeight == 6 and .vsize > 0 and .hex == null' +# An index blockbook refuses to open is wiped. With no peer snapshot to restore +# it from and the old blocks pruned, the backend starts over too, and both get +# the chain from A again (the addnode is in the config). +P_OUT=$(docker exec bb-p bash -c 'echo "Coins do not match. DB coin Testnet, RPC coin Testnet4" >> /root/blockbook.log; . /run/bb/env.sh; /corruption.sh') +echo "$P_OUT" +[[ "$P_OUT" == *"starting the backend over too"* ]] || { echo "FAILED: the pruned backend was not started over"; exit 1; } +wait_for 600 "P: backend and index rebuilt from A" height_is bb-p 1002 + +# Bitcoin Cash Node 29 needs glibc 2.34; on the old Debian 11 image it exited at once. +docker run -d --name bb-bcash --network $NET -e COIN=bcash -e BLOCKBOOK_PORT=9131 -e PEER_BOOTSTRAP=0 "$IMAGE" > /dev/null +wait_for 600 "bcash: bitcoind running" docker exec bb-bcash pgrep -x bitcoind +sleep 30 +docker exec bb-bcash pgrep -x bitcoind > /dev/null +refute docker exec bb-bcash grep -q GLIBC /root/backend.log +docker exec bb-bcash jq -r .daemon_url /root/daemon_config.json | grep -q 29.2.0 + +# Flux gets fluxd from overrides.json, not the version upstream pins. +docker run -d --name bb-flux --network $NET -e COIN=flux -e BLOCKBOOK_PORT=9158 -e PEER_BOOTSTRAP=0 "$IMAGE" > /dev/null +wait_for 600 "flux: fluxd installed" docker exec bb-flux test -x /usr/local/bin/fluxd +docker exec bb-flux jq -r .daemon_url /root/daemon_config.json | grep -q v9.1.0 + +docker run --rm --entrypoint zebrad "$IMAGE" --version +echo "smoke test passed" diff --git a/utils.sh b/utils.sh index e8aa43e..fc7c3fe 100644 --- a/utils.sh +++ b/utils.sh @@ -362,7 +362,7 @@ if [[ "$1" == "backup_share" ]]; then if [[ -d /root/backup_archive ]]; then echo -n "| " cd /root/backup_archive - python3 -m http.server 1337 + python3 -m http.server ${SHARE_PORT:-1338} else echo -e "Backup directory not exist, operation aborted..." fi @@ -409,14 +409,14 @@ if [[ "$1" == "log_clean" ]]; then echo -e "| LOG CLEANER v2.0 [$(date '+%Y-%m-%d %H:%M:%S')]" echo -e "--------------------------------------------------" LOG_SIZE_LIMIT=${LOG_SIZE_LIMIT:-20} - LOG_LIST=($(find /root -type f \( -name "$COIN*.log" -o -name "debug.log" -o -name "blockbook.log*" -o -name "*.log" \))) + # Named log files only. A "*.log" search also matched the write-ahead logs of + # LevelDB (chainstate, block index) and RocksDB (blockbook-db), and emptying + # those corrupts the database ("SST file is ahead of WALs"). + LOG_LIST=($(ls /root/*.log /root/$CONFIG_DIR/backend/debug.log /root/$CONFIG_DIR/backend/db.log /root/$CONFIG_DIR/backend/zebra.log 2>/dev/null)) LENGTH=${#LOG_LIST[@]} for (( j=0; j<${LENGTH}; j++ )); do LOG_PATH="${LOG_LIST[$j]}" - if [[ $(egrep "blocks" <<< $LOG_PATH) != "" ]]; then - continue - fi SIZE=$(ls -l --b=M $LOG_PATH | cut -d " " -f5) #echo -e "| File: ${LOG_PATH} SIZE: ${SIZE}" if [[ $(egrep -o '[0-9]+' <<< $SIZE) -gt $LOG_SIZE_LIMIT ]]; then From f7f16a5e843f62286c05f045a6b6e0ad524853e4 Mon Sep 17 00:00:00 2001 From: TheTrunk Date: Wed, 21 Oct 2026 16:43:04 +0800 Subject: [PATCH 02/15] Run on Debian 13: zebrad 6.4.2 needs glibc 2.39 --- Dockerfile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index a8f7b34..6cf3d93 100644 --- a/Dockerfile +++ b/Dockerfile @@ -77,7 +77,9 @@ RUN for coin in $(jq -r 'keys[]' /tmp/overrides.json); do \ cp -r static /out/static && \ echo "blockbook $(jq -r .version configs/environ.json) $(git rev-parse --short HEAD)" > /out/VERSION -FROM debian:12-slim +# zebrad (copied from zfnd/zebra, built on Debian 13) needs glibc 2.39 and +# CXXABI_1.3.15; blockbook built on Debian 12 runs on the newer glibc too. +FROM debian:13-slim # Links the ghcr.io package to this repository. LABEL org.opencontainers.image.source=https://github.com/RunOnFlux/blockbook-docker ENV DEBIAN_FRONTEND=noninteractive From a90825f92570ef1db96b8519714ee688bd428768 Mon Sep 17 00:00:00 2001 From: TheTrunk Date: Wed, 21 Oct 2026 17:23:22 +0800 Subject: [PATCH 03/15] Install python3 in the build stage: bitcoind configs lacked their rpcauth line --- Dockerfile | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Dockerfile b/Dockerfile index 6cf3d93..c69c0c7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -51,6 +51,11 @@ RUN VERSION=$(jq -r .version configs/environ.json) && \ -X github.com/trezor/blockbook/common.gitcommit=$(git rev-parse --short HEAD) \ -X github.com/trezor/blockbook/common.buildtime=$(date --iso-8601=seconds)" +# The config generator writes bitcoind's rpcauth line with +# build/scripts/rpcauth.py; without python3 it silently leaves the line out +# and the daemon refuses every RPC login. +RUN apt-get update && apt-get install -y --no-install-recommends python3 && rm -rf /var/lib/apt/lists/* + # Coin overrides (daemon versions we need ahead of upstream), then every coin's # blockchaincfg.json and backend server.conf rendered with the container's # paths, so nothing has to be compiled or fetched from GitHub at run time. @@ -73,6 +78,7 @@ RUN for coin in $(jq -r 'keys[]' /tmp/overrides.json); do \ echo "coins rendered: $(ls /out/pkg | wc -l)" && \ test -f /out/pkg/flux/blockchaincfg.json && test -f /out/pkg/zcash/server.conf && \ grep -q 'cache_dir = "/root/zcash/backend/zebra"' /out/pkg/zcash/server.conf && \ + grep -q '^rpcauth=rpc:' /out/pkg/bitcoin/server.conf && grep -q '^rpcauth=rpc:' /out/pkg/bitcoin_regtest/server.conf && \ mkdir -p /out/configs && cp -r configs/coins /out/configs/ && cp configs/environ.json /out/configs/ && \ cp -r static /out/static && \ echo "blockbook $(jq -r .version configs/environ.json) $(git rev-parse --short HEAD)" > /out/VERSION From 2c0a76d96132f49f598b6bbe8e62bf4b265d2960 Mon Sep 17 00:00:00 2001 From: TheTrunk Date: Wed, 21 Oct 2026 17:39:02 +0800 Subject: [PATCH 04/15] Build on Debian 13 like the runtime; health check logs in with blockbook's RPC credentials --- Dockerfile | 6 ++++-- check-health.sh | 21 +++++++++++---------- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/Dockerfile b/Dockerfile index c69c0c7..b7c35d3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -9,7 +9,9 @@ ARG ZEBRA_VERSION=6.4.2 FROM zfnd/zebra:${ZEBRA_VERSION} AS zebra -FROM debian:12 AS build +# Same Debian as the runtime stage: zmq4 refuses to start when the libzmq it +# was built against differs from the one it runs with (4.3.4 vs 4.3.5). +FROM debian:13 AS build SHELL ["/bin/bash", "-o", "pipefail", "-c"] ARG BLOCKBOOK_REPO=https://github.com/trezor/blockbook.git ARG BLOCKBOOK_COMMIT=3e6a90a287fb4e6d597978baf0aceeec985b5e41 @@ -84,7 +86,7 @@ RUN for coin in $(jq -r 'keys[]' /tmp/overrides.json); do \ echo "blockbook $(jq -r .version configs/environ.json) $(git rev-parse --short HEAD)" > /out/VERSION # zebrad (copied from zfnd/zebra, built on Debian 13) needs glibc 2.39 and -# CXXABI_1.3.15; blockbook built on Debian 12 runs on the newer glibc too. +# CXXABI_1.3.15. FROM debian:13-slim # Links the ghcr.io package to this repository. LABEL org.opencontainers.image.source=https://github.com/RunOnFlux/blockbook-docker diff --git a/check-health.sh b/check-health.sh index 6d49cd5..e078752 100644 --- a/check-health.sh +++ b/check-health.sh @@ -32,19 +32,20 @@ exit 1 fi ## Checking Daemon + # Credentials from blockchaincfg.json: several backend configs only carry a + # hashed rpcauth line, which a CLI cannot log in with. + RPC_USER=$(jq -r ".rpc_user // \"$RPC_USER\"" /root/blockchaincfg.json 2>/dev/null || echo "$RPC_USER") + RPC_PASS=$(jq -r ".rpc_pass // \"$RPC_PASS\"" /root/blockchaincfg.json 2>/dev/null || echo "$RPC_PASS") + CLI_ARGS=(-rpcuser="$RPC_USER" -rpcpassword="$RPC_PASS") if [[ -f /root/${CONFIG_DIR}/${CONFIG_FILE}.conf ]]; then - CURRENT_NODE_HEIGHT=$(${CLI_NAME} -conf="/root/${CONFIG_DIR}/${CONFIG_FILE}.conf" -getinfo 2>/dev/null | jq .blocks) - if [[ "$CURRENT_NODE_HEIGHT" == "" ]]; then - CURRENT_NODE_HEIGHT=$(${CLI_NAME} -conf="/root/${CONFIG_DIR}/${CONFIG_FILE}.conf" getinfo 2>/dev/null | jq .blocks) - fi - else - CURRENT_NODE_HEIGHT=$(${CLI_NAME} -rpcpassword="$RPC_PASS" -rpcuser="$RPC_USER" -getinfo 2>/dev/null | jq .blocks) - if [[ "$CURRENT_NODE_HEIGHT" == "" ]]; then - CURRENT_NODE_HEIGHT=$(${CLI_NAME} -rpcpassword="$RPC_PASS" -rpcuser="$RPC_USER" getinfo 2>/dev/null | jq .blocks) - fi + CLI_ARGS+=(-conf="/root/${CONFIG_DIR}/${CONFIG_FILE}.conf") + fi + CURRENT_NODE_HEIGHT=$(${CLI_NAME} "${CLI_ARGS[@]}" -getinfo 2>/dev/null | jq .blocks) + if [[ "$CURRENT_NODE_HEIGHT" == "" ]]; then + CURRENT_NODE_HEIGHT=$(${CLI_NAME} "${CLI_ARGS[@]}" getinfo 2>/dev/null | jq .blocks) fi - if ! egrep -o "^[0-9]+$" <<< "$CURRENT_NODE_HEIGHT" &>/dev/null; then + if ! grep -Eq "^[0-9]+$" <<< "$CURRENT_NODE_HEIGHT"; then msg="$msg, Daemon = [FAILED]" echo -e "$msg" exit 1 From 0d94f7c459f9fb65d68820725ff0b9a00eb9bbfd Mon Sep 17 00:00:00 2001 From: TheTrunk Date: Wed, 21 Oct 2026 18:07:50 +0800 Subject: [PATCH 05/15] Call blockbook's status page as /api/: /api is a redirect --- prune.sh | 2 +- snapshot.sh | 2 +- test/smoke.sh | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/prune.sh b/prune.sh index 2fc0902..e7cd43e 100755 --- a/prune.sh +++ b/prune.sh @@ -24,7 +24,7 @@ function cli() { -rpcuser="$(jq -r .rpc_user /root/blockchaincfg.json)" -rpcpassword="$(jq -r .rpc_pass /root/blockchaincfg.json)" "$@" } -INDEXED=$(curl -s -m 20 http://127.0.0.1:${BLOCKBOOK_PORT}/api | jq -r '.blockbook.bestHeight // 0' 2>/dev/null) +INDEXED=$(curl -s -m 20 http://127.0.0.1:${BLOCKBOOK_PORT}/api/ | jq -r '.blockbook.bestHeight // 0' 2>/dev/null) INDEXED=${INDEXED:-0} if (( INDEXED > KEEP + 288 )); then cli pruneblockchain $((INDEXED - KEEP)) > /dev/null 2>&1 diff --git a/snapshot.sh b/snapshot.sh index 7c8f76c..849aa0e 100755 --- a/snapshot.sh +++ b/snapshot.sh @@ -54,7 +54,7 @@ function link_tree() { } function bb_status() { - curl -s -m 20 http://127.0.0.1:${BLOCKBOOK_PORT}/api + curl -s -m 20 http://127.0.0.1:${BLOCKBOOK_PORT}/api/ } function create() { diff --git a/test/smoke.sh b/test/smoke.sh index 9bf2d10..25e184f 100755 --- a/test/smoke.sh +++ b/test/smoke.sh @@ -33,7 +33,7 @@ wait_for() { # seconds description command... } # set -e ignores a failing "! cmd", so negative checks go through this. refute() { if "$@" > /dev/null 2>&1; then echo "FAILED: expected to fail: $*"; exit 1; fi; } -api() { docker exec "$1" curl -sf http://127.0.0.1:19121/api; } +api() { docker exec "$1" curl -sf http://127.0.0.1:19121/api/; } height_is() { [[ "$(api "$1" | jq -r .blockbook.bestHeight)" == "$2" ]]; } cli() { local c=$1; shift; docker exec "$c" bitcoin-cli -conf=$CONF -rpcuser=rpc -rpcpassword=rpc "$@"; } From 797427a36846b48c8bd067c2c2416376c1ec1583 Mon Sep 17 00:00:00 2001 From: TheTrunk Date: Wed, 21 Oct 2026 18:30:36 +0800 Subject: [PATCH 06/15] Add libatomic1: Bitcoin Cash Node 29 links it --- Dockerfile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index b7c35d3..bafa71c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -91,9 +91,11 @@ FROM debian:13-slim # Links the ghcr.io package to this repository. LABEL org.opencontainers.image.source=https://github.com/RunOnFlux/blockbook-docker ENV DEBIAN_FRONTEND=noninteractive +# The daemons downloaded at start need only glibc (2.34 at most), libgcc_s, +# libstdc++ (fluxd) and libatomic (Bitcoin Cash Node 29), checked 2026-10-21. RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates curl wget jq bc supervisor cron procps pv libarchive-tools unzip xz-utils \ - python3 libsnappy1v5 libzstd1 liblz4-1 libbz2-1.0 zlib1g libzmq5 libgflags2.2 libstdc++6 && \ + python3 libsnappy1v5 libzstd1 liblz4-1 libbz2-1.0 zlib1g libzmq5 libgflags2.2 libstdc++6 libatomic1 && \ rm -rf /var/lib/apt/lists/* COPY --from=build /out/blockbook /opt/blockbook/blockbook From f05230b048e09d4e0fbc62dfe69cd5b84e8ab649 Mon Sep 17 00:00:00 2001 From: TheTrunk Date: Wed, 21 Oct 2026 20:05:02 +0800 Subject: [PATCH 07/15] Wait for the daemon by command line: bitcoind renames itself while it flushes --- daemon.sh | 21 +++++++++++++++++---- snapshot.sh | 20 +++++++++++++++++++- test/smoke.sh | 6 ++++++ 3 files changed, 42 insertions(+), 5 deletions(-) diff --git a/daemon.sh b/daemon.sh index 5a5a8e6..fbf2360 100644 --- a/daemon.sh +++ b/daemon.sh @@ -174,11 +174,24 @@ function cdn_speedtest() { echo -e "| Best server: $DOWNLOAD_URL" } +# The daemon is found by its command line: while it shuts down it renames its +# main thread (bitcoind becomes "b-shutoff"), and a wait on the process name +# returned while it was still flushing its databases. A snapshot or a wipe +# that followed then caught them half written. +function daemon_pattern() { + echo "^([^ ]*/)?${BINARY_NAME}( |$)" +} + +function stop_daemon() { + pkill -TERM -f "$(daemon_pattern)" + for i in $(seq 1 280); do pgrep -f "$(daemon_pattern)" > /dev/null || return 0; sleep 1; done + pkill -9 -f "$(daemon_pattern)" +} + stop_script() { echo -e "| Stopping daemon (EXIT)..." if [[ "$BINARY_NAME" != "" ]]; then - pkill -TERM -x "$BINARY_NAME" - for i in $(seq 1 280); do pgrep -x "$BINARY_NAME" > /dev/null || break; sleep 1; done + stop_daemon fi exit 0 } @@ -255,9 +268,9 @@ if [[ "$BOOTSTRAP" == "1" && ! -f /root/BOOTSTRAP_LOCKED ]]; then fi touch /run/bb/daemon_bootstrap_done -if [[ "$BINARY_NAME" != "" ]]; then +if [[ "$BINARY_NAME" != "" ]] && pgrep -f "$(daemon_pattern)" > /dev/null; then echo -e "| Stopping daemon (START)..." - pkill -9 -x "$BINARY_NAME" + stop_daemon fi if [[ ! -f /root/blockbook.json ]]; then diff --git a/snapshot.sh b/snapshot.sh index 849aa0e..c32921d 100755 --- a/snapshot.sh +++ b/snapshot.sh @@ -53,6 +53,19 @@ function link_tree() { done } +# supervisorctl returns once the launcher has exited. Make sure the daemon has +# too: a copy taken while it still flushes has empty databases. +function daemon_stopped() { + local name + name=$(jq -r '.binary_name // empty' /root/daemon_config.json 2>/dev/null) + [[ -n "$name" ]] || return 0 + for _ in $(seq 1 300); do + pgrep -f "^([^ ]*/)?${name}( |$)" > /dev/null || return 0 + sleep 1 + done + return 1 +} + function bb_status() { curl -s -m 20 http://127.0.0.1:${BLOCKBOOK_PORT}/api/ } @@ -91,7 +104,11 @@ function create() { supervisorctl stop blockbook > /dev/null supervisorctl stop daemon > /dev/null local ok=1 - link_tree $BACKEND ${SNAP}.new/backend 0 && link_tree $BBDB ${SNAP}.new/blockbook-db 1 || ok=0 + if ! daemon_stopped; then + log "snapshot: the daemon did not stop" + ok=0 + fi + [[ "$ok" == "1" ]] && link_tree $BACKEND ${SNAP}.new/backend 0 && link_tree $BBDB ${SNAP}.new/blockbook-db 1 || ok=0 supervisorctl start daemon > /dev/null supervisorctl start blockbook > /dev/null if [[ "$ok" != "1" ]]; then @@ -238,6 +255,7 @@ function reseed() { (( ${indexed:-0} * 10 < height * 9 )) || return 0 log "reseed: indexed ${indexed:-0}, a peer has a snapshot at $height, reseeding" supervisorctl stop blockbook daemon > /dev/null + daemon_stopped || { log "reseed: the daemon did not stop"; supervisorctl start daemon blockbook > /dev/null; return 1; } restore 0 1 supervisorctl start daemon blockbook > /dev/null } diff --git a/test/smoke.sh b/test/smoke.sh index 25e184f..cbc0081 100755 --- a/test/smoke.sh +++ b/test/smoke.sh @@ -62,6 +62,12 @@ wait_for 300 "B: seeded from A and serving height 150" height_is bb-b 150 docker exec bb-b grep -q "restored from $A_IP" /root/bootstrap.log [[ "$(cli bb-b getblockcount)" == "150" ]] +# supervisorctl stop returns only once the daemon has exited: bitcoind renames +# itself b-shutoff while it flushes, and a wait on its name returned too early. +docker exec bb-a bash -c 'supervisorctl stop daemon > /dev/null; ! pgrep -f "^([^ ]*/)?bitcoind( |$)"' +docker exec bb-a supervisorctl start daemon > /dev/null +wait_for 120 "A: bitcoind back after a stop" cli bb-a getblockcount + TIP=$(cli bb-a getblockhash 140) cli bb-a invalidateblock "$TIP" [[ "$(cli bb-a getblockcount)" == "139" ]] From 7b39d828ca938df773e2e625420103049a1748bc Mon Sep 17 00:00:00 2001 From: TheTrunk Date: Wed, 21 Oct 2026 21:59:20 +0800 Subject: [PATCH 08/15] Smoke test: print what a failed check saw --- test/smoke.sh | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/test/smoke.sh b/test/smoke.sh index cbc0081..e056158 100755 --- a/test/smoke.sh +++ b/test/smoke.sh @@ -16,7 +16,9 @@ CONF=/root/$COIN/$COIN.conf cleanup() { for c in bb-a bb-b bb-p bb-bcash bb-flux; do - echo "::group::logs $c"; docker exec $c bash -c 'tail -n 40 /root/*.log' 2>/dev/null || true; echo "::endgroup::" + echo "::group::logs $c" + docker exec $c bash -c 'supervisorctl status; ps -eo pid,etime,args | cut -c1-200; tail -n 80 /root/*.log' 2>/dev/null || true + echo "::endgroup::" done docker rm -f bb-a bb-b bb-p bb-bcash bb-flux > /dev/null 2>&1 || true docker network rm $NET > /dev/null 2>&1 || true @@ -24,17 +26,20 @@ cleanup() { trap cleanup EXIT wait_for() { # seconds description command... - local t=$1 what=$2; shift 2 + local t=$1 what=$2 out=; shift 2 for _ in $(seq 1 "$t"); do - if "$@" > /dev/null 2>&1; then echo "ok: $what"; return 0; fi + if out=$("$@" 2>&1); then echo "ok: $what"; return 0; fi sleep 1 done - echo "FAILED: $what"; return 1 + echo "FAILED: $what"; echo "last attempt: ${out:0:1000}"; return 1 } # set -e ignores a failing "! cmd", so negative checks go through this. refute() { if "$@" > /dev/null 2>&1; then echo "FAILED: expected to fail: $*"; exit 1; fi; } -api() { docker exec "$1" curl -sf http://127.0.0.1:19121/api/; } -height_is() { [[ "$(api "$1" | jq -r .blockbook.bestHeight)" == "$2" ]]; } +api() { docker exec "$1" curl -sSf -m 20 http://127.0.0.1:19121/api/; } +height_is() { + local s; s=$(api "$1") || return 1 + [[ "$(jq -r .blockbook.bestHeight <<< "$s")" == "$2" ]] || { jq -c '{blockbook: .blockbook | {bestHeight, inSync, initialSync}, backend: .backend | {blocks, error}}' <<< "$s"; return 1; } +} cli() { local c=$1; shift; docker exec "$c" bitcoin-cli -conf=$CONF -rpcuser=rpc -rpcpassword=rpc "$@"; } docker network create $NET > /dev/null From 08ad8ef0cb88b78a368a70e32c7298a8d5502579 Mon Sep 17 00:00:00 2001 From: TheTrunk Date: Tue, 27 Oct 2026 17:40:29 +0800 Subject: [PATCH 09/15] Build from ZelCore-io/blockbook (new explorer UI); Blockbook stops cleanly: close the ZMQ socket on its own thread, re-read the height after an unclean stop --- Dockerfile | 12 ++- README.md | 11 +- patches/0002-clean-shutdown.patch | 165 ++++++++++++++++++++++++++++++ test/smoke.sh | 8 ++ 4 files changed, 189 insertions(+), 7 deletions(-) create mode 100644 patches/0002-clean-shutdown.patch diff --git a/Dockerfile b/Dockerfile index bafa71c..4323443 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,8 +13,9 @@ FROM zfnd/zebra:${ZEBRA_VERSION} AS zebra # was built against differs from the one it runs with (4.3.4 vs 4.3.5). FROM debian:13 AS build SHELL ["/bin/bash", "-o", "pipefail", "-c"] -ARG BLOCKBOOK_REPO=https://github.com/trezor/blockbook.git -ARG BLOCKBOOK_COMMIT=3e6a90a287fb4e6d597978baf0aceeec985b5e41 +# Zelcore's fork of trezor/blockbook: the Flux/Zelcore explorer UI and an optional Insight API +ARG BLOCKBOOK_REPO=https://github.com/ZelCore-io/blockbook.git +ARG BLOCKBOOK_COMMIT=423f085a181435450a55f4ea30a20adb7ba9269d ARG GOLANG_VERSION=go1.25.4 ARG GOLANG_SHA256=9fa5ffeda4170de60f67f3aa0f824e426421ba724c21e133c1e35d6159ca1bec ARG ROCKSDB_VERSION=v9.10.0 @@ -41,8 +42,9 @@ WORKDIR /src/blockbook COPY patches /tmp/patches RUN for p in /tmp/patches/*.patch; do git apply --verbose "$p" || exit 1; done RUN go mod download -# patches/0001 against a fake pruned bitcoind -RUN go test -count=1 -run 'Pruned' ./bchain/coins/btc/ +# patches/0001 against a fake pruned bitcoind, patches/0002 against a zmq publisher +RUN go test -count=1 -run 'Pruned' ./bchain/coins/btc/ && go test -count=1 -run 'MQShutdown' ./bchain/ && \ + go test -count=1 ./explorercontent/ ./static/templates/ ENV CGO_CFLAGS="-I/opt/rocksdb/include -O -D__BLST_PORTABLE__" \ CGO_CFLAGS_ALLOW="-O -D__BLST_PORTABLE__" @@ -50,7 +52,7 @@ RUN VERSION=$(jq -r .version configs/environ.json) && \ export CGO_LDFLAGS="-L/opt/rocksdb -ldl -lrocksdb -lstdc++ -lm -lz -lbz2 -lsnappy -llz4 -lzstd $(gcc -print-file-name=libjemalloc_pic.a)" && \ go build -o /out/blockbook -ldflags="-s -w \ -X github.com/trezor/blockbook/common.version=${VERSION} \ - -X github.com/trezor/blockbook/common.gitcommit=$(git rev-parse --short HEAD) \ + -X github.com/trezor/blockbook/common.gitcommit=$(git rev-parse HEAD) \ -X github.com/trezor/blockbook/common.buildtime=$(date --iso-8601=seconds)" # The config generator writes bitcoind's rpcauth line with diff --git a/README.md b/README.md index 345b59d..6ac1c96 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,11 @@ Images are published as `ghcr.io/runonflux/blockbook-docker:` from `v*` git tags (CI builds and runs `test/smoke.sh` first). Pin app specs to a tag, never `latest`. -- Blockbook, RocksDB and every coin's configs are built into the image from the trezor/blockbook - commit pinned in the `Dockerfile`; nothing is compiled or fetched from GitHub at container start. +- Blockbook, RocksDB and every coin's configs are built into the image from the + [ZelCore-io/blockbook](https://github.com/ZelCore-io/blockbook) commit pinned in the `Dockerfile` + (trezor/blockbook with the Flux/Zelcore explorer UI); nothing is compiled or fetched from GitHub + at container start. The fork's dashboard feed (`-explorercontenturl`) and Insight API + (`-insight`) are off unless passed in `BLOCKBOOK_PARAMS`. Daemon versions come from that commit's coin configs, with `overrides.json` on top (fluxd 9.1.0, zebrad for Zcash, which is copied in from `zfnd/zebra`). - When the image changes, an existing container re-renders its configs and downloads the new @@ -17,6 +20,10 @@ runs `test/smoke.sh` first). Pin app specs to a tag, never `latest`. `SNAPSHOT_PEERS="ip:port ..."` seeds from given peers. - `heal.sh` runs `reconsiderblock` when the daemon has marked the network's chain invalid and stopped on its last good block. +- Blockbook stops cleanly (`patches/0002`). It closed its ZMQ socket from another thread while a + receive was waiting on it, so libzmq aborted the process now and then and the index was left + marked open. After such a stop, `/api/` showed the last stored height (0 on a new index) until + the next block. - `corruption.sh` only wipes a database its own process reports as corrupt or refuses to open (another coin, other index settings); `log_clean` only empties named log files (it used to empty LevelDB/RocksDB write-ahead logs). diff --git a/patches/0002-clean-shutdown.patch b/patches/0002-clean-shutdown.patch new file mode 100644 index 0000000..5de7232 --- /dev/null +++ b/patches/0002-clean-shutdown.patch @@ -0,0 +1,165 @@ +diff --git a/bchain/mq.go b/bchain/mq.go +index fe39a4bc..667c2d4c 100644 +--- a/bchain/mq.go ++++ b/bchain/mq.go +@@ -55,6 +55,11 @@ func NewMQ(binding string, curve *CurveConfig, callback func(NotificationType), + if err != nil { + return nil, err + } ++ // a SUB socket only has subscriptions to send; Context.Term in Shutdown must not ++ // wait for them when the backend is already gone ++ if err := socket.SetLinger(0); err != nil { ++ return nil, err ++ } + if subs.BlockSubscribe != "" { + if err := socket.SetSubscribe(subs.BlockSubscribe); err != nil { + return nil, err +@@ -110,6 +115,9 @@ func (mq *MQ) run(callback func(NotificationType)) { + if r := recover(); r != nil { + glog.Error("MQ loop recovered from ", r) + } ++ // this goroutine is the only user of the socket, so it closes it; Context.Term ++ // in Shutdown returns once it is closed ++ mq.socket.Close() + mq.isRunning = false + glog.Info("MQ loop terminated") + mq.finished <- nil +@@ -162,31 +170,13 @@ func (mq *MQ) run(callback func(NotificationType)) { + func (mq *MQ) Shutdown(ctx context.Context) error { + glog.Info("MQ server shutdown") + if mq.isRunning { ++ // A zmq socket must not be used by two threads at once. Unsubscribing and closing ++ // it here while run() waited in RecvMessageBytes made libzmq abort the process ++ // (SIGABRT) now and then, before the index was closed. Terminating the context ++ // instead makes that receive return ETERM, and run() closes the socket itself. + go func() { +- // if errors in the closing sequence, let it close ungracefully +- if mq.subs.BlockSubscribe != "" { +- if err := mq.socket.SetUnsubscribe(mq.subs.BlockSubscribe); err != nil { +- mq.finished <- err +- return +- } +- } +- if mq.subs.TxSubscribe != "" { +- if err := mq.socket.SetUnsubscribe(mq.subs.TxSubscribe); err != nil { +- mq.finished <- err +- return +- } +- } +- if err := mq.socket.Unbind(mq.binding); err != nil { +- mq.finished <- err +- return +- } +- if err := mq.socket.Close(); err != nil { +- mq.finished <- err +- return +- } + if err := mq.context.Term(); err != nil { + mq.finished <- err +- return + } + }() + var err error +diff --git a/bchain/mq_shutdown_test.go b/bchain/mq_shutdown_test.go +new file mode 100644 +index 00000000..70e6529f +--- /dev/null ++++ b/bchain/mq_shutdown_test.go +@@ -0,0 +1,80 @@ ++package bchain ++ ++import ( ++ "context" ++ "testing" ++ "time" ++ ++ zmq "github.com/pebbe/zmq4" ++) ++ ++// Shutdown used to unsubscribe and close the socket while run() waited in ++// RecvMessageBytes on it, which libzmq does not allow: it returned an error ++// (the socket was never bound) and now and then aborted the whole process. ++// Shut down repeatedly, right after a notification and while idle. ++func TestMQShutdown(t *testing.T) { ++ subs := SubscriptionTopics{BlockSubscribe: "hashblock", BlockReceive: "hashblock", TxSubscribe: "hashtx", TxReceive: "hashtx"} ++ for i := 0; i < 40; i++ { ++ pubCtx, err := zmq.NewContext() ++ if err != nil { ++ t.Fatal(err) ++ } ++ pub, err := pubCtx.NewSocket(zmq.PUB) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if err := pub.SetLinger(0); err != nil { ++ t.Fatal(err) ++ } ++ if err := pub.Bind("tcp://127.0.0.1:*"); err != nil { ++ t.Fatal(err) ++ } ++ endpoint, err := pub.GetLastEndpoint() ++ if err != nil { ++ t.Fatal(err) ++ } ++ got := make(chan NotificationType, 1) ++ mq, err := NewMQ(endpoint, nil, func(nt NotificationType) { ++ select { ++ case got <- nt: ++ default: ++ } ++ }, subs) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if i%2 == 0 { ++ // a PUB socket drops messages until the subscription has reached it ++ deadline := time.After(10 * time.Second) ++ for delivered := false; !delivered; { ++ if _, err := pub.SendMessage("hashblock", []byte{1}, []byte{0, 0, 0, 0}); err != nil { ++ t.Fatal(err) ++ } ++ select { ++ case nt := <-got: ++ if nt != NotificationNewBlock { ++ t.Fatalf("iteration %d: notification %v, want NotificationNewBlock", i, nt) ++ } ++ delivered = true ++ case <-time.After(20 * time.Millisecond): ++ case <-deadline: ++ t.Fatalf("iteration %d: no notification", i) ++ } ++ } ++ } else { ++ // run() is blocked in RecvMessageBytes ++ time.Sleep(20 * time.Millisecond) ++ } ++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) ++ err = mq.Shutdown(ctx) ++ cancel() ++ if err != nil { ++ t.Fatalf("iteration %d: Shutdown: %v", i, err) ++ } ++ if mq.isRunning { ++ t.Fatalf("iteration %d: the receive loop is still running", i) ++ } ++ pub.Close() ++ pubCtx.Term() ++ } ++} +diff --git a/db/sync.go b/db/sync.go +index b2e46715..9b23c475 100644 +--- a/db/sync.go ++++ b/db/sync.go +@@ -270,6 +270,12 @@ func (w *SyncWorker) ResyncIndex(onNewBlock bchain.OnNewBlockFunc, initialSync b + w.metrics.BlockbookBestHeight.Set(float64(bh)) + return err + case syncNotNeeded: ++ // The internal state is only stored now and then, so after an unclean stop its ++ // best height can be behind the index (0 on a fresh one). With nothing to sync ++ // it was never corrected and /api/ reported that height until the next block. ++ if bh, _, err := w.db.GetBestBlock(); err == nil { ++ w.is.UpdateBestHeight(bh) ++ } + w.is.FinishedSyncNoChange() + w.metrics.IndexDBSize.Set(float64(w.db.DatabaseSizeOnDisk())) + if initialSync { diff --git a/test/smoke.sh b/test/smoke.sh index e056158..982d808 100755 --- a/test/smoke.sh +++ b/test/smoke.sh @@ -54,10 +54,18 @@ cli bb-a generatetodescriptor 150 'raw(51)' > /dev/null wait_for 300 "A: blockbook indexed 150 blocks" height_is bb-a 150 [[ "$(api bb-a | jq -r .blockbook.inSync)" == "true" ]] docker exec bb-a cat /opt/blockbook/VERSION +# the explorer pages render with the fork's UI and its stylesheet is served +HOME_PAGE=$(docker exec bb-a curl -sSf -m 20 http://127.0.0.1:19121/) +HUB_CSS=$(grep -o '/static/css/hub[^"]*\.css' <<< "$HOME_PAGE" | head -1) +[[ -n "$HUB_CSS" ]] || { echo "FAILED: the explorer home page has no hub stylesheet"; exit 1; } +docker exec bb-a curl -sSf -m 20 -o /dev/null "http://127.0.0.1:19121$HUB_CSS" +docker exec bb-a curl -sSf -m 20 -o /dev/null "http://127.0.0.1:19121/block/1" docker exec bb-a bash -c '. /run/bb/env.sh; /snapshot.sh create' docker exec bb-a cat /root/snapshot/info.json | jq -e '.height == 150 and .bytes > 0' wait_for 120 "A: blockbook back after the snapshot" height_is bb-a 150 +# blockbook used to abort now and then when stopped (patches/0002) +refute docker exec bb-a grep -q "possibly previous ungraceful shutdown" /root/blockbook.log docker exec bb-a test ! -e /root/snapshot/backend/wallet.dat docker exec bb-a bash -c "test -z \"\$(find /root/snapshot -name '*.conf')\"" From 0a8b5f5f07769893a09c3891e821d83e7619a662 Mon Sep 17 00:00:00 2001 From: TheTrunk Date: Wed, 28 Oct 2026 16:30:29 +0800 Subject: [PATCH 10/15] Rebuild an index left inconsistent by an interrupted first sync, then sync with one worker; cap blockbook's Go heap; v3 releases also move the v3 and v3.0.0 tags --- .github/workflows/docker.yml | 11 +++++++++-- README.md | 14 ++++++++++++-- blockbook.sh | 16 ++++++++++++++++ build.sh | 2 +- corruption.sh | 12 +++++++++++- test/smoke.sh | 12 +++++++++++- 6 files changed, 60 insertions(+), 7 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 9b59010..2149369 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -58,7 +58,14 @@ jobs: if: startsWith(github.ref, 'refs/tags/v') run: | TAG=${GITHUB_REF_NAME} + # Flux nodes check an app's image tag every 6 hours and redeploy the app + # in place, data kept, when the tag points at a new image; a spec update + # installs it afresh wherever the network places it. So a v3 release also + # moves v3 and v3.0.0, the tag the app specs use. + TAGS=$(case $TAG in v3.*) echo "$TAG v3 v3.0.0" ;; *) echo "$TAG" ;; esac | tr ' ' '\n' | sort -u) for image in $GHCR_IMAGE $([ "$HAS_HUB" = "true" ] && echo $HUB_IMAGE); do - docker tag blockbook-docker:test $image:$TAG - docker push $image:$TAG + for t in $TAGS; do + docker tag blockbook-docker:test $image:$t + docker push $image:$t + done done diff --git a/README.md b/README.md index 6ac1c96..1251dcc 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,10 @@ ### v3: pinned image Images are published as `ghcr.io/runonflux/blockbook-docker:` from `v*` git tags (CI builds and -runs `test/smoke.sh` first). Pin app specs to a tag, never `latest`. +runs `test/smoke.sh` first). Pin app specs to a tag, never `latest`. Every `v3.*` release also +moves `v3` and `v3.0.0` (the tag the app specs use): Flux nodes check an app's tag every 6 hours +and redeploy it in place with its data kept, while a spec update installs the app afresh +wherever the network places it. - Blockbook, RocksDB and every coin's configs are built into the image from the [ZelCore-io/blockbook](https://github.com/ZelCore-io/blockbook) commit pinned in the `Dockerfile` @@ -26,7 +29,14 @@ runs `test/smoke.sh` first). Pin app specs to a tag, never `latest`. the next block. - `corruption.sh` only wipes a database its own process reports as corrupt or refuses to open (another coin, other index settings); `log_clean` only empties named log files (it used to empty - LevelDB/RocksDB write-ahead logs). + LevelDB/RocksDB write-ahead logs). It runs every 30 minutes. +- The first sync with several workers is a bulk import: blockbook holds large maps of + transactions and balances in memory and marks the index inconsistent until it ends. Killed + before that (out of memory, shared with the daemon), it leaves an index it refuses to open. + `corruption.sh` rebuilds such an index (from a peer's snapshot if one has it) and + `/root/blockbook-db.sequential` makes blockbook sync with one worker from then on: slower, + much less memory, consistent after every block. Blockbook runs with `GOMEMLIMIT` at half the + container's memory (80% without a local daemon). - `PRUNE_BACKEND=1` (Bitcoin): the daemon runs without txindex and with manual pruning, and `prune.sh` keeps it `PRUNE_KEEP_BLOCKS` (2000) behind blockbook, pausing it at `PRUNE_MAX_BLOCKS_GB` (80) of unindexed blocks. Blockbook (`-prunedbackend`, `patches/0001`) diff --git a/blockbook.sh b/blockbook.sh index 19e5fc1..8f71e45 100644 --- a/blockbook.sh +++ b/blockbook.sh @@ -50,6 +50,22 @@ if [[ ! -d /root/blockbook-db ]]; then mkdir -p /root/blockbook-db fi +# The first sync with several workers is a bulk import: it keeps large maps of +# transactions and balances in memory and leaves the index unusable if it is +# killed before it ends. After that happened once (corruption.sh), one worker: +# slower, much less memory, and the index is consistent after every block. +if [[ -z "$WORKERS" && -f /root/blockbook-db.sequential ]]; then + WORKERS=1 +fi +# Go collects garbage harder near this limit instead of letting its heap grow +# to twice what is live. Blockbook shares the container with the daemon. +mem_max=$(cat /sys/fs/cgroup/memory.max 2>/dev/null) +if [[ -z "$GOMEMLIMIT" && "$mem_max" =~ ^[0-9]+$ ]]; then + if [[ "${DAEMON:-1}" == "1" ]]; then share=50; else share=80; fi + export GOMEMLIMIT="$(( mem_max / 1048576 * share / 100 ))MiB" + echo -e "| GOMEMLIMIT=$GOMEMLIMIT" +fi + # -dbcache is in bytes: the old default of 500 gave RocksDB a 500 byte cache. exec_string="$HOME/blockbook/blockbook -sync -blockchaincfg=$CFG_FILE -datadir=/root/blockbook-db -workers=${WORKERS:-4} -dbcache=${DBCACHE:-536870912} -public=:${BLOCKBOOK_PORT} -logtostderr" args_to_remove=( -datadir -debug -log -blockchaincfg -sync -logtostderr -public ) diff --git a/build.sh b/build.sh index 0a00195..c1579d0 100644 --- a/build.sh +++ b/build.sh @@ -49,7 +49,7 @@ echo "$IMAGE_VERSION" > /root/.image_version cat > /etc/cron.d/blockbook <<'EOF' SHELL=/bin/bash 0 0 */5 * * root . /run/bb/env.sh; /utils.sh log_clean >> /root/maintenance.log 2>&1 -15 */2 * * * root . /run/bb/env.sh; flock -n /run/bb/corruption.lock /corruption.sh >> /root/maintenance.log 2>&1 +5,35 * * * * root . /run/bb/env.sh; flock -n /run/bb/corruption.lock /corruption.sh >> /root/maintenance.log 2>&1 */30 * * * * root . /run/bb/env.sh; flock -n /run/bb/heal.lock /heal.sh >> /root/maintenance.log 2>&1 */20 * * * * root . /run/bb/env.sh; flock -n /run/bb/snapshot.lock /snapshot.sh create >> /root/maintenance.log 2>&1 */5 * * * * root . /run/bb/env.sh; flock -n /run/bb/prune.lock /prune.sh >> /root/maintenance.log 2>&1 diff --git a/corruption.sh b/corruption.sh index 21817a8..3c2b80e 100644 --- a/corruption.sh +++ b/corruption.sh @@ -11,14 +11,24 @@ CF_LOGS=/root/corrupion_events.log # settings (a testnet3 index after the switch to testnet4, a full node's index # under PRUNE_BACKEND or the other way round), which blockbook refuses to open. BLOCKBOOK_PATTERNS='rocksDB: Corruption|SST file is ahead of WALs|Coins do not match|ExtendedIndex setting does not match|PrunedBackend setting does not match|does not match the required version|BlockGolombFilterP does not match|BlockFilterScripts does not match|BlockFilterUseZeroedKey does not match' +# An index that can only be rebuilt: a first (bulk) sync that was killed, most +# often out of memory, leaves it marked inconsistent, and an index ahead of a +# chain it has no undo data for cannot disconnect its blocks. +INDEX_PATTERNS='database is in inconsistent state|Cannot disconnect blocks' BACKEND_PATTERNS='Corrupted block database detected|Error opening block database|Fatal LevelDB error|Error initializing block database|database corrupted' [[ -f /run/bb/prepared && -f /run/bb/bootstrapped ]] || exit 0 echo -e "------------------------------------------ [$(date '+%Y-%m-%d %H:%M:%S')] corruption check" -if [[ -f /root/blockbook.log ]] && tail -n 5000 /root/blockbook.log | grep -aqE "$BLOCKBOOK_PATTERNS"; then +if [[ -f /root/blockbook.log ]] && tail -n 5000 /root/blockbook.log | grep -aqE "$BLOCKBOOK_PATTERNS|$INDEX_PATTERNS"; then echo "[$(date "+%d/%m/%y %H:%M:%S %Z %z")] - BlockBook Corruption detected" >> $CF_LOGS echo -e "| RocksDB corruption, cleaning the blockbook database" + if tail -n 5000 /root/blockbook.log | grep -aq "database is in inconsistent state"; then + # It would be killed at the same point again: blockbook.sh syncs with one + # worker from now on, block by block, consistent after every block. + echo -e "| The first sync was interrupted, rebuilding with one worker" + touch /root/blockbook-db.sequential + fi supervisorctl stop blockbook > /dev/null 2>&1 rm -rf /root/blockbook-db/* : > /root/blockbook.log diff --git a/test/smoke.sh b/test/smoke.sh index 982d808..e73181e 100755 --- a/test/smoke.sh +++ b/test/smoke.sh @@ -70,10 +70,20 @@ docker exec bb-a test ! -e /root/snapshot/backend/wallet.dat docker exec bb-a bash -c "test -z \"\$(find /root/snapshot -name '*.conf')\"" A_IP=$(docker inspect -f "{{(index .NetworkSettings.Networks \"$NET\").IPAddress}}" bb-a) -run bb-b -e PEER_BOOTSTRAP=1 -e SNAPSHOT_PEERS="$A_IP:1337" +run bb-b --memory=4g -e PEER_BOOTSTRAP=1 -e SNAPSHOT_PEERS="$A_IP:1337" wait_for 300 "B: seeded from A and serving height 150" height_is bb-b 150 docker exec bb-b grep -q "restored from $A_IP" /root/bootstrap.log [[ "$(cli bb-b getblockcount)" == "150" ]] +# A first sync killed out of memory leaves the index marked inconsistent, and +# blockbook refuses to open it. corruption.sh rebuilds it (from A's snapshot +# here) and blockbook continues with one worker. +docker exec bb-b bash -c 'echo "E1028 blockbook.go:292] internalState: database is in inconsistent state and cannot be used" >> /root/blockbook.log; . /run/bb/env.sh; /corruption.sh' +docker exec bb-b test -f /root/blockbook-db.sequential +wait_for 300 "B: index rebuilt after an interrupted first sync" height_is bb-b 150 +B_PID=$(docker exec bb-b pgrep -x blockbook) +B_ARGS=$(docker exec bb-b bash -c "tr '\0' ' ' < /proc/$B_PID/cmdline") +[[ "$B_ARGS" == *-workers=1* ]] || { echo "FAILED: B blockbook args: $B_ARGS"; exit 1; } +docker exec bb-b bash -c "tr '\0' '\n' < /proc/$B_PID/environ | grep -q '^GOMEMLIMIT=[0-9]*MiB$'" # supervisorctl stop returns only once the daemon has exited: bitcoind renames # itself b-shutoff while it flushes, and a wait on its name returned too early. From 8005d5bc03eaf73df866292765834c882969220b Mon Sep 17 00:00:00 2001 From: TheTrunk Date: Wed, 28 Oct 2026 23:24:35 +0800 Subject: [PATCH 11/15] Make cron load its jobs when it started in the second build.sh wrote them --- build.sh | 6 ++++++ test/smoke.sh | 3 +++ 2 files changed, 9 insertions(+) diff --git a/build.sh b/build.sh index c1579d0..a8dc402 100644 --- a/build.sh +++ b/build.sh @@ -57,6 +57,12 @@ SHELL=/bin/bash EOF chmod 644 /etc/cron.d/blockbook crontab -r 2>/dev/null +# cron reloads a file when its mtime changes, in whole seconds. crond starts +# alongside this script, and when it read /etc/cron.d in the second the file +# was written, it never ran a single job (no corruption checks, no pruning). +# A second later mtime tells it the file changed. +sleep 2 +touch /etc/cron.d/blockbook /etc/cron.d touch /run/bb/prepared echo -e "| Configs ready" diff --git a/test/smoke.sh b/test/smoke.sh index e73181e..613459a 100755 --- a/test/smoke.sh +++ b/test/smoke.sh @@ -54,6 +54,9 @@ cli bb-a generatetodescriptor 150 'raw(51)' > /dev/null wait_for 300 "A: blockbook indexed 150 blocks" height_is bb-a 150 [[ "$(api bb-a | jq -r .blockbook.inSync)" == "true" ]] docker exec bb-a cat /opt/blockbook/VERSION +# cron loads its file only if its mtime is later than the second cron read it +docker exec bb-a bash -c '(( $(stat -c %Y /etc/cron.d/blockbook) > $(date -d "$(ps -o lstart= -p $(pgrep -x cron))" +%s) ))' \ + || { echo "FAILED: the cron file was not touched after cron started"; exit 1; } # the explorer pages render with the fork's UI and its stylesheet is served HOME_PAGE=$(docker exec bb-a curl -sSf -m 20 http://127.0.0.1:19121/) HUB_CSS=$(grep -o '/static/css/hub[^"]*\.css' <<< "$HOME_PAGE" | head -1) From 7317a9902ef69b81be490a79e1d458ab355acd54 Mon Sep 17 00:00:00 2001 From: TheTrunk Date: Sat, 31 Oct 2026 18:11:11 +0800 Subject: [PATCH 12/15] Build from ZelCore-io/blockbook f459589: the new explorer UI without the Trezor terms link 423f085 predates the explorer rollout, so Flux instances served the old UI while the Zelcore servers in the same app pools served the new one. --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 4323443..9c7829a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -15,7 +15,7 @@ FROM debian:13 AS build SHELL ["/bin/bash", "-o", "pipefail", "-c"] # Zelcore's fork of trezor/blockbook: the Flux/Zelcore explorer UI and an optional Insight API ARG BLOCKBOOK_REPO=https://github.com/ZelCore-io/blockbook.git -ARG BLOCKBOOK_COMMIT=423f085a181435450a55f4ea30a20adb7ba9269d +ARG BLOCKBOOK_COMMIT=f4595896869d663c2e69bdd2b86524f8a5049e4c ARG GOLANG_VERSION=go1.25.4 ARG GOLANG_SHA256=9fa5ffeda4170de60f67f3aa0f824e426421ba724c21e133c1e35d6159ca1bec ARG ROCKSDB_VERSION=v9.10.0 From 77fe4da33ad78bfc65ad569f678b74180ee9fb7c Mon Sep 17 00:00:00 2001 From: TheTrunk Date: Wed, 4 Nov 2026 08:02:55 +0800 Subject: [PATCH 13/15] Zebra 7.0.0 (NU7; 6.4.2 reached end of support); a reseed deletes local data only once a peer is sending; a failed download leaves no partial data; one restore at a time --- Dockerfile | 2 +- README.md | 9 ++++++--- overrides.json | 2 +- snapshot.sh | 42 ++++++++++++++++++++++++++++++------------ snapshot_server.py | 2 +- test/smoke.sh | 10 ++++++++++ 6 files changed, 49 insertions(+), 18 deletions(-) diff --git a/Dockerfile b/Dockerfile index 9c7829a..4cfb406 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,7 +5,7 @@ # container starts in seconds instead of compiling for half an hour. Daemon # binaries are still downloaded on first start, from the URL pinned in the # coin config of that same commit (plus overrides.json). -ARG ZEBRA_VERSION=6.4.2 +ARG ZEBRA_VERSION=7.0.0 FROM zfnd/zebra:${ZEBRA_VERSION} AS zebra diff --git a/README.md b/README.md index 1251dcc..19c10a6 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,9 @@ wherever the network places it. snapshot of its chain data and serves it on container port 1337 to the other instances of the same Flux app. A new or far-behind instance seeds from the best peer instead of syncing from block 0. Needs port 1337 mapped in the app spec. `PEER_BOOTSTRAP=0` disables seeding, - `SNAPSHOT_PEERS="ip:port ..."` seeds from given peers. + `SNAPSHOT_PEERS="ip:port ..."` seeds from given peers. A peer serves two downloads at a time + and answers the rest busy; an instance replacing its own data deletes it only once a peer is + sending, so a busy or unreachable peer leaves it as it was. - `heal.sh` runs `reconsiderblock` when the daemon has marked the network's chain invalid and stopped on its last good block. - Blockbook stops cleanly (`patches/0002`). It closed its ZMQ socket from another thread while a @@ -49,8 +51,9 @@ wherever the network places it. instead of ~1.1 TB plus 886 GB of blocks (2026); as on every other coin without it, a spent output gets `spentTxId` only with `?spending=true`. If no peer sends a block, the transaction comes from the index: fee and vsize included, scripts and input txids not. -- Zebra releases stop at an end-of-support height about 16 weeks after release: bump - `ZEBRA_VERSION` in time. +- Zebra releases stop at an end-of-support height, 8 to 16 weeks after release (zebrad + panics in `end_of_support.rs` at every start): bump `ZEBRA_VERSION` in time. 7.0.0 (NU7) + halts about 56 days after its release, around mid-December 2026. ### USAGE ``` diff --git a/overrides.json b/overrides.json index e8c7e29..267b03a 100644 --- a/overrides.json +++ b/overrides.json @@ -7,7 +7,7 @@ }, "zcash": { "backend": { - "version": "6.4.2" + "version": "7.0.0" } }, "bcash": { diff --git a/snapshot.sh b/snapshot.sh index c32921d..be5b25f 100755 --- a/snapshot.sh +++ b/snapshot.sh @@ -153,16 +153,28 @@ function peers() { | sort -n | cut -d' ' -f2- } -# $1 = peer ip:port, $2 = path on the peer, $3 = members expected in the tar +# $1 = peer ip:port, $2 = path on the peer, $3 = command run once the peer is +# sending (it has sent info.json, the tar's first member), $4... = members +# expected in the tar. A peer that is busy or gone sends nothing, so local data +# that $3 makes room by deleting is kept unless the download really started. function download() { - local peer=$1 path=$2 - shift 2 - rm -rf $TMP && mkdir -p $TMP + local peer=$1 path=$2 on_start=$3 + shift 3 + rm -rf $TMP $TMP.rc && mkdir -p $TMP log "bootstrap: downloading http://$peer$path" - curl -sf --connect-timeout 15 --speed-limit 51200 --speed-time 600 http://$peer$path | tar -x -C $TMP - local rc=("${PIPESTATUS[@]}") + ( curl -sf --connect-timeout 15 --speed-limit 51200 --speed-time 600 http://$peer$path | tar -x -C $TMP + echo "${PIPESTATUS[@]}" > $TMP.rc ) & + local pid=$! + if [[ -n "$on_start" ]]; then + while kill -0 $pid 2> /dev/null && [[ ! -e $TMP/info.json ]]; do sleep 1; done + [[ -e $TMP/info.json ]] && $on_start + fi + wait $pid + local rc=($(cat $TMP.rc 2> /dev/null)) + rm -f $TMP.rc if [[ "${rc[0]}" != "0" || "${rc[1]}" != "0" ]]; then log "bootstrap: download from $peer failed (curl ${rc[0]}, tar ${rc[1]})" + rm -rf $TMP return 1 fi for m in "$@"; do @@ -170,10 +182,19 @@ function download() { done } +# Make room for a download that has started (restore's local_* are in scope). +function clear_index() { rm -rf "${BBDB:?}"/*; local_bb=0; } +function clear_chain() { rm -rf "${BACKEND:?}"/* "${BBDB:?}"/*; local_backend=0 local_bb=0; } + # $1=1 restores only the index; $2=1 replaces local data even if it is close. function restore() { local only_blockbook=$1 force=$2 mkdir -p /run/bb $BACKEND $BBDB + # One restore at a time (corruption.sh and the hourly reseed both restore); + # whatever is left in $TMP is from one that was killed. + exec 9> /run/bb/restore.lock + flock 9 + rm -rf $TMP [[ "$only_blockbook" == "1" || "$force" == "1" ]] || trap 'touch /run/bb/bootstrapped' EXIT until [[ -f /run/bb/prepared ]]; do sleep 5; done if [[ "$PEER_BOOTSTRAP" != "1" || "$DAEMON" != "1" || ( -z "$FLUX_APP_NAME" && -z "$SNAPSHOT_PEERS" ) ]]; then @@ -206,7 +227,7 @@ function restore() { (( tried++ >= 3 )) && break if [[ "$only_blockbook" == "1" ]]; then (( $(free_bytes) > bb_bytes * 11 / 10 )) || { log "bootstrap: not enough disk for $bb_bytes bytes"; return 0; } - download $peer /snapshot-blockbook.tar blockbook-db/CURRENT || continue + download $peer /snapshot-blockbook.tar "" blockbook-db/CURRENT || continue rm -rf $BBDB && mv $TMP/blockbook-db $BBDB && rm -rf $TMP log "bootstrap: index restored from $peer at height $height" return 0 @@ -219,16 +240,13 @@ function restore() { if [[ "$force" != "1" ]] && (( local_backend * 10 >= backend_bytes * 9 )); then log "bootstrap: backend is synced but the index is far behind, taking only the index from $peer" (( $(free_bytes) + local_bb > bb_bytes * 11 / 10 )) || { log "bootstrap: not enough disk"; return 0; } - rm -rf "${BBDB:?}"/* - download $peer /snapshot-blockbook.tar blockbook-db/CURRENT || continue + download $peer /snapshot-blockbook.tar clear_index blockbook-db/CURRENT || continue rm -rf $BBDB && mv $TMP/blockbook-db $BBDB && rm -rf $TMP log "bootstrap: index restored from $peer at height $height" return 0 fi (( $(free_bytes) + local_backend + local_bb > total * 11 / 10 )) || { log "bootstrap: not enough disk for $total bytes"; return 0; } - rm -rf "${BACKEND:?}"/* $BBDB/* - local_backend=0 local_bb=0 - download $peer /snapshot.tar backend blockbook-db/CURRENT || continue + download $peer /snapshot.tar clear_chain backend blockbook-db/CURRENT || continue # Only the chain data is replaced; configs, wallet and logs stay. cp -al $TMP/backend/. $BACKEND/ && rm -rf $BBDB && mv $TMP/blockbook-db $BBDB && rm -rf $TMP echo -e "Bootstrap [LOCKED] from peer $peer" > /root/BOOTSTRAP_LOCKED diff --git a/snapshot_server.py b/snapshot_server.py index e86fcb5..2ae96c4 100755 --- a/snapshot_server.py +++ b/snapshot_server.py @@ -19,7 +19,7 @@ import time import urllib.request -SNAP = '/root/snapshot' +SNAP = os.environ.get('SNAPSHOT_DIR', '/root/snapshot') APP = os.environ.get('FLUX_APP_NAME', '') PORT = int(os.environ.get('SNAPSHOT_SERVER_PORT', '1337')) PUBLIC = os.environ.get('SNAPSHOT_PUBLIC') == '1' diff --git a/test/smoke.sh b/test/smoke.sh index 613459a..410b8ca 100755 --- a/test/smoke.sh +++ b/test/smoke.sh @@ -87,6 +87,16 @@ B_PID=$(docker exec bb-b pgrep -x blockbook) B_ARGS=$(docker exec bb-b bash -c "tr '\0' ' ' < /proc/$B_PID/cmdline") [[ "$B_ARGS" == *-workers=1* ]] || { echo "FAILED: B blockbook args: $B_ARGS"; exit 1; } docker exec bb-b bash -c "tr '\0' '\n' < /proc/$B_PID/environ | grep -q '^GOMEMLIMIT=[0-9]*MiB$'" +# A peer far ahead whose downloads are all taken: B's reseed fails and B keeps +# its chain and index (it used to delete them before the download began). +docker exec bb-a bash -c 'mkdir -p /root/busy && jq ".height = 100000" /root/snapshot/info.json > /root/busy/info.json' +docker exec -d -e SNAPSHOT_DIR=/root/busy -e SNAPSHOT_SERVER_PORT=1338 -e SNAPSHOT_MAX_DOWNLOADS=0 bb-a python3 /snapshot_server.py +wait_for 30 "A: busy peer answers" docker exec bb-b curl -sf -m 5 http://$A_IP:1338/snapshot/info.json +RESEED=$(docker exec bb-b bash -c ". /run/bb/env.sh; SNAPSHOT_PEERS=$A_IP:1338 FLUX_APP_NAME=smoke /snapshot.sh reseed 2>&1") +echo "$RESEED" +grep -q "every peer download failed" <<< "$RESEED" || { echo "FAILED: B did not try the busy peer"; exit 1; } +wait_for 300 "B: kept its index after a failed reseed" height_is bb-b 150 +[[ "$(cli bb-b getblockcount)" == "150" ]] # supervisorctl stop returns only once the daemon has exited: bitcoind renames # itself b-shutoff while it flushes, and a wait on its name returned too early. From 72f3f75fdb40c1f9a1997283a061bd3fcb79ece5 Mon Sep 17 00:00:00 2001 From: TheTrunk Date: Wed, 11 Nov 2026 14:20:12 +0800 Subject: [PATCH 14/15] Litecoin snapshots carry the MWEB state; catch every RocksDB corruption; cap daemon caches to the container - Litecoin keeps its MWEB leafset and MMR (leaf000923.dat, O000923.dat) at the top of the datadir, which link_tree left out with the wallet and logs. A restored node failed verifying its last MWEB blocks (MMR_MISMATCH), logged "Corrupted block database", and corruption.sh wiped it and downloaded the 501 GB snapshot again, every few hours. The files are taken now, and a Litecoin snapshot without them is replaced once not in use. - corruption.sh matched only "rocksDB: Corruption"; blockbook also logs "storeInternalStateLoop Corruption: block checksum mismatch", and a VTC index stayed corrupt at block 36656. Any "Corruption: " now, and the matching lines go to corrupion_events.log. - The backend template's dbcache=1000 and maxmempool=2000 are capped at 1/8 of the container's memory: viacoind in a 4 GB app was killed 100 times in a week, losing its unflushed cache each time. --- build.sh | 11 +++++++++++ corruption.sh | 6 +++++- snapshot.sh | 12 +++++++++++- test/smoke.sh | 3 +++ 4 files changed, 30 insertions(+), 2 deletions(-) diff --git a/build.sh b/build.sh index a8dc402..650bca9 100644 --- a/build.sh +++ b/build.sh @@ -40,6 +40,17 @@ if [[ "$DAEMON_CONFIG" == "AUTO" && -f $PKG/server.conf && ! -f /root/$CONFIG_DI echo -e "| Installing $CONFIG_FILE.conf" cp $PKG/server.conf /root/$CONFIG_DIR/$CONFIG_FILE.conf touch /root/$CONFIG_DIR/.conf_fresh + # The template's dbcache=1000 and maxmempool=2000 (MB) are for a dedicated + # server: in a 4 GB app viacoind grew past the limit and was killed every + # hour or two, losing the cache it had not flushed. At most 1/8 of the + # container's memory each. + MEM_MAX=$(cat /sys/fs/cgroup/memory.max 2>/dev/null) + if [[ "$MEM_MAX" =~ ^[0-9]+$ ]]; then + CACHE_MB=$(( MEM_MAX / 8 / 1048576 )) + (( CACHE_MB < 300 )) && CACHE_MB=300 + awk -F= -v OFS== -v cap=$CACHE_MB '($1 == "dbcache" || $1 == "maxmempool") && $2 > cap { $2 = cap } 1' \ + /root/$CONFIG_DIR/$CONFIG_FILE.conf > /tmp/conf && mv /tmp/conf /root/$CONFIG_DIR/$CONFIG_FILE.conf + fi fi echo "$IMAGE_VERSION" > /root/.image_version diff --git a/corruption.sh b/corruption.sh index 3c2b80e..3a9f1a9 100644 --- a/corruption.sh +++ b/corruption.sh @@ -10,7 +10,9 @@ CF_LOGS=/root/corrupion_events.log # The "does not match" errors: an index built for another coin or with other # settings (a testnet3 index after the switch to testnet4, a full node's index # under PRUNE_BACKEND or the other way round), which blockbook refuses to open. -BLOCKBOOK_PATTERNS='rocksDB: Corruption|SST file is ahead of WALs|Coins do not match|ExtendedIndex setting does not match|PrunedBackend setting does not match|does not match the required version|BlockGolombFilterP does not match|BlockFilterScripts does not match|BlockFilterUseZeroedKey does not match' +# RocksDB reports corruption as "Corruption: ", prefixed with whatever +# call hit it ("rocksDB: ", "storeInternalStateLoop ", ...). +BLOCKBOOK_PATTERNS='Corruption: |SST file is ahead of WALs|Coins do not match|ExtendedIndex setting does not match|PrunedBackend setting does not match|does not match the required version|BlockGolombFilterP does not match|BlockFilterScripts does not match|BlockFilterUseZeroedKey does not match' # An index that can only be rebuilt: a first (bulk) sync that was killed, most # often out of memory, leaves it marked inconsistent, and an index ahead of a # chain it has no undo data for cannot disconnect its blocks. @@ -22,6 +24,7 @@ echo -e "------------------------------------------ [$(date '+%Y-%m-%d %H:%M:%S' if [[ -f /root/blockbook.log ]] && tail -n 5000 /root/blockbook.log | grep -aqE "$BLOCKBOOK_PATTERNS|$INDEX_PATTERNS"; then echo "[$(date "+%d/%m/%y %H:%M:%S %Z %z")] - BlockBook Corruption detected" >> $CF_LOGS + tail -n 5000 /root/blockbook.log | grep -aE "$BLOCKBOOK_PATTERNS|$INDEX_PATTERNS" | tail -n 3 >> $CF_LOGS echo -e "| RocksDB corruption, cleaning the blockbook database" if tail -n 5000 /root/blockbook.log | grep -aq "database is in inconsistent state"; then # It would be killed at the same point again: blockbook.sh syncs with one @@ -49,6 +52,7 @@ fi DEBUG_LOG=/root/$CONFIG_DIR/backend/debug.log if [[ "$DAEMON" == "1" && -f $DEBUG_LOG ]] && tail -n 5000 $DEBUG_LOG | grep -aqE "$BACKEND_PATTERNS"; then echo "[$(date "+%d/%m/%y %H:%M:%S %Z %z")] - Backend Corruption detected" >> $CF_LOGS + tail -n 5000 $DEBUG_LOG | grep -aE "$BACKEND_PATTERNS" | tail -n 3 >> $CF_LOGS echo -e "| Backend database corruption, starting over from a peer snapshot or block 0" supervisorctl stop blockbook daemon > /dev/null 2>&1 # The index cannot be kept: it would be ahead of the emptied backend. diff --git a/snapshot.sh b/snapshot.sh index be5b25f..1d82455 100755 --- a/snapshot.sh +++ b/snapshot.sh @@ -50,6 +50,14 @@ function link_tree() { *.ldb|*.sst|*.blob|blk*.dat|rev*.dat) ln "$src/$f" "$dst/$f" || return 1 ;; *) cp -p "$src/$f" "$dst/$f" || return 1 ;; esac + done || return 1 + # Litecoin keeps its MWEB state (leaf000923.dat, O000923.dat, numbered with + # the chainstate) at the top of the datadir. A snapshot without it restored + # a node that failed on its last MWEB blocks (MMR_MISMATCH), called its block + # database corrupted and was wiped and restored again every few hours. + [[ "$top" == "1" ]] && return 0 + (cd "$src" && find . -maxdepth 1 -type f \( -name 'leaf[0-9]*.dat' -o -name '[A-Z][0-9]*.dat' \)) | while read -r f; do + cp -p "$src/$f" "$dst/$f" || return 1 done } @@ -81,7 +89,9 @@ function create() { if ls /run/bb/serving.* > /dev/null 2>&1; then return 0 fi - if [[ -f $SNAP/info.json ]]; then + # A Litecoin snapshot from before link_tree took the MWEB files cannot be + # restored: it is replaced as soon as nobody is downloading it. + if [[ -f $SNAP/info.json ]] && ! { ls $BACKEND/leaf*.dat && ! ls $SNAP/backend/leaf*.dat; } > /dev/null 2>&1; then local created=$(jq -r .created $SNAP/info.json) local jitter=$(( $(cksum <<< "$FLUX_NODE_HOST_IP" | cut -d' ' -f1) % 7200 )) (( $(date +%s) - created < INTERVAL + jitter )) && return 0 diff --git a/test/smoke.sh b/test/smoke.sh index 410b8ca..fc14f98 100755 --- a/test/smoke.sh +++ b/test/smoke.sh @@ -87,6 +87,9 @@ B_PID=$(docker exec bb-b pgrep -x blockbook) B_ARGS=$(docker exec bb-b bash -c "tr '\0' ' ' < /proc/$B_PID/cmdline") [[ "$B_ARGS" == *-workers=1* ]] || { echo "FAILED: B blockbook args: $B_ARGS"; exit 1; } docker exec bb-b bash -c "tr '\0' '\n' < /proc/$B_PID/environ | grep -q '^GOMEMLIMIT=[0-9]*MiB$'" +# 4 GB: the template's dbcache=1000 and maxmempool=2000 are capped at 512. +docker exec bb-b grep -q '^dbcache=512$' $CONF +docker exec bb-b grep -q '^maxmempool=512$' $CONF # A peer far ahead whose downloads are all taken: B's reseed fails and B keeps # its chain and index (it used to delete them before the download began). docker exec bb-a bash -c 'mkdir -p /root/busy && jq ".height = 100000" /root/snapshot/info.json > /root/busy/info.json' From 2778661bf42682fb789f56f55baddea3c7f370ae Mon Sep 17 00:00:00 2001 From: TheTrunk Date: Sun, 15 Nov 2026 15:39:34 +0800 Subject: [PATCH 15/15] Snapshot downloads continue where they broke off; local data stays until a download is complete - A ZEC peer's connections were all dropped once an hour, 12 minutes into a 313 GB download. Two instances started over from byte 0 every hour, 175 times, and held both of its download slots while the other instances were turned away busy. A download that breaks off now continues from the tar member it was writing (snapshot_server.py ?from=&created=: the tar is built sorted by name, so the bytes are the same; 409 if the snapshot was replaced). It gives up after 3 tries that get nowhere; a peer that sends nothing is still left at once. - Done means tar read the end-of-archive blocks. A stream cut at a member boundary made tar exit 0, and after a resume tar can stop before curl has written the record padding (curl 23). - A reseed deleted the local index or chain as soon as the peer started sending, so a download that broke off cost a ZEC instance its 2.67M-block index. Local data is now replaced only once the download is complete, and deleted at the start only when the disk cannot hold both. - The dbcache/maxmempool cap ran only when the daemon config was first installed, and an image with the same blockbook and coin configs does not install it again: viacoind kept dbcache=1000 and its OOM kills. It runs on every start now. - peers() printed "the app spec maps no port to 1337" to stdout, where restore() read it as a peer ("not enough disk for bootstrap: bytes"), and its port lookup failed on a spec without 1337 (jq: Cannot iterate over null). --- README.md | 6 ++-- build.sh | 23 ++++++++-------- snapshot.sh | 69 +++++++++++++++++++++++++++++++++------------- snapshot_server.py | 35 +++++++++++++++++------ test/smoke.sh | 7 +++++ 5 files changed, 100 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index 19c10a6..4443700 100644 --- a/README.md +++ b/README.md @@ -21,8 +21,10 @@ wherever the network places it. Flux app. A new or far-behind instance seeds from the best peer instead of syncing from block 0. Needs port 1337 mapped in the app spec. `PEER_BOOTSTRAP=0` disables seeding, `SNAPSHOT_PEERS="ip:port ..."` seeds from given peers. A peer serves two downloads at a time - and answers the rest busy; an instance replacing its own data deletes it only once a peer is - sending, so a busy or unreachable peer leaves it as it was. + and answers the rest busy. A download that breaks off continues from the file it was writing. + An instance keeps its own data until the download is complete, unless the disk cannot hold + both; then it deletes it only once a peer is sending, so a busy or unreachable peer leaves it + as it was. - `heal.sh` runs `reconsiderblock` when the daemon has marked the network's chain invalid and stopped on its last good block. - Blockbook stops cleanly (`patches/0002`). It closed its ZMQ socket from another thread while a diff --git a/build.sh b/build.sh index 650bca9..3848540 100644 --- a/build.sh +++ b/build.sh @@ -40,17 +40,18 @@ if [[ "$DAEMON_CONFIG" == "AUTO" && -f $PKG/server.conf && ! -f /root/$CONFIG_DI echo -e "| Installing $CONFIG_FILE.conf" cp $PKG/server.conf /root/$CONFIG_DIR/$CONFIG_FILE.conf touch /root/$CONFIG_DIR/.conf_fresh - # The template's dbcache=1000 and maxmempool=2000 (MB) are for a dedicated - # server: in a 4 GB app viacoind grew past the limit and was killed every - # hour or two, losing the cache it had not flushed. At most 1/8 of the - # container's memory each. - MEM_MAX=$(cat /sys/fs/cgroup/memory.max 2>/dev/null) - if [[ "$MEM_MAX" =~ ^[0-9]+$ ]]; then - CACHE_MB=$(( MEM_MAX / 8 / 1048576 )) - (( CACHE_MB < 300 )) && CACHE_MB=300 - awk -F= -v OFS== -v cap=$CACHE_MB '($1 == "dbcache" || $1 == "maxmempool") && $2 > cap { $2 = cap } 1' \ - /root/$CONFIG_DIR/$CONFIG_FILE.conf > /tmp/conf && mv /tmp/conf /root/$CONFIG_DIR/$CONFIG_FILE.conf - fi +fi +# The template's dbcache=1000 and maxmempool=2000 (MB) are for a dedicated +# server: in a 4 GB app viacoind grew past the limit and was killed every hour +# or two, losing the cache it had not flushed. At most 1/8 of the container's +# memory each, on every start: an image with the same blockbook and coin config +# does not render the config again. +MEM_MAX=$(cat /sys/fs/cgroup/memory.max 2>/dev/null) +if [[ "$DAEMON_CONFIG" == "AUTO" && -f /root/$CONFIG_DIR/$CONFIG_FILE.conf && "$MEM_MAX" =~ ^[0-9]+$ ]]; then + CACHE_MB=$(( MEM_MAX / 8 / 1048576 )) + (( CACHE_MB < 300 )) && CACHE_MB=300 + awk -F= -v OFS== -v cap=$CACHE_MB '($1 == "dbcache" || $1 == "maxmempool") && $2 > cap { $2 = cap } 1' \ + /root/$CONFIG_DIR/$CONFIG_FILE.conf > /tmp/conf && mv /tmp/conf /root/$CONFIG_DIR/$CONFIG_FILE.conf fi echo "$IMAGE_VERSION" > /root/.image_version diff --git a/snapshot.sh b/snapshot.sh index 1d82455..39567a8 100755 --- a/snapshot.sh +++ b/snapshot.sh @@ -147,8 +147,9 @@ function peers() { else spec=$(curl -sf -m 20 $API/apps/appspecifications/$FLUX_APP_NAME) || return 1 port=${SNAPSHOT_PORT:-$(jq -r '(.data.compose // [.data]) | map(select(((.containerPorts // []) | map(tostring) | index("1337")) != null)) - | .[0] | .ports[((.containerPorts | map(tostring) | index("1337")))] // empty' <<< "$spec")} - [[ -n "$port" ]] || { log "bootstrap: the app spec maps no port to 1337, no peer snapshots"; return 2; } + | .[0] // empty | .ports[((.containerPorts | map(tostring) | index("1337")))] // empty' <<< "$spec")} + # stderr: what this prints is the list of peers + [[ -n "$port" ]] || { log "bootstrap: the app spec maps no port to 1337, no peer snapshots" >&2; return 2; } endpoints=$(curl -sf -m 20 $API/apps/location/$FLUX_APP_NAME | jq -r '.data[].ip' | cut -d: -f1 | sort -u \ | grep -vxF "$FLUX_NODE_HOST_IP" | sed "s/\$/:$port/") fi @@ -167,26 +168,49 @@ function peers() { # sending (it has sent info.json, the tar's first member), $4... = members # expected in the tar. A peer that is busy or gone sends nothing, so local data # that $3 makes room by deleting is kept unless the download really started. +# +# A download that breaks off continues from the member it was writing: a peer +# whose router dropped every connection once an hour sent the first 12 minutes +# of a 313 GB snapshot to the same two instances over and over, and they held +# both of its slots. It gives up after 3 tries in a row that get nowhere. function download() { local peer=$1 path=$2 on_start=$3 shift 3 rm -rf $TMP $TMP.rc && mkdir -p $TMP log "bootstrap: downloading http://$peer$path" - ( curl -sf --connect-timeout 15 --speed-limit 51200 --speed-time 600 http://$peer$path | tar -x -C $TMP - echo "${PIPESTATUS[@]}" > $TMP.rc ) & - local pid=$! - if [[ -n "$on_start" ]]; then - while kill -0 $pid 2> /dev/null && [[ ! -e $TMP/info.json ]]; do sleep 1; done - [[ -e $TMP/info.json ]] && $on_start - fi - wait $pid - local rc=($(cat $TMP.rc 2> /dev/null)) - rm -f $TMP.rc - if [[ "${rc[0]}" != "0" || "${rc[1]}" != "0" ]]; then - log "bootstrap: download from $peer failed (curl ${rc[0]}, tar ${rc[1]})" - rm -rf $TMP - return 1 - fi + local offset=0 query="" stalls=0 rc last + while true; do + ( curl -sf --connect-timeout 15 --speed-limit 51200 --speed-time 600 "http://$peer$path$query" | tar -xv -R -C $TMP > $TMP.blocks + echo "${PIPESTATUS[@]}" > $TMP.rc ) & + local pid=$! + if [[ -n "$on_start" ]]; then + while kill -0 $pid 2> /dev/null && [[ ! -e $TMP/info.json ]]; do sleep 1; done + [[ -e $TMP/info.json ]] && $on_start && on_start="" + fi + wait $pid + rc=($(cat $TMP.rc 2> /dev/null)) + rm -f $TMP.rc + # Done when tar read the end of the archive. tar stops there, so curl may + # still fail writing the padding after it (23) once a try started mid-record. + [[ "${rc[1]}" == "0" ]] && grep -q '^block [0-9]*: \*\* Block of NULs \*\*' $TMP.blocks && break + # tar -R prints "block N: path" for each member, N being the block after its + # header; the last one may be cut short, so the next try sends it again. + last=$(awk '/^block [0-9]+: / && !/: \*\*/ { n = $2 + 0 } END { print n + 0 }' $TMP.blocks) + if (( last > 1 )); then + offset=$(( offset + (last - 1) * 512 )) stalls=0 + fi + # A peer that sent nothing (busy, gone) is left for the next one at once; a + # peer without resume support answers 404 to the query, 3 times. + if [[ ! -f $TMP/info.json ]] || (( last <= 1 && ++stalls >= 3 )); then + log "bootstrap: download from $peer failed (curl ${rc[0]}, tar ${rc[1]})" + rm -rf $TMP $TMP.blocks + return 1 + fi + query="?from=$offset&created=$(jq -r .created $TMP/info.json)" + log "bootstrap: download from $peer broke off (curl ${rc[0]}, tar ${rc[1]}), continuing at byte $offset" + sleep 30 + done + rm -f $TMP.blocks for m in "$@"; do [[ -e $TMP/$m ]] || { log "bootstrap: $peer sent no $m"; return 1; } done @@ -247,17 +271,24 @@ function restore() { log "bootstrap: local data ($local_backend + $local_bb bytes) is close to $peer's snapshot, keeping it" return 0 fi + # Local data is deleted when the download starts only if the disk cannot + # hold both: a reseed that broke off had cost a ZEC instance an index of + # 2.67M blocks it was still adding to. + local make_room="" if [[ "$force" != "1" ]] && (( local_backend * 10 >= backend_bytes * 9 )); then log "bootstrap: backend is synced but the index is far behind, taking only the index from $peer" (( $(free_bytes) + local_bb > bb_bytes * 11 / 10 )) || { log "bootstrap: not enough disk"; return 0; } - download $peer /snapshot-blockbook.tar clear_index blockbook-db/CURRENT || continue + (( $(free_bytes) > bb_bytes * 11 / 10 )) || make_room=clear_index + download $peer /snapshot-blockbook.tar "$make_room" blockbook-db/CURRENT || continue rm -rf $BBDB && mv $TMP/blockbook-db $BBDB && rm -rf $TMP log "bootstrap: index restored from $peer at height $height" return 0 fi (( $(free_bytes) + local_backend + local_bb > total * 11 / 10 )) || { log "bootstrap: not enough disk for $total bytes"; return 0; } - download $peer /snapshot.tar clear_chain backend blockbook-db/CURRENT || continue + (( $(free_bytes) > total * 11 / 10 )) || make_room=clear_chain + download $peer /snapshot.tar "$make_room" backend blockbook-db/CURRENT || continue # Only the chain data is replaced; configs, wallet and logs stay. + clear_chain cp -al $TMP/backend/. $BACKEND/ && rm -rf $BBDB && mv $TMP/blockbook-db $BBDB && rm -rf $TMP echo -e "Bootstrap [LOCKED] from peer $peer" > /root/BOOTSTRAP_LOCKED log "bootstrap: restored from $peer at height $height" diff --git a/snapshot_server.py b/snapshot_server.py index 2ae96c4..0ed228f 100755 --- a/snapshot_server.py +++ b/snapshot_server.py @@ -5,6 +5,11 @@ GET /snapshot.tar backend + blockbook-db, streamed as a tar GET /snapshot-blockbook.tar blockbook-db only +?from=&created= continues a download that broke off: +the tar is built the same way every time (sorted by name), so the stream from +that byte on is what the first one would have sent, as long as the snapshot is +the same one (409 if it was replaced). + The tar downloads are only for addresses that run the same Flux app (they are tens to hundreds of GB of the node operator's bandwidth), and only a couple at a time. @@ -17,6 +22,7 @@ import subprocess import threading import time +import urllib.parse import urllib.request SNAP = os.environ.get('SNAPSHOT_DIR', '/root/snapshot') @@ -44,12 +50,14 @@ def app_ips(): class Handler(http.server.BaseHTTPRequestHandler): def do_GET(self): - if self.path == '/snapshot/info.json': + url = urllib.parse.urlsplit(self.path) + query = urllib.parse.parse_qs(url.query) + if url.path == '/snapshot/info.json': return self.send_file(os.path.join(SNAP, 'info.json')) - if self.path == '/snapshot.tar': - return self.send_tar(['info.json', 'backend', 'blockbook-db']) - if self.path == '/snapshot-blockbook.tar': - return self.send_tar(['info.json', 'blockbook-db']) + if url.path == '/snapshot.tar': + return self.send_tar(['info.json', 'backend', 'blockbook-db'], query) + if url.path == '/snapshot-blockbook.tar': + return self.send_tar(['info.json', 'blockbook-db'], query) self.send_error(404) def send_file(self, path): @@ -64,12 +72,18 @@ def send_file(self, path): self.end_headers() self.wfile.write(body) - def send_tar(self, members): + def send_tar(self, members, query): client = self.client_address[0] if not PUBLIC and client not in app_ips(): return self.send_error(403, f'{client} does not run {APP}') - if not os.path.exists(os.path.join(SNAP, 'info.json')): + try: + with open(os.path.join(SNAP, 'info.json')) as f: + created = str(json.load(f)['created']) + start = int(query.get('from', ['0'])[0]) + except (OSError, ValueError, KeyError): return self.send_error(404, 'no snapshot') + if start and query.get('created', [''])[0] != created: + return self.send_error(409, 'the snapshot was replaced, start over') if not slots.acquire(blocking=False): return self.send_error(503, 'busy, try another peer') # snapshot.sh create does not replace a snapshot while this exists. @@ -81,8 +95,13 @@ def send_tar(self, members): self.send_response(200) self.send_header('Content-Type', 'application/x-tar') self.end_headers() - tar = subprocess.Popen(['tar', '-C', SNAP, '-cf', '-', *members], + tar = subprocess.Popen(['tar', '-C', SNAP, '--sort=name', '-cf', '-', *members], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + while start > 0: + skipped = len(tar.stdout.read(min(start, 1 << 20))) + if not skipped: + break + start -= skipped shutil.copyfileobj(tar.stdout, self.wfile, 1 << 20) tar.wait() print(f'{client} finished {self.path}', flush=True) diff --git a/test/smoke.sh b/test/smoke.sh index fc14f98..dd6e7b8 100755 --- a/test/smoke.sh +++ b/test/smoke.sh @@ -100,6 +100,13 @@ echo "$RESEED" grep -q "every peer download failed" <<< "$RESEED" || { echo "FAILED: B did not try the busy peer"; exit 1; } wait_for 300 "B: kept its index after a failed reseed" height_is bb-b 150 [[ "$(cli bb-b getblockcount)" == "150" ]] +# A download that broke off continues: the stream from a byte on is the tail of +# the whole one, unless the snapshot was replaced in between. +CREATED=$(docker exec bb-a jq -r .created /root/snapshot/info.json) +docker exec bb-b bash -c "cmp <(curl -sf http://$A_IP:1337/snapshot.tar | tail -c +10241) \ + <(curl -sf 'http://$A_IP:1337/snapshot.tar?from=10240&created=$CREATED')" \ + || { echo "FAILED: a continued download differs from the whole one"; exit 1; } +[[ "$(docker exec bb-b curl -s -o /dev/null -w '%{http_code}' "http://$A_IP:1337/snapshot.tar?from=10240&created=1")" == "409" ]] # supervisorctl stop returns only once the daemon has exited: bitcoind renames # itself b-shutoff while it flushes, and a wait on its name returned too early.