@echo off
setlocal enabledelayedexpansion
rem ============================================================
rem  BigCoin easy solo miner (Windows)
rem  Guide: http://133.242.139.204/mining
rem
rem  Usage:
rem    mine-bigcoin.cmd          mine with (CPU cores - 1) workers
rem    mine-bigcoin.cmd 4        mine with exactly 4 workers
rem
rem  Put this file in the folder where you extracted the
rem  BigCoin-win64 release zip, next to bitcoind.exe, and
rem  double-click it. It will:
rem    1. start a BigCoin node, chain data goes to the "data"
rem       subfolder of this directory
rem    2. wait until the blockchain is synced
rem    3. create a wallet and one mining address per worker,
rem       reused on later runs
rem    4. mine until you close this window
rem
rem  Nothing is sent anywhere. Every command this script runs is
rem  a local RPC call to the bitcoind sitting next to it, and the
rem  keys it creates never leave the data folder. Read it before
rem  running it.
rem
rem  Stop mining: close this window.
rem  Stop node  : bigcoin-cli.exe -datadir=data stop
rem ============================================================

cd /d "%~dp0"

set "DD=-datadir=%~dp0data"
set "SEED=133.242.139.204:8338"

rem ---- Nonce budget for a single generatetoaddress call --------
rem The call is synchronous: it grinds up to this many nonces on
rem one template and returns. The budget is a time budget in
rem disguise, and both ends of it hurt.
rem
rem   Too large: the worker keeps hashing a template whose
rem     previous block is no longer the tip, because the call does
rem     not notice a new chain tip while it runs, so a block found
rem     late in the call can be orphaned. At a 600 s target
rem     spacing, a 30 s call is about a 5 percent risk of that.
rem   Too small: the node rebuilds a template for every call and
rem     the worker sits idle during the round trip.
rem
rem From BigCoin v1.7 on it is also a hard correctness constraint.
rem A yespower hash costs about 3 ms, roughly 20,000 times a
rem double-SHA256, so the fixed 100,000,000 of releases up to v1.6
rem would hold one call open for days - far past bigcoin-cli's own
rem timeout, which would make this script report failures while
rem the node kept grinding.
rem
rem So the budget is measured rather than assumed. Each worker
rem times its own calls and resizes towards TARGET_SECONDS, which
rem makes the script correct on a slow single-core box and on a
rem 32-core machine, under either algorithm, without being told
rem which one is in force.
set "TARGET_SECONDS=30"
set "BUDGET_MIN=256"
set "BUDGET_MAX=20000000"
rem Starting points, used only until the first call has been timed.
set "BUDGET_START_SHA256D=20000000"
rem About 13 s at the few hundred hashes per second per core that a
rem current x86-64 core manages at yespower.
set "BUDGET_START_YESPOWER=4000"
rem Safety net for the very first call of an era, before any
rem measurement exists. Nothing should ever come close to this.
set "MINE_TIMEOUT=3600"

rem Workers are separate copies of this script, started by the
rem first one. They skip all of the setup below.
if /i "%~1"=="worker" goto worker

if not exist "bitcoind.exe" (
  echo [ERROR] bitcoind.exe was not found in this folder.
  echo.
  echo Put mine-bigcoin.cmd into the folder where you extracted
  echo BigCoin-win64-v1.7.zip, then run it again.
  pause
  exit /b 1
)
if not exist "bigcoin-cli.exe" (
  echo [ERROR] bigcoin-cli.exe was not found in this folder.
  pause
  exit /b 1
)

rem ---- Decide the worker count, argument wins over the default --
set "CORES=%NUMBER_OF_PROCESSORS%"
if "%CORES%"=="" set "CORES=1"
if "%~1"=="" goto autoworkers
set "WORKERS=%~1"
rem Digits only, no leading zero, at most three of them. Deliberately
rem not "echo %WORKERS%| findstr": on that line cmd binds both
rem redirections to echo, the left side of the pipe, so findstr reads
rem an empty stream and rejects every value the user types. A for /f
rem with the digits as its delimiters needs neither a pipe nor a
rem redirection: an all-digit string is entirely delimiters and yields
rem no token at all, so the body only runs when something else is in
rem there. The length and leading-zero rules are what make the
rem comparison below a numeric one - cmd falls back to comparing
rem strings as soon as either side does not fit in 32 bits.
set "WBAD="
for /f "delims=0123456789" %%Z in ("%WORKERS%") do set "WBAD=1"
if defined WBAD goto badworkers
if "%WORKERS:~0,1%"=="0" goto badworkers
if not "%WORKERS:~3%"=="" goto badworkers
if %WORKERS% gtr 256 goto badworkers
goto haveworkers

:badworkers
echo [ERROR] worker count must be a whole number from 1 to 256.
echo.
echo Usage:  mine-bigcoin.cmd       use ^(CPU cores - 1^) workers
echo         mine-bigcoin.cmd 4     use exactly 4 workers
pause
exit /b 1

:autoworkers
rem Leave one core for the OS. On a 1-2 core box use a single worker.
if %CORES% leq 2 (set "WORKERS=1") else (set /a WORKERS=%CORES%-1)

:haveworkers

rem ---- Data directory and config file -------------------------
rem generatetoaddress holds one RPC thread for the whole duration
rem of the call. bitcoind only serves 4 threads by default, so
rem workers beyond that would queue behind each other instead of
rem mining in parallel. Reserve workers + 4.
if not exist "%~dp0data" mkdir "%~dp0data"
set "CONF=%~dp0data\bitcoin.conf"
set /a NEED_THREADS=%WORKERS%+4
set "CONF_NOTE="
if exist "%CONF%" goto haveconf
>"%CONF%"  echo # BigCoin node config, generated by mine-bigcoin.cmd
>>"%CONF%" echo server=1
>>"%CONF%" echo addnode=%SEED%
>>"%CONF%" echo fallbackfee=0.0001
>>"%CONF%" echo # generatetoaddress holds one RPC thread, so: workers + 4
>>"%CONF%" echo rpcthreads=!NEED_THREADS!
goto confdone

:haveconf
rem An existing config belongs to the user, so it is never
rem rewritten here - only completed. A too-small rpcthreads makes
rem the workers wait on each other instead of mining, so say so.
set "CUR_THREADS="
for /f "usebackq tokens=2 delims==" %%T in (`findstr /r /c:"^[ 	]*rpcthreads=" "%CONF%" 2^>nul`) do set "CUR_THREADS=%%T"
if "!CUR_THREADS!"=="" (
  rem The blank line first. A config file the user edited by hand may not end
  rem in a newline, and appending straight onto it would produce something like
  rem "fallbackfee=0.0001rpcthreads=8" - one invalid option, and the node then
  rem refuses to start at all. An extra empty line is harmless; a welded line
  rem is not. Batch cannot read the last byte of a file, so it is written
  rem unconditionally.
  >>"%CONF%" echo.
  >>"%CONF%" echo rpcthreads=!NEED_THREADS!
  set "CONF_NOTE=added"
  goto confdone
)
set "CUR_THREADS=!CUR_THREADS: =!"
if !CUR_THREADS! lss !NEED_THREADS! set "CONF_NOTE=small"

:confdone

rem ---- Start the node, or leave a running one alone ------------
set "NODE_WAS_RUNNING=0"
>nul 2>&1 bigcoin-cli.exe "%DD%" getblockcount
if errorlevel 1 goto startnode
set "NODE_WAS_RUNNING=1"
echo A BigCoin node is already running on this data directory.
goto waitrpc

:startnode
echo Starting the BigCoin node ...
start "BigCoin node" /min bitcoind.exe "%DD%"

:waitrpc
echo Waiting for the node to accept commands ...
set /a TRIES=0
:waitrpcloop
>nul 2>&1 bigcoin-cli.exe "%DD%" getblockcount
if not errorlevel 1 goto rpcup
set /a TRIES+=1
if !TRIES! equ 24 (
  echo.
  echo Still waiting. If BigCoin Core or bigcoin-qt is already
  echo running on this PC, close it first and run this again.
  echo Node log: %~dp0data\debug.log
  echo.
)
if !TRIES! geq 120 (
  echo [ERROR] the node did not come up. See %~dp0data\debug.log
  pause
  exit /b 1
)
rem Five seconds. Not with timeout.exe: it reads the console input handle and
rem dies with "input redirection is not supported" whenever this script is
rem piped, redirected or started from another process. ping always works.
>nul ping -n 6 127.0.0.1
goto waitrpcloop

:rpcup
if "!CONF_NOTE!"=="" goto nonote
if "!NODE_WAS_RUNNING!"=="0" goto nonote
echo.
if "!CONF_NOTE!"=="added" echo [NOTE] rpcthreads=!NEED_THREADS! was added to the config file,
if "!CONF_NOTE!"=="small" echo [NOTE] rpcthreads in the config file is !CUR_THREADS!, below !NEED_THREADS!,
echo        but the running node still uses the old value. To use
echo        all !WORKERS! workers at full speed, restart the node:
echo            bigcoin-cli.exe -datadir=data stop
echo        then run this script again.
echo.
:nonote

rem ---- Wait until there is nothing left to download ------------
rem Deliberately not just "wait for initialblockdownload to turn false".
rem A node only leaves that state once its tip is less than a day old,
rem and it never re-enters it afterwards - so the flag is a reliable
rem "I have caught up" signal for a node that was already running, and a
rem trap for one that is started while the chain itself is stalled.
rem BigCoin stood still for 123 hours in November 2026. Anybody who had
rem started this script during that window would have watched it print
rem "synced up to block 17324" forever, because the tip was five days old
rem and the flag never turned, and the chain would have been left without
rem the one miner that could have ended the stall.
rem
rem So the wait ends on either of two conditions: the node says it has
rem finished, or there is demonstrably nothing left to fetch - the block
rem count has caught up with the header count, there is at least one peer
rem to have heard that from, and nothing has moved for a minute.
echo Node is up. Syncing the blockchain ...
set "SETTLED=0"
:waitsync
bigcoin-cli.exe "%DD%" getblockchaininfo 2>nul | findstr /r /c:"initialblockdownload.*false" >nul
if not errorlevel 1 goto synced
rem Read both counts out of one call. No findstr and no second pipe: the
rem field name arrives as token 1 still carrying its JSON quotes, so
rem comparing it against a quoted literal needs no escaping at all.
set "BLOCKS=?"
set "HEADERS=?"
set "PEERS=0"
for /f "usebackq tokens=1,2 delims=:, " %%K in (`bigcoin-cli.exe "%DD%" getblockchaininfo 2^>nul`) do (
  if %%K=="blocks"  set "BLOCKS=%%L"
  if %%K=="headers" set "HEADERS=%%L"
)
for /f "usebackq delims=" %%P in (`bigcoin-cli.exe "%DD%" getconnectioncount 2^>nul`) do set "PEERS=%%P"
if "!BLOCKS!"=="?" goto notsettled
if not "!BLOCKS!"=="!HEADERS!" goto notsettled
if !BLOCKS! leq 0 goto notsettled
if !PEERS! leq 0 goto notsettled
set /a SETTLED+=1
goto settledcheck
:notsettled
set "SETTLED=0"
:settledcheck
if !SETTLED! geq 12 goto stalled
echo   synced up to block !BLOCKS! of !HEADERS! ...
>nul ping -n 6 127.0.0.1
goto waitsync

:stalled
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.

:synced

rem ---- Mining wallet ------------------------------------------
>nul 2>&1 bigcoin-cli.exe "%DD%" createwallet miner
>nul 2>&1 bigcoin-cli.exe "%DD%" loadwallet miner
>nul 2>&1 bigcoin-cli.exe "%DD%" -rpcwallet=miner getwalletinfo
if errorlevel 1 (
  echo [ERROR] could not create or load the mining wallet.
  pause
  exit /b 1
)

rem ---- One mining address per worker --------------------------
rem Why each worker needs its own address:
rem   A generatetoaddress template is fully determined by the
rem   previous block, the height, the coinbase output and nTime -
rem   and nTime only has one-second granularity. Two workers that
rem   start in the same second on the same address therefore grind
rem   a byte-identical header in the identical nonce order, and one
rem   of them does no useful work at all. A different address means
rem   a different coinbase, hence a different merkle root, hence a
rem   disjoint search space.
rem   All the addresses belong to the same 'miner' wallet, so the
rem   balances simply add up.
rem
rem Created once, stored in a file and reused; new ones are only
rem issued when the worker count grows.
set "ADDRFILE=%~dp0data\mining-addresses.txt"
if not exist "%ADDRFILE%" >"%ADDRFILE%" break
set /a NADDR=0
for /f "usebackq tokens=* delims=" %%A in ("%ADDRFILE%") do call :addaddr "%%A"
:addrloop
if !NADDR! geq !WORKERS! goto addrdone
set /a NEXTN=!NADDR!+1
set "NEWADDR="
rem "-rpcwallet=miner" has to stay quoted here. A for /f backtick
rem command is re-parsed by a second cmd, and that pass treats the
rem bare = as a token separator: the option arrives as -rpcwallet
rem with no value, getnewaddress is swallowed as the wallet name and
rem the label becomes the method, so the node answers "Method not
rem found" and this loop sees an empty line. -datadir survives only
rem because %DD% is already quoted.
for /f "usebackq delims=" %%A in (`bigcoin-cli.exe "%DD%" "-rpcwallet=miner" getnewaddress mine!NEXTN! 2^>nul`) do set "NEWADDR=%%A"
if "!NEWADDR!"=="" (
  echo [ERROR] could not create a mining address.
  pause
  exit /b 1
)
>>"%ADDRFILE%" echo !NEWADDR!
call :addaddr "!NEWADDR!"
goto addrloop
:addrdone

rem ---- What the chain is doing right now ----------------------
set "HEIGHT=?"
set "DIFFI=?"
set "YPH="
for /f "usebackq delims=" %%H in (`bigcoin-cli.exe "%DD%" getblockcount 2^>nul`) do set "HEIGHT=%%H"
for /f "usebackq delims=" %%D in (`bigcoin-cli.exe "%DD%" getdifficulty 2^>nul`) do set "DIFFI=%%D"
for /f "usebackq tokens=2 delims=:," %%V in (`bigcoin-cli.exe "%DD%" getblockchaininfo 2^>nul ^| findstr /r /c:"yespower_activation_height"`) do set "YPH=%%V"
if not "!YPH!"=="" set "YPH=!YPH: =!"
call :probealgo
set "ALGO=!NOWALGO!"

echo.
echo ============================================================
echo  Workers: !WORKERS! of %CORES% CPU cores   Height: !HEIGHT!   Difficulty: !DIFFI!
echo  Wallet : miner   - all rewards land in this one wallet
if /i "!ALGO!"=="yespower" goto banneryp
if "!YPH!"=="" goto banneralgodone
if "!HEIGHT!"=="?" goto banneralgodone
set /a YPAWAY=!YPH!-!HEIGHT!
echo.
echo  Algorithm: double-SHA256 now, yespower from block !YPH!,
echo  !YPAWAY! blocks away. Nothing to do about it - this script
echo  switches by itself, because it asks the node which
echo  algorithm the next block needs.
goto banneralgodone
:banneryp
echo.
echo  Algorithm: yespower, a memory-hard function. Every hash
echo  needs 2 MiB of fast memory, which is what keeps BigCoin on
echo  ordinary CPUs: an ASIC gains nothing it can spend on
echo  hashing here. Expect a few hundred hashes per second per
echo  core, not millions. The numbers below are the real rate of
echo  this machine.
:banneralgodone
echo.
echo  Mining addresses - one per worker, so the workers do not
echo  search the same nonce range twice:
set /a I=0
:bannerloop
set /a I+=1
if !I! gtr !WORKERS! goto bannerdone
call set "SHOWADDR=%%ADDR_!I!%%"
echo    w!I!  !SHOWADDR!
goto bannerloop
:bannerdone
echo.
echo  Every block found pays 50 BIG. Rewards become spendable
echo  after 100 confirmations - roughly one day.
echo.
echo  Check your balance:
echo      bigcoin-cli.exe -datadir=data -rpcwallet=miner getbalances
echo  Back up your wallet - do this, the keys are only in the
echo  data folder:
echo      bigcoin-cli.exe -datadir=data -rpcwallet=miner backupwallet C:\path\backup.dat
echo.
echo  Close this window to stop mining. The node keeps running.
echo  To stop the node later:
echo      bigcoin-cli.exe -datadir=data stop
echo ============================================================
echo.
if /i not "!ALGO!"=="yespower" goto notip
if !WORKERS! leq 1 goto notip
echo  [TIP] yespower is limited by memory bandwidth, not by clock
echo        speed, so more workers do not always mean more hashes.
echo        Watch the hashes/s line below, then try a smaller
echo        worker count - mine-bigcoin.cmd 4 - and compare. Use
echo        whichever number is actually faster on your machine.
echo.
:notip

rem ---- Start workers 2..N as copies of this script -------------
rem They share this console, so all of their output appears here
rem and closing this window stops every one of them.
set /a I=1
:spawnloop
set /a I+=1
if !I! gtr !WORKERS! goto spawndone
call set "WADDR=%%ADDR_!I!%%"
start "" /b "%COMSPEC%" /c call "%~f0" worker !I! !WADDR!
goto spawnloop
:spawndone

rem This first copy is worker 1, and the only one that prints the
rem periodic status line.
set "WID=1"
set "ADDR=!ADDR_1!"
goto mine

:worker
set "WID=%~2"
set "ADDR=%~3"
set "WORKERS=1"
if "!ADDR!"=="" exit /b 1

rem ============================================================
rem  The worker loop
rem ============================================================
rem generatetoaddress is a synchronous RPC: it tries nonces up to
rem the given ceiling and returns the block hash if it finds one,
rem or an empty array if it does not.
rem Mining itself does not use a wallet, so no -rpcwallet here -
rem passing one would stop mining as well whenever the wallet gets
rem unloaded.
:mine
set "OUTFILE=%TEMP%\bigcoin-mine-!WID!-%RANDOM%%RANDOM%.txt"
set "ALGO="
set "BUDGET="
set /a RATE=0
set /a LASTBEAT=0

:mineloop
rem Which algorithm does the next block need? Asked of the node
rem rather than hardcoded here, so this script cannot disagree
rem with consensus about where the switch happens. Asked before
rem every call and not after, because the first call of the
rem yespower era must not be sized with a double-SHA256 budget or
rem it would run for days instead of seconds.
call :probealgo
if "!NOWALGO!"=="!ALGO!" goto algodone
if "!ALGO!"=="" goto algoset
if "!WID!"=="1" echo [!time!] *** proof-of-work algorithm is now !NOWALGO! - resizing the nonce budget ***
:algoset
set "ALGO=!NOWALGO!"
set /a RATE=0
if "!NOWALGO!"=="yespower" (set "BUDGET=%BUDGET_START_YESPOWER%") else (set "BUDGET=%BUDGET_START_SHA256D%")
:algodone

call :now
set /a T0=!NOWCS!
bigcoin-cli.exe "%DD%" -rpcclienttimeout=%MINE_TIMEOUT% generatetoaddress 1 !ADDR! !BUDGET! >"%OUTFILE%" 2>&1
if not errorlevel 1 goto mined
echo [!time!] w!WID! node not reachable - retrying in 15 seconds ...
rem ping, not timeout: timeout reads the console and several
rem workers share one console here.
>nul ping -n 16 127.0.0.1
goto mineloop

:mined
call :now
set /a ELAPSED=^(!NOWCS!-!T0!^)/100
if !ELAPSED! lss 0 set /a ELAPSED+=86400

rem A 64-hex string in quotes is a block hash. Not just any run of
rem hex: up to v1.6 this script looked for leading zeros, but from
rem v1.7 on the hash a found block reports is its identity, which
rem is double-SHA256 in both eras and so no longer has to start
rem with zeros. Matching on zeros would silently miss every
rem yespower block. The redirect comes first because a findstr
rem pattern containing an escaped quote confuses cmd's parsing of
rem a trailing one.
>nul findstr /r /c:"\"[0-9a-f][0-9a-f][0-9a-f][0-9a-f]" "%OUTFILE%"
if errorlevel 1 goto noblock
echo [!time!] w!WID! *** BLOCK FOUND - 50 BIG credited to your wallet ***
rem The call returned early, so it says nothing about speed.
goto mineloop

:noblock
rem No block, so the budget was spent in full and this is an exact
rem measurement of this worker's hash rate. Resize towards
rem TARGET_SECONDS. Calls shorter than a second are not measurable
rem at this clock resolution and are left alone.
if !ELAPSED! lss 1 goto nomeasure
set /a RATE=!BUDGET!/!ELAPSED!
set /a BUDGET=!RATE!*%TARGET_SECONDS%
if !BUDGET! lss %BUDGET_MIN% set "BUDGET=%BUDGET_MIN%"
if !BUDGET! gtr %BUDGET_MAX% set "BUDGET=%BUDGET_MAX%"
:nomeasure

rem If every worker reported, the log would be unreadable, so only
rem worker 1 prints a status line, and only once a minute.
if not "!WID!"=="1" goto mineloop
call :now
set /a BEATAGE=^(!NOWCS!-!LASTBEAT!^)/100
if !BEATAGE! lss 0 set /a BEATAGE+=86400
if !BEATAGE! lss 60 goto mineloop
set /a LASTBEAT=!NOWCS!
set "HEIGHT=?"
set "DIFFI=?"
for /f "usebackq delims=" %%H in (`bigcoin-cli.exe "%DD%" getblockcount 2^>nul`) do set "HEIGHT=%%H"
for /f "usebackq delims=" %%D in (`bigcoin-cli.exe "%DD%" getdifficulty 2^>nul`) do set "DIFFI=%%D"
if !RATE! leq 0 goto plainbeat
set /a TOTRATE=!RATE!*!WORKERS!
echo [!time!] mining ... height=!HEIGHT! difficulty=!DIFFI! algo=!ALGO! !RATE! hashes/s/worker, about !TOTRATE! total over !WORKERS!
goto mineloop
:plainbeat
echo [!time!] mining ... height=!HEIGHT! difficulty=!DIFFI! algo=!ALGO! workers=!WORKERS!
goto mineloop

rem ============================================================
rem  Subroutines
rem ============================================================

rem Record one address as ADDR_<n> and count it.
:addaddr
set "AA=%~1"
set "AA=!AA: =!"
if "!AA!"=="" goto :eof
set /a NADDR+=1
set "ADDR_!NADDR!=!AA!"
goto :eof

rem Which algorithm the next block needs: yespower or sha256d.
rem The pattern avoids quote characters on purpose - a dot matches
rem the quotes in the JSON - so that cmd does not have to be
rem taught where this argument ends.
:probealgo
set "NOWALGO=sha256d"
bigcoin-cli.exe "%DD%" getblockchaininfo 2>nul | findstr /r /c:"pow_algo.: .yespower" >nul
if not errorlevel 1 set "NOWALGO=yespower"
goto :eof

rem Wall clock in hundredths of a second since midnight. %TIME% is
rem space-padded before 10 o'clock in some locales and zero-padded
rem in others, and its decimal separator can be a comma, so pad to
rem two digits and accept both separators.
:now
set "NOWT=%time%"
set "NOWT=!NOWT: =0!"
for /f "tokens=1-4 delims=:.," %%a in ("!NOWT!") do (
  set "NH=0%%a"
  set "NM=0%%b"
  set "NS=0%%c"
  set "NF=0%%d"
)
set "NH=!NH:~-2!"
set "NM=!NM:~-2!"
set "NS=!NS:~-2!"
set "NF=!NF:~-2!"
set /a NOWCS=^(^(^(1!NH!-100^)*60+1!NM!-100^)*60+1!NS!-100^)*100+1!NF!-100
goto :eof
