#!/usr/bin/env bash
# ============================================================
#  BigCoin easy solo miner (Linux)
#  Guide: http://133.242.139.204/mining
#
#  Usage:
#    ./mine-bigcoin.sh          # mine with (CPU cores - 1) workers
#    ./mine-bigcoin.sh 4        # mine with exactly 4 workers
#
#  Put this script in the folder you extracted (next to bitcoind)
#  and run it. It does all of the following for you:
#    1. start the node (chain data goes into ./data)
#    2. wait until the chain is synced
#    3. create a wallet and mining addresses (reused on restart)
#    4. mine until you press Ctrl-C
#
#  Nothing is sent anywhere. Every command this script runs is a
#  local RPC call to the bitcoind sitting next to it, and the keys
#  it creates never leave ./data. Read it before running it.
#
#  NOTE: if you are on a rented server, check your provider's terms
#  first - many shared VPS hosts prohibit mining. Running a node
#  without mining is almost always fine.
# ============================================================
set -uo pipefail

# ── Work from the script's own directory, however it was invoked ──
cd "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" || exit 1

DAEMON=./bitcoind
CLI=./bigcoin-cli
DATADIR="$PWD/data"
DD="-datadir=$DATADIR"
CONF="$DATADIR/bitcoin.conf"
ADDRFILE="$DATADIR/mining-addresses.txt"
SEED=133.242.139.204:8338

# ── Nonce budget for a single generatetoaddress call ──────────────
# The call is synchronous: it grinds up to this many nonces on one
# template and returns. The budget is a time budget in disguise, and
# both ends of it hurt.
#
#   Too large: the worker keeps hashing a template whose previous
#     block is no longer the tip (the call does not notice a new
#     chain tip while it runs), so a block found late in the call
#     can be orphaned. At a 600 s target spacing, a 30 s call is
#     about a 5 % chance of ending up stale.
#   Too small: the node rebuilds a template for every call, and the
#     worker sits idle during the round trip.
#
# It is also a hard correctness constraint from BigCoin v1.7 on. A
# yespower hash costs about 3 ms, roughly 20,000 times a double-SHA256,
# so a budget sized for the old algorithm would hold one RPC call open
# for days - far past bigcoin-cli's own timeout, which would make the
# script report failures while the node kept grinding.
#
# So the budget is measured rather than assumed. Each worker times its
# own calls and resizes its budget to land near TARGET_SECONDS, which
# makes the script correct on a slow single-core box and on a 64-core
# machine, under either algorithm, without being told which.
TARGET_SECONDS=30
BUDGET_MIN=256
# 20,000,000 was the fixed budget of releases up to v1.6, and on a fast
# machine under double-SHA256 that is still only a few seconds, so the
# cap keeps the pre-fork behaviour people already know.
BUDGET_MAX=20000000
# Starting points, used only until the first call has been timed.
BUDGET_START_SHA256D=20000000
# About 13 s at the ~300 hashes/s per core that a current x86-64 core
# manages, and still inside bigcoin-cli's default 900 s timeout even on
# a core thirty times slower than that.
BUDGET_START_YESPOWER=4000
# Safety net for the very first call of an era, before any measurement
# exists. Nothing should ever come close to this.
MINE_TIMEOUT=3600

# ── Check the bundled binaries are here ──
if [ ! -x "$DAEMON" ] || [ ! -x "$CLI" ]; then
  echo "[ERROR] bitcoind / bigcoin-cli were not found in this folder."
  echo
  echo "Put mine-bigcoin.sh into the folder where you extracted the"
  echo "BigCoin Linux release, then run it again:"
  echo "    tar xzf bigcoin-linux-x64-v1.7.tar.gz"
  echo "    cd bigcoin"
  echo "    ./mine-bigcoin.sh"
  exit 1
fi

# ── Decide the worker count (argument wins over the default) ──
CORES=$(nproc 2>/dev/null || echo 1)
if [ "$#" -ge 1 ]; then
  WORKERS=$1
else
  # Leave one core for the OS. On a 1-2 core box use a single worker.
  if [ "$CORES" -le 2 ]; then WORKERS=1; else WORKERS=$((CORES - 1)); fi
fi
case "$WORKERS" in
  ''|*[!0-9]*|0) echo "[ERROR] worker count must be a positive integer"; exit 1 ;;
esac

# ── Prepare the data directory and the config file ──
# generatetoaddress holds one RPC thread for the whole duration of the
# call. bitcoind only serves 4 threads by default, so adding workers
# beyond that would just make them queue behind each other instead of
# mining in parallel. Reserve (workers + 4).
mkdir -p "$DATADIR"
NEED_THREADS=$((WORKERS + 4))
CONF_CHANGED=0
if [ ! -f "$CONF" ]; then
  {
    echo "# BigCoin node config (generated by mine-bigcoin.sh)"
    echo "server=1"
    echo "addnode=$SEED"
    echo "fallbackfee=0.0001"
    echo "# generatetoaddress holds one RPC thread, so: workers + 4"
    echo "rpcthreads=$NEED_THREADS"
  } > "$CONF"
else
  # Respect an existing config, but a too-small rpcthreads makes the
  # workers wait on each other instead of mining, so raise that one.
  CUR_THREADS=$(sed -n 's/^[[:space:]]*rpcthreads=\([0-9][0-9]*\).*/\1/p' "$CONF" | tail -1)
  if [ -z "$CUR_THREADS" ]; then
    # Terminate the last line first. A config the user edited by hand may not
    # end in a newline, and appending straight onto it would produce something
    # like "fallbackfee=0.0001rpcthreads=8" - one invalid option, and the node
    # then refuses to start at all. tail -c 1 inside $() comes back empty
    # exactly when that last byte is already a newline.
    if [ -s "$CONF" ] && [ -n "$(tail -c 1 "$CONF")" ]; then printf '\n' >> "$CONF"; fi
    echo "rpcthreads=$NEED_THREADS" >> "$CONF"
    CONF_CHANGED=1
  elif [ "$CUR_THREADS" -lt "$NEED_THREADS" ]; then
    sed -i "s/^[[:space:]]*rpcthreads=.*/rpcthreads=$NEED_THREADS/" "$CONF"
    CONF_CHANGED=1
  fi
fi

# ── Start the node (do nothing if one is already running) ──
NODE_WAS_RUNNING=0
if "$CLI" "$DD" getblockcount >/dev/null 2>&1; then
  NODE_WAS_RUNNING=1
  echo "A BigCoin node is already running on this data directory."
else
  echo "Starting the BigCoin node ..."
  "$DAEMON" "$DD" -daemon >/dev/null 2>&1
fi

if [ "$NODE_WAS_RUNNING" = "1" ] && [ "$CONF_CHANGED" = "1" ]; then
  echo
  echo "[NOTE] rpcthreads was raised to $NEED_THREADS in $CONF,"
  echo "       but the running node still uses the old value. To use all"
  echo "       $WORKERS workers at full speed, restart the node:"
  echo "           $CLI $DD stop   &&   sleep 5   &&   $0 $WORKERS"
  echo
fi

# ── Wait for RPC to answer ──
echo "Waiting for the node to accept commands ..."
TRIES=0
until "$CLI" "$DD" getblockcount >/dev/null 2>&1; do
  TRIES=$((TRIES + 1))
  if [ "$TRIES" -eq 24 ]; then
    echo
    echo "Still waiting. If another BigCoin node is already using"
    echo "$DATADIR, stop it first and run this script again."
    echo "Node log: $DATADIR/debug.log"
    echo
  fi
  if [ "$TRIES" -ge 120 ]; then
    echo "[ERROR] the node did not come up. See $DATADIR/debug.log"
    exit 1
  fi
  sleep 5
done

# ── Wait until there is nothing left to download ───────────────────
# Deliberately not just "wait for initialblockdownload to turn false".
# A node only leaves that state once its tip is less than a day old, and
# it never re-enters it afterwards - so the flag is a reliable "I have
# caught up" signal for a node that was already running, and a trap for
# one that is started while the chain itself is stalled. BigCoin stood
# still for 123 hours in November 2026. Anybody who had started this
# script during that window would have watched it print "synced up to
# block 17324" forever, because the tip was five days old and the flag
# never turned, and the chain would have been left without the one miner
# that could have ended the stall.
#
# So the wait ends on either of two conditions: the node says it has
# finished, or there is demonstrably nothing left to fetch - the block
# count has caught up with the header count, there is at least one peer
# to have heard that from, and nothing has moved for a minute.
echo "Node is up. Syncing the blockchain ..."
SETTLED=0
while :; do
  INFO=$("$CLI" "$DD" getblockchaininfo 2>/dev/null)
  case "$INFO" in
    *'"initialblockdownload": false'*) break ;;
  esac
  BLOCKS=$(printf '%s' "$INFO" | sed -n 's/.*"blocks": *\([0-9][0-9]*\).*/\1/p')
  HEADERS=$(printf '%s' "$INFO" | sed -n 's/.*"headers": *\([0-9][0-9]*\).*/\1/p')
  PEERS=$("$CLI" "$DD" getconnectioncount 2>/dev/null)
  # Order matters: the -n test has to pass before -gt sees the value, or
  # an empty answer from a busy node would be an arithmetic error rather
  # than simply "no news this round".
  if [ -n "$BLOCKS" ] && [ "$BLOCKS" = "$HEADERS" ] \
     && [ "$BLOCKS" -gt 0 ] && [ "${PEERS:-0}" -gt 0 ]; then
    SETTLED=$((SETTLED + 1))
  else
    SETTLED=0
  fi
  if [ "$SETTLED" -ge 12 ]; then
    echo
    echo "  Nothing left to download: block $BLOCKS is the newest block any"
    echo "  of the $PEERS connected peer(s) has, and it has not moved for a"
    echo "  minute. The chain is stalled, which is the moment it most needs"
    echo "  a miner, so this starts mining instead of waiting it out."
    echo
    break
  fi
  echo "  synced up to block ${BLOCKS:-?} of ${HEADERS:-?} ..."
  sleep 5
done

# ── Which algorithm the next block needs ──────────────────────────
# Asked of the node rather than hardcoded here, so that this script
# cannot disagree with consensus about where the switch happens.
# Returns "yespower", "sha256d", or empty if the node did not answer.
current_algo() {
  info=$("$CLI" "$DD" getblockchaininfo 2>/dev/null) || return 0
  case "$info" in
    *'"pow_algo": "yespower"'*) printf 'yespower' ;;
    *'"pow_algo": "sha256d"'*)  printf 'sha256d' ;;
  esac
}

budget_for_algo() {
  case "$1" in
    yespower) printf '%s' "$BUDGET_START_YESPOWER" ;;
    *)        printf '%s' "$BUDGET_START_SHA256D" ;;
  esac
}

# ── Prepare the mining wallet ──
"$CLI" "$DD" createwallet miner >/dev/null 2>&1
"$CLI" "$DD" loadwallet miner   >/dev/null 2>&1
if ! "$CLI" "$DD" -rpcwallet=miner getwalletinfo >/dev/null 2>&1; then
  echo "[ERROR] could not create or load the mining wallet."
  exit 1
fi

# ── One mining address per worker ─────────────────────────────────
# Why each worker needs its own address:
#   A generatetoaddress block template is fully determined by the
#   previous block, the height, the coinbase output and nTime - and
#   nTime only has one-second granularity. Two workers that start in
#   the same second on the same address therefore grind a byte-identical
#   header in the identical nonce order, and one of them does no useful
#   work at all. A different address means a different coinbase, hence a
#   different merkle root, hence a disjoint search space.
#   All the addresses belong to the same 'miner' wallet, so the balances
#   simply add up.
#
# Created once and stored in a file, then reused; new ones are only
# issued when the worker count grows.
touch "$ADDRFILE"
# Count non-blank lines. Not with grep -c: it prints "0" and *also*
# exits 1 when there is no match, which would poison the comparison.
# awk always succeeds.
HAVE=$(awk 'NF{c++} END{print c+0}' "$ADDRFILE")
while [ "$HAVE" -lt "$WORKERS" ]; do
  A=$("$CLI" "$DD" -rpcwallet=miner getnewaddress "mine$((HAVE + 1))")
  if [ -z "$A" ]; then
    echo "[ERROR] could not create a mining address."
    exit 1
  fi
  printf '%s\n' "$A" >> "$ADDRFILE"
  HAVE=$((HAVE + 1))
done

# Read them into an array (dropping trailing whitespace and any CR)
ADDRS=()
while IFS= read -r line; do
  line=$(printf '%s' "$line" | tr -d ' \t\r')
  [ -n "$line" ] && ADDRS+=("$line")
done < "$ADDRFILE"
if [ "${#ADDRS[@]}" -lt "$WORKERS" ]; then
  echo "[ERROR] only ${#ADDRS[@]} mining addresses available for $WORKERS workers."
  exit 1
fi

DIFF=$("$CLI" "$DD" getdifficulty 2>/dev/null || echo "?")
HEIGHT=$("$CLI" "$DD" getblockcount 2>/dev/null || echo "?")
INFO=$("$CLI" "$DD" getblockchaininfo 2>/dev/null)
ALGO=$(current_algo)
[ -z "$ALGO" ] && ALGO=sha256d
YP_HEIGHT=$(printf '%s' "$INFO" | sed -n 's/.*"yespower_activation_height": *\([0-9][0-9]*\).*/\1/p')

cat <<BANNER

============================================================
 Workers: $WORKERS (of $CORES CPU cores)   Height: $HEIGHT   Difficulty: $DIFF
 Wallet : miner   (all rewards land in this one wallet)
BANNER

if [ "$ALGO" = "yespower" ]; then
  cat <<BANNER
 Algorithm: yespower - a memory-hard function. Every hash needs
 2 MiB of fast memory, which is what keeps BigCoin on ordinary
 CPUs: an ASIC gains nothing it can spend on hashing here.
 Expect a few hundred hashes per second per core, not millions.
 The numbers below are the real rate of this machine.
BANNER
elif [ -n "$YP_HEIGHT" ] && [ "$HEIGHT" != "?" ]; then
  cat <<BANNER
 Algorithm: double-SHA256 now; yespower from block $YP_HEIGHT
 ($((YP_HEIGHT - HEIGHT)) blocks away). Nothing to do about it - this
 script switches by itself, because it asks the node which
 algorithm the next block needs.
BANNER
fi

cat <<BANNER

 Mining addresses - one per worker, so the workers do not
 search the same nonce range twice:
BANNER
i=0
while [ "$i" -lt "$WORKERS" ]; do
  printf '   w%-2s %s\n' "$((i + 1))" "${ADDRS[$i]}"
  i=$((i + 1))
done
cat <<BANNER

 Every block found pays 50 BIG. Rewards become spendable
 after 100 confirmations - roughly one day.

 Check your balance:
     $CLI $DD -rpcwallet=miner getbalances
 Back up your wallet (do this - the keys are only in ./data):
     $CLI $DD -rpcwallet=miner backupwallet /path/to/backup.dat

 Press Ctrl-C to stop mining. The node keeps running.
 To stop the node later:
     $CLI $DD stop
============================================================

BANNER

if [ "$ALGO" = "yespower" ] && [ "$WORKERS" -gt 1 ]; then
  cat <<'BANNER'
 [TIP] yespower is limited by memory bandwidth, not by clock
       speed, so more workers do not always mean more hashes.
       Watch the hashes/s line below, then try a smaller worker
       count (./mine-bigcoin.sh 4) and compare. Use whichever
       number is actually faster on your machine.

BANNER
fi

# ── The worker loop ──
# generatetoaddress is a synchronous RPC: it tries nonces up to the
# given ceiling and returns the block hash if it finds one, or an empty
# array if it does not.
# Mining itself does not use a wallet, so no -rpcwallet here - passing
# one would stop mining as well whenever the wallet gets unloaded.
mine_worker() {
  wid=$1
  addr=$2
  last_beat=0
  algo=$ALGO
  budget=$(budget_for_algo "$algo")
  rate=0
  while :; do
    # Re-ask before every call, not after: the first call of the
    # yespower era must not be sized with a double-SHA256 budget, or it
    # would run for days instead of seconds.
    now_algo=$(current_algo)
    if [ -n "$now_algo" ] && [ "$now_algo" != "$algo" ]; then
      algo=$now_algo
      budget=$(budget_for_algo "$algo")
      rate=0
      if [ "$wid" = "1" ]; then
        printf '[%s] *** proof-of-work algorithm is now %s - resizing ***\n' \
               "$(date +%H:%M:%S)" "$algo"
      fi
    fi

    t0=$(date +%s)
    if ! out=$("$CLI" "$DD" "-rpcclienttimeout=$MINE_TIMEOUT" \
                     generatetoaddress 1 "$addr" "$budget" 2>&1); then
      printf '[%s] w%-2s node not reachable - retrying in 15s\n' "$(date +%H:%M:%S)" "$wid"
      sleep 15
      continue
    fi
    elapsed=$(( $(date +%s) - t0 ))

    # A 64-hex string in quotes is a block hash. Not just any 64 hex
    # characters: from v1.7 on the hash a found block reports is its
    # identity (double-SHA256), which no longer has to start with
    # zeros, so matching on leading zeros would silently miss blocks.
    if printf '%s' "$out" | grep -qE '"[0-9a-f]{64}"'; then
      printf '[%s] w%-2s *** BLOCK FOUND - 50 BIG credited to your wallet ***\n' "$(date +%H:%M:%S)" "$wid"
      # The call returned early, so it says nothing about speed.
      continue
    fi

    # No block: the budget was spent in full, so this is an exact
    # measurement of this worker's hash rate. Resize towards
    # TARGET_SECONDS. Calls shorter than a second are not measurable at
    # this clock resolution and are left alone.
    if [ "$elapsed" -ge 1 ]; then
      rate=$(( budget / elapsed ))
      budget=$(( rate * TARGET_SECONDS ))
      [ "$budget" -lt "$BUDGET_MIN" ] && budget=$BUDGET_MIN
      [ "$budget" -gt "$BUDGET_MAX" ] && budget=$BUDGET_MAX
    fi

    if [ "$wid" = "1" ]; then
      # If every worker reported, the log would be unreadable, so only
      # worker 1 prints a heartbeat and only once a minute.
      now=$(date +%s)
      if [ "$((now - last_beat))" -ge 60 ]; then
        last_beat=$now
        h=$("$CLI" "$DD" getblockcount 2>/dev/null || echo "?")
        d=$("$CLI" "$DD" getdifficulty 2>/dev/null || echo "?")
        if [ "$rate" -gt 0 ]; then
          printf '[%s] mining ... height=%s difficulty=%s algo=%s %s hashes/s/worker (~%s total over %s workers)\n' \
                 "$(date +%H:%M:%S)" "$h" "$d" "$algo" "$rate" "$((rate * WORKERS))" "$WORKERS"
        else
          printf '[%s] mining ... height=%s difficulty=%s algo=%s workers=%s\n' \
                 "$(date +%H:%M:%S)" "$h" "$d" "$algo" "$WORKERS"
        fi
      fi
    fi
  done
}

PIDS=""
cleanup() {
  echo
  echo "Stopping miners ..."
  for p in $PIDS; do kill "$p" 2>/dev/null; done
  wait 2>/dev/null
  echo "Miners stopped. The node is still running."
  echo "To stop the node:  $CLI $DD stop"
  exit 0
}
trap cleanup INT TERM

i=0
while [ "$i" -lt "$WORKERS" ]; do
  mine_worker "$((i + 1))" "${ADDRS[$i]}" &
  PIDS="$PIDS $!"
  i=$((i + 1))
done
wait
