Introducing a new way to review your PRs.

Read the announcement

luke-jr / bfgminer

Modular ASIC/FPGA miner written in C, featuring overclocking, monitoring, fan speed control and remote interface capabilities.

View on GitHub

13 documents · Updated Nov 16, 2026

docs / miner-core-runtime

Core BFGMiner Runtime

Overview

The core runtime is centered in miner.c and exported through miner.h. main() in miner.c owns process startup: it initializes curl, Winsock/libusb when present, mutexes/rwlocks/condition variables, thread-local storage, checksum tables, the global get-work queue, signal handlers, option/config parsing, mining goals, pools, device detection, and control threads. After setup it becomes the get-work scheduler: it keeps enough struct work staged for the active devices, selects an upstream pool by strategy and mining algorithm, generates Stratum/GBT/getwork/benchmark work, and pushes that work into the staged hash queue consumed by mining threads.

miner.h is the shared state contract for the rest of the codebase. It defines the central runtime objects: struct device_drv for driver callbacks, struct cgpu_info for devices and processors, struct thr_info for mining and control threads, struct pool for upstream pool state, struct work for block header/share state, struct stratum_work for Stratum job templates, and struct mining_algorithm / struct mining_goal_info for algorithm-specific blockchains and pool goals. Drivers connect to the runtime by filling struct device_drv callbacks such as drv_detect, thread_prepare, minerloop, scanhash, scanwork, queue_full, flush_work, thread_disable, and API/status callbacks. Work sources and submission paths use the same structs, so API code and drivers both observe the global stats, pool status, device health, and queue state declared in miner.h.

Work acquisition and scheduling in miner.c run through a staged queue protected by getq->mutex (stgd_lock) and signaled by gws_cond. HTTP getwork/GBT uses get_upstream_work() and json_rpc_call() from util.c; Stratum pools are maintained by one stratum_thread() per pool, parsed by parse_method() in util.c, and converted to struct work by gen_stratum_work*() in miner.c. Long-polling uses longpoll_thread() to turn block-change responses into staged work and restarts mining threads. Device threads call get_work() or queued-work helpers (get_queued(), add_queued(), hash_queued_work()) and report shares via submit_nonce() / submit_noffset_nonce(), which validates the nonce, updates diff counters, and hands a work copy to the asynchronous submit thread.

Pool lifecycle, failover, and selection are runtime concerns in miner.c. add_pool2() initializes pool locks, queues, curl state, Stratum state, stats, and default goals; detect_stratum() recognizes stratum+tcp:// URLs; pool_active() probes pools, negotiates GBT/getwork/Stratum, starts longpoll/Stratum threads, and stages test work. select_pool(), switch_pools(), adjust_quota_gcd(), and bfg_strategy_change() implement failover, round-robin, rotate, load-balance, and balance strategies. pool_check_coinbase() and related option parsing connect pool work to coinbase payout validation, local bitcoind fallback, and mining-goal scripts.

Device lifecycle starts with low-level or driver-specific detection in drv_detect_all(), probe_device(), and create_new_cgpus(). register_device() adds processors to the global devices array, increments mining_threads, and contributes to per-algorithm queue depth; allocate_cgpu() wires cgpu_info to thr_info objects and per-thread notifiers; start_cgpu() calls driver preparation and launches miner_thread(). Hotplug support in miner.c uses udev/epoll on Unix-like systems or Windows device-change messages to schedule rescans, and algorithm changes through goal_set_malgo() can trigger hotplug when newly required hardware may be needed.

Runtime control loops are also in miner.c. watchpool_thread() monitors pool liveness and rotation; watchdog_thread() checks device health and calls bfg_watchdog()/driver watchdog hooks; restart_threads() marks every mining thread for a work restart and wakes their notifiers; kill_work() / app_restart() perform shutdown or exec restart by canceling control/mining/API threads and waking the submit queue. Scheduled start/stop windows are handled by should_run() using schedstart/schedstop parsed from command-line/config options.

util.c / util.h provide the runtime's shared platform, networking, timer, JSON, Stratum, queue, and binary helpers. HTTP JSON-RPC is split into json_rpc_call_async() and json_rpc_call_completed() so the submit thread can multiplex curl handles while simple callers use json_rpc_call(). Stratum socket helpers (_stratum_send(), recv_line(), initiate_stratum(), auth_stratum(), restart_stratum(), suspend_stratum()) operate directly on struct pool fields defined in miner.h. Timers are initialized lazily through timer_set_now, preferring monotonic clocks or QueryPerformanceCounter before gettimeofday; cgsleep_*, timer_*, and select_timeout() are used throughout the scheduler, watchdog, hotplug, and network loops. thread_q, thr_info_create(), thr_info_cancel(), and notifier_t wrap inter-thread queues, thread lifecycle, and wakeup pipes/sockets.

Logging is split between logging.c and logging.h. Callers use applog() / applogsiz() macros, which gate debug messages unless opt_debug is set. _applog() writes to syslog, curses log windows, stdout/stderr, or redirected log files depending on use_syslog, opt_log_output, opt_quiet, opt_realquiet, opt_log_microseconds, and whether stderr is a tty. Fatal paths use quit(), quithere(), or quitfrom(); these call _bfg_clean_up() or _quit() declared in runtime headers. Curses display and status rendering live in miner.c and consume the same global counters, pool state, and cgpu_info stats as API/status code.

dynclock.c / dynclock.h implement a shared dynamic clock policy used by drivers that can adjust device frequency. Drivers initialize struct dclk_data with dclk_prepare(), report successful nonce samples with dclk_gotNonces(), report error portions with dclk_errorCount(), call dclk_preUpdate() after a sampling period, then call dclk_updateFreq() with a driver-specific changeclock callback. The policy chooses the best frequency multiplier from measured error rates, applies hysteresis, logs frequency changes through dclk_msg_freqchange(), and returns false if a large drop suggests overheating.

sha2.c / sha2.h provide the SHA-256 implementation used for midstates, double-SHA block hashing, Stratum merkle roots, and libblkmaker/base58 callbacks. The runtime registers my_blkmaker_sha256_callback() in main() so libblkmaker and base58 use the same SHA-256 implementation. miner.c also uses sha256_init() / sha256_update() for midstate calculation and gen_hash() for double-SHA256.

Portability headers keep this runtime buildable across C/C++, Windows, Unix, and generated gnulib environments. compat.h supplies platform shims for missing list macros, timers, nanosleep(), sleep(), pthread cancellation, setpriority(), and Windows localtime_r(). winhacks.h avoids Windows header macro collisions with curses. c++defs.h, arg-nonnull.h, and warn-on-use.h are gnulib support headers for C++ aliases, non-null attributes, and portability warnings.

Coverage

Coupling

  • If a driver changes struct device_drv callbacks or struct cgpu_info queue fields in miner.h, verify the scheduler paths in miner.c (allocate_cgpu(), start_cgpu(), get_work(), fill_queue(), hash_queued_work()) still match the driver's minerloop style. Synchronous scanhash, async minerloops, and queued scanwork paths use different callback combinations and stale-work/disable semantics.
  • If struct work, struct stratum_work, or mining algorithm fields in miner.h change, update both work producers and consumers in miner.c and util.c: work_decode(), gen_stratum_work3(), submit_upstream_work_request(), parse_notify(), _test_nonce2(), and driver work-queue helpers all assume specific byte offsets, endian conversions, and ownership of job_id, nonce1, nonce2, template refs, and device-private data.
  • If pool selection or struct pool state changes in miner.h, check miner.c and util.c together. miner.c owns pool strategy, work staging, longpoll, and submit retry state, while util.c directly mutates Stratum socket/session/job fields and pool network counters.
  • If JSON-RPC or Stratum logging/debug options change in miner.c, verify logging.c, logging.h, and util.c: protocol dumps are emitted in json_rpc_call_async(), json_rpc_call_completed(), _stratum_send(), recv_line(), and parse_notify(), but global gates (opt_protocol, opt_debug, opt_quiet, opt_realquiet) are declared across miner.c/logging.c and exported through headers.
  • If timer behavior is changed in util.c / util.h, verify scheduler loops in miner.c that rely on monotonic deltas: staged-work expiry, longpoll retry timing, Stratum transparency timers, device watchdog timing, rescan scheduling, and dynamic queue underrun handling all use timer_set_now, timer_elapsed*, timer_passed(), or select_timeout().
  • If mining algorithm registration changes, check miner.c goal handling and device discovery. get_mining_goal(), goal_set_malgo(), drv_algo_check(), pool algorithm filtering, and per-algorithm base_queue/staged counters determine which drivers are detected and which pools can feed work to which devices.
  • If SHA-256 or byte-order helpers change in sha2.c, sha2.h, miner.h, or util.h, verify midstate generation, gen_hash(), Stratum merkle root creation, target comparison, and difficulty conversion in miner.c/util.c; these paths mix little-endian pool/device data with big-endian JSON/header encodings.

Risks

  • miner.c has many global locks (control_lock, devices_lock, mining_thr_lock, stgd_lock, pool->data_lock, pool->stratum_lock, stats_lock) that are acquired from scheduler, Stratum, longpoll, submit, watchdog, curses, and driver-facing paths. Changing lock ordering in miner.c or util.c can deadlock mining threads or block share submission, especially around gen_stratum_work2() downgrading pool->data_lock and around submit retry paths holding submitting_lock while interacting with pool sockets.
  • miner.c work ownership is fragile: clean_work(), free_work(), _copy_work(), copy_work_noffset(), stratum_work_cpy(), and stratum_work_clean() manage nested allocations and libblkmaker template refs. If a new struct work field is added in miner.h without updating these functions, work cloning or discard paths can leak memory, double-free, or submit stale device-private data.
  • util.c Stratum parsing mutates pool->swork under pool->data_lock, while miner.c generates work and submits shares against the same state. If parse_notify(), stratum_set_extranonce(), initiate_stratum(), or gen_stratum_work() change nonce/session handling, duplicate nonce2 values or mismatched session IDs can cause invalid shares or discarded resubmissions.
  • miner.c device detection and hotplug are highly stateful. create_new_cgpus() reallocates global devices and mining_thr arrays while existing threads use accessor locks, and low-level probe threads in probe_device_thread() can request delayed rescans. Changes here can orphan cgpu_info instances or start threads before notifiers and queue locks are initialized.