#!/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 ceiling for a single generatetoaddress call.
# Too high and a worker keeps grinding a stale template after someone
# else has already found the block (the call does not notice a new
# chain tip while it runs). Too low and we rebuild templates too often.
# 20,000,000 is about 40 s at 0.5 MH/s and about 4 s at 5 MH/s.
MAXTRIES=20000000

# ── 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.5.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
    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 the initial block download is finished ──
echo "Node is up. Syncing the blockchain ..."
while :; do
  INFO=$("$CLI" "$DD" getblockchaininfo 2>/dev/null)
  case "$INFO" in
    *'"initialblockdownload": false'*) break ;;
  esac
  HEIGHT=$("$CLI" "$DD" getblockcount 2>/dev/null || echo "?")
  echo "  synced up to block $HEIGHT ..."
  sleep 5
done

# ── 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 "?")

cat <<BANNER

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

 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

# ── 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
  while :; do
    if ! out=$("$CLI" "$DD" generatetoaddress 1 "$addr" "$MAXTRIES" 2>&1); then
      printf '[%s] w%-2s node not reachable - retrying in 15s\n' "$(date +%H:%M:%S)" "$wid"
      sleep 15
      continue
    fi
    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"
    elif [ "$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 "?")
        printf '[%s] mining ... height=%s difficulty=%s workers=%s\n' \
               "$(date +%H:%M:%S)" "$h" "$d" "$WORKERS"
      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
