Architecture & Internals
How bmc combines hand-authored x86-64 / AArch64 assembly primitives with a shared C daemon layer,
an LSM UTXO store, monotonic block archiving, and zero-delay sorted-run indexing.
1. Assembly + C Layering
The codebase (~191k LOC across core assembly, C, and CUDA; ~363k LOC including tests and validation harnesses) splits cleanly along an ABI boundary enforced by static Python auditors:
| Layer | Files | Responsibility |
|---|---|---|
| Core Assembly | asm/*.asm (x86-64 NASM)port/osx/*.S (ARM64 Mach-O) |
SHA-256 / SHA-512 / RIPEMD-160 / SHA-1, secp256k1 field & point arithmetic, ECDSA, BIP340 Schnorr, BIP341 Taproot, Script VM, BIP143 sighash, MuHash3072, BIP32/39, Block Store, Undo Log, LSM UTXO Engine, P2P wire & compact blocks. |
| Shared C Daemon | asm/daemon/*.c |
Process supervision, outbound P2P multiplexer, parallel IBD chunk scheduler, block connect & reorg coordinator, mempool & fee estimation, Tor/I2P/SOCKS5/BIP324 transport, ZMQ publisher, trailing index builders, config parser. |
| RPC, REST, Esplora & Wallet | asm/rpc_*.c, asm/rest.c, asm/wallet_*.c, asm/miniscript.c, asm/musig2.c, asm/descriptor.c |
HTTP/JSON-RPC 2.0 server with lock-free/lane concurrency, Core REST endpoints, Esplora facade, HD wallet, output descriptors, iterative Miniscript, BIP327 MuSig2, PSBT v0/v2, external signer interface. |
| Optional GPU Tier | asm/cuda/*.cu |
CUDA batch SHA-256, ECDSA, and BIP340 Schnorr verification kernels with automatic CPU fallback when no NVIDIA GPU/toolchain is present. |
2. Cryptographic Primitives
- secp256k1 Field & Scalar Arithmetic: 4×64-bit limb representation with Montgomery/Safegcd modular inversion, addition-chain square roots (
fe_sqrt), and GLV endomorphism wNAF scalar multiplication (secp256k1_glv_c.c+ assembly). - Constant-Time Signing Paths: Complete-formula projective/homogeneous point addition (
secp256k1_point_ct.asm) used for secret-key scalar multiplications so private keys never leak via branch timing or point-at-infinity edge cases. - Hardware Acceleration: Runtime CPUID dispatch for x86-64 SHA-NI (
sha256_blocks_shani) and AVX2 keystream generation for MuHash3072 (muhash_mul). - Secret Hygiene: Dedicated volatile wipe routines clear BIP39 entropy, BIP32 master keys, MuSig2 nonces/intermediates, and wallet HD key buffers on wallet lock, switch, or unload.
3. Custom LSM UTXO Engine
Rather than embedding LevelDB, bmc implements a domain-specific Log-Structured Merge-tree (bitcoin_utxo_lsm.asm / port/osx/bitcoin_utxo_lsm.S + asm/utxo_lsm_mm.c) tailored to Bitcoin's 36-byte outpoint keys (txid[32] || vout[4]).
Live Memtable & WAL
Bounded by dbcache (default 450 MiB). Backed by anonymous huge-page-eligible memory (bmc.memtableanon=1)
with a write-ahead log (utxo.dat) checkpointed and fsynced at block/batch boundaries. Tombstone lookups use a
dedicated open-addressing hash table with WAL deduplication and fail-closed reload checks.
Async Forked Flushes (B3)
When the live memtable reaches its threshold, it is frozen and handed to a forked writer process while the applier immediately
continues on a fresh memtable. The writer sorts records, builds a per-run sized Bloom filter and 64-stride sparse index,
fsyncs utxo_run_NNNNNN.dat, and atomically publishes utxo_manifest.dat via temp+fsync+rename.
Leveled Compaction & Fast Reads
Background compaction performs a streaming k-way merge with 256 KiB read-ahead buffers per run, dropping obsolete tombstones
when merging from the oldest prefix. Read lookups use a per-thread 64-slot LRU mmap cache (utxo_lsm_mm.c)
tagged by (epoch, run_no, gen) with a pthread_key destructor to guarantee zero FD/mapping leaks on thread exit.
An opt-in bmc.lsmreads=pread mode keeps record pages out of process PSS.
4. Monotonic Block Archive & Packed Undo Log
- Block Files (
blkNNNNN.dat): Append-only 128 MiB framed files ([magic:4][len:4][raw_block]) accompanied by a positional 48-byte-per-heightindex.dat, 80-byte-per-heightheaders.dat, and 16-byte cumulativechainwork.dat. - Monotonic Layout: During parallel IBD, chunk workers stage verified blocks to temporary chunk files and a single committer appends them strictly in height order. As a result,
blk*.datfiles are monotonic with zero holes (simplifying pruning and range truncation). - Boundary Hole & Prune Safety:
store_truncate_torefuses to truncate across an all-zero index hole (preventing archive destruction), andstore_pruneresets cached descriptors/mappings before unlinking pruned files. - Full-Chain Undo (
rev*.dat): Every spent coin's value, height, coinbase bit, and scriptPubKey is recorded in packed undo files, enabling reorgs of arbitrary depth and full fee/prevout queries without re-scanning old blocks.
5. Sorted-Run Trailing Indexes
Every optional index (txindex, txospenderindex, blockfilterindex, addrindex, coinstatsindex)
uses a unified two-tier architecture (daemon/index_runs.h + daemon/index_trail.c):
- Immutable Sorted Runs: Background child builders fold ranges of
bmc.indexrunblocks(default 20,000) heights into compact sorted run files with sparse indexes during IBD, merging runs as they accumulate. - Bounded Live Tail: Blocks above the highest committed run are appended to a small unsorted tail journal (
*.tail), which is rotated once folded into a run and truncated on disk during chain reorganizations so post-reorg restarts never skip replacement blocks. - Reliable Builder Supervision: Child builder exit status is verified over a dedicated
CLOEXECstatus pipe rather than relying onwaitpid()underSIGCHLD=SIG_IGN, ensuring a crashed builder never triggers tail deletion.
6. Headers-First Parallel Initial Block Download
- Parallel Header Sync: Four peers are probed simultaneously; 19 parallel header ranges download and validate PoW + difficulty transitions (
bad-diffbits) intoheaders.dat. - Peer Ranking & Stall Control: Peers are ranked by timed throughput samples. Ten download workers claim 16-block chunks within Core's 1,024-block download window. Stalling peers hit Core's exponential 2s → 64s stall clock, get reassigned immediately, and are banned for the run on a second stall.
- Pipelined Apply & Indexing: Block connection, parallel script verification (
-parthreads), async UTXO flushing, MuHash folding, and trailing index construction run concurrently with downloading—reaching the tip with all indexes ready in 3h 17m 55s.
7. Cross-Architecture Porting
- macOS Apple Silicon (
port/osx/): Complete AArch64 Mach-O assembly counterparts exporting the identical C ABI symbols asasm/*.asm, hardened with-fstack-protector-strong -D_FORTIFY_SOURCE=2andF_FULLFSYNCdurability barriers (asm/bmc_fsync.h). - Windows x86-64 (
port/win/): Reuses the exact Linux x86-64 NASM assembly (assembled-f win64) and LLVM-retargeted C over a native Win32/NT Linux syscall emulation layer (port/win/winsys/), includingfork()semantics, without WSL or Cygwin.