Notes on reimplementing p2pool in C++
The making of c2pool
Update, November 2026. These notes were written in June 2026, while c2pool ran Litecoin with Dogecoin merged mining next to Python p2pool. They are kept as written, with dated notes where the facts have changed. Today c2pool builds one binary per parent chain: Litecoin with Dogecoin, and Dash, are in production; Bitcoin, DigiByte and Bitcoin Cash nodes run live with no coin daemon; BIP-110 and Monero are experimental. See c2pool today.
p2pool is a decentralized mining protocol. There is no pool operator. Miners form a peer-to-peer network, agree on a shared chain of “shares” (low-difficulty blocks), and when a real block is found, the coinbase reward is split among everyone who contributed work. It was originally written for Bitcoin, later forked for Litecoin, Dogecoin, Vertcoin, and nearly every other PoW coin. It has been running since 2011.
We reimplemented the Litecoin fork from scratch in C++ — a clean-room implementation that joins the existing sharechain starting from V35, then follows the network through the V36 transition. We call it c2pool.
It has been said that a second compatible implementation would be “a menace to the network” because so much depends on all nodes getting exactly identical results in lockstep. The difficulty part turned out to be right (though we think the conclusion is wrong — a second implementation finds consensus bugs that a single codebase never will). The project took considerably longer than expected, not because of the C++ port itself, but because p2pool’s consensus rules turned out to be far more subtle than the code suggests. This is what we found.
Standing on existing code
A clean-room implementation does not mean writing everything from scratch. Bitcoin Core’s codebase provides well-tested cryptographic primitives (SHA-256 with hardware acceleration, RIPEMD-160, SipHash for compact blocks), the uint256 type, the binary serialization framework, base58 and bech32 encoding, and the script types. We pulled these into a static library and used them directly. The serialization layer alone is 37 KB of battle-tested code that handles every edge case in Bitcoin’s wire format.
From Litecoin Core we took the scrypt proof-of-work implementation (Colin Percival’s original, adapted by pooler) and the MWEB structures. From Dogecoin Core we took the AuxPoW header format and DigiShield v3 difficulty retargeting logic. In each case the reference daemon source was the authority — not documentation, not a specification, but the actual code that the network runs.
p2pool stores its share chain and state in flat files. We use LevelDB for everything: the share chain, the UTXO set, the mempool index, embedded block headers for both chains, found block records, merged block records. Having all persistent state in one storage layer means atomic access across components — a share verification can look up UTXO coins, header difficulty, and PPLNS weights in the same transaction. Crash recovery is straightforward because WriteBatch either commits completely or not at all. Bloom filters give fast negative lookups, Snappy compression keeps the footprint small. And the key-value structure means that future components — temporal layer accumulators, adaptive window state, cross-chain settlement records — can be added as new key prefixes without restructuring anything.
Mining without a daemon
Every mining pool — centralized or decentralized — assumes it can call getblocktemplate on a local coin daemon. That RPC call returns a block template: the current difficulty target, a set of transactions from the mempool, and the coinbase value (block reward plus transaction fees). The pool assembles a candidate block from this template and hands it to miners.
p2pool is no different. It requires a fully synced litecoind (50+ GB) and, for merged mining, a fully synced dogecoind (80+ GB). It is written in Python 2, which modern systems no longer ship — running it on a current OS means installing a deprecated runtime manually. Windows support was lost years ago. macOS requires workarounds. In practice, you need a Linux machine, admin skills, patience with dependency resolution, and a willingness to maintain two full coin daemons. Most miners look at this and use a centralized pool instead.
It should be possible to mine without any of that. c2pool is a compiled binary — Linux, Windows (installer and portable), macOS (Intel and Apple Silicon). It embeds lightweight SPV nodes for both Litecoin and Dogecoin, syncs block headers via P2P from DNS seed nodes, tracks a UTXO set for fee computation, maintains a mempool, and builds block templates internally.
This turned out to be harder than the C++ port.
The subsidy mismatch
The first thing we discovered is that getblocktemplate does more than return a block template. It returns a coinbasevalue field: the maximum satoshis the coinbase transaction can claim. This value is block_reward + total_mempool_fees. Every share on the p2pool network commits to this number. Every other node reconstructs the coinbase to verify it. If the number doesn’t match, the share is rejected.
Our embedded SPV node had no UTXO set, which meant no way to compute transaction fees (fee = sum(inputs) − sum(outputs), and you need the UTXO set to look up input values). Our coinbasevalue was just the block reward. No fees.
81 out of 109 test shares failed with GENTX-MISMATCH. The subsidy was off by a few thousand satoshis — the sum of mempool fees we couldn’t compute.
The fix required building a full UTXO tracking system: a LevelDB-backed UTXO store, an in-memory write-back cache, connect_block and disconnect_from_undo for reorgs, coinbase maturity enforcement (100 blocks for LTC, 240 for DOGE), and a feerate-sorted mempool index for optimal block building. We also activate BIP 35 mempool sync to populate the mempool from peers immediately after connecting.
The resulting block templates match litecoind’s getblocktemplate output to within a few satoshis (mempool composition may differ slightly between nodes, which is expected).
The invisible sync gate
p2pool doesn’t have an explicit “wait for sync” check at startup. It doesn’t need one. Its startup sequence calls getblocktemplate and blocks until the daemon responds. If the daemon is still syncing, the RPC call fails, the retry loop spins, and the stratum server never opens. Sync is implicit.
Without a daemon, there is no blocking RPC call. Our first test of the embedded node produced shares before the header chain finished syncing. The difficulty bits were wrong. Every share had near-zero difficulty. p2pool peers received a flood of invalid shares and disconnected.
We had to discover this invisible gate and recreate it explicitly: the stratum server stays closed until the header chain tip is within two hours of wall clock time and the first block template builds successfully. For merged mining chains like Dogecoin, we don’t block startup — mining begins with Litecoin work only, and Dogecoin work is added when its header chain catches up. This matches p2pool’s behavior: merged chains degrade gracefully.
The self-verification paradox
This one took a while to understand. c2pool couldn’t verify its own shares.
After embedding the UTXO set and mempool, our shares had correct subsidies and p2pool accepted them. Zero GENTX failures on the p2pool side. But c2pool’s own verification produced 683 GENTX-MISMATCH retries on shares it had created moments earlier.
The root cause turned out to be a misunderstanding of what share verification actually is. It is not reconstruction — it is replay. When c2pool created a share, it stored subsidy = 156251106 (block reward + fees at creation time). Later, when the verification engine checked that share, it reconstructed the coinbase using the current mempool fees, which had changed. Different subsidy, different coinbase transaction, different hash. Verification failed.
p2pool’s check() method uses self.share_data['subsidy'] — the share’s own stored value, frozen at creation time. Verification replays the share’s parameters, it doesn’t recompute them from the current state. Once we understood this distinction, the fix was one line: use share.m_subsidy instead of the live template’s coinbasevalue. I think this is the kind of thing that makes second implementations dangerous — the original code makes it obvious, but the abstraction doesn’t.
Designing the upgrade
Before reimplementing p2pool in C++, we had to design what we were reimplementing. The existing Litecoin p2pool (V35) had no merged mining — miners could mine LTC but not DOGE simultaneously. It used flat PPLNS weighting where shares are weighted by difficulty but not by age, which is vulnerable to pool-hopping. The donation script used an uncompressed P2PK output (67 bytes), wasting coinbase space.
We wrote V36 first in Python, as a fork of p2pool itself. It adds merged mining with per-share address commitments, exponential decay PPLNS, a compact P2SH donation script (23 bytes), and native support for bech32/P2SH address types in the coinbase. These are consensus changes — every node on the sharechain must agree on the new rules, or the network splits.
The problem is that you cannot just switch. The sharechain is live, miners are running, and a hard cutover would partition the network into nodes that understand V36 and nodes that don’t. The original p2pool already had a version voting mechanism for earlier transitions (the desired_version field and share version signaling were forrestv’s design). We extended it into a full state machine for V36.
Hashrate-weighted voting
Each share carries two version fields: the share format version (35 or 36, determining its structure) and a desired_version field (what the miner wants the network to upgrade to). A node in voting mode produces V35-format shares but sets desired_version = 36 on every one. The votes are weighted by difficulty — a share at difficulty 64 gets four times the vote weight of difficulty 16. This prevents someone from flooding the network with low-difficulty votes.
The activation logic is a three-state machine we call AutoRatchet:
- VOTING: the node produces V35 shares, votes for V36. When 95% of difficulty-weighted votes in the sampling window favor V36 (with a tail guard requiring 60% in the oldest portion of the window), the ratchet advances.
- ACTIVATED: the node begins producing V36 shares. If votes drop below 50%, it falls back to VOTING. The state is persisted to disk so it survives restarts.
- CONFIRMED: after 2× CHAIN_LENGTH shares of sustained 95% V36, the transition is permanent. The minimum protocol version locks at 3600 and old V35-only peers are dropped.
Update, November 2026. In the code of both c2pool and p2pool-merged-v36, the ratchet’s 95% and 50% thresholds count shares: one share, one vote. Votes are weighted by work only in the tail guard, where at least 60% of the work in the oldest tenth of the window must signal V36.
The hysteresis (95% up, 50% down) prevents oscillation. The tail guard prevents premature activation before the entire PPLNS window has transitioned. And even in CONFIRMED state, if the network somehow reverts below 50%, the node follows consensus and produces V35 — the persisted state is a preference, not an override.
Update, November 2026. In July 2026 specific false-activation modes of the AutoRatchet could still trip and flap, desynchronizing the share chain. Those modes are now guarded by regression tests; the c2pool README does not claim the whole class is closed.
c2pool enters the network speaking protocol version 3500, producing V35 shares, voting for V36. It follows the same ratchet logic ported to C++, reading and writing the same v36_ratchet.json persistence file. On a network that has already confirmed V36, a fresh c2pool node loads the persisted state and begins producing V36 shares immediately.
Update, November 2026. The V35 → V36 ratchet has completed. Since 2026-11-13 00:00:00 UTC every share on the Litecoin share chain is a share version 3601 share. That switch was a flag day fixed in the release (c2pool v0.2.12.1), not a vote. A peer below protocol 3601, which includes Python p2pool, is disconnected and is no longer on the Litecoin share chain.
The mixed window
The transition does not happen at a clean boundary. When V36 activates, the PPLNS window still contains a mix of V35 and V36 shares that takes hours to flush. During this period, two things run simultaneously, and getting either one wrong by a single share produces a cascade.
The PPLNS walk must apply flat weighting to V35 shares and exponential decay to V36 shares, switching formulas at the exact activation share. Both p2pool and c2pool support testnet configurations with a shorter sharechain window — 400 shares instead of mainnet’s 8,640. This compresses hours of transition into minutes, which is necessary for iterating on consensus bugs. On our testnet sharechain, V36 activated around share 400. The PPLNS window was 400 shares. At share 800 the V36 boundary entered the window. At share 870, GENTX failures started. PPLNS weight dropped from 36% to 14%. This was reproducible across every test run — the boundary crossing always triggered it. On mainnet the same transition plays out over roughly three days.
One of the harder bugs to find: c2pool selected the PPLNS formula at compile time (the share type determines V35 or V36 at the template level), while p2pool selects it at runtime based on the AutoRatchet state. During the transition, p2pool verifies a V35 share using V36 decay weights (because the ratchet is ACTIVATED), while c2pool verifies the same V35 share using flat weights (because the share struct is V35). Different coinbase outputs, GENTX mismatch, peer ban. The fix was to match p2pool’s logic: use the ratchet state, not the share version, to select the formula.
Update, November 2026. The public code settled the other way: p2pool and c2pool verify every share with the formula of the share’s own version (v36_active = VERSION ≥ 36). The ratchet state decides only which share version a node produces.
In a later overnight run, the AutoRatchet itself desynced. c2pool measured chain progress by absolute share height; p2pool measured by chain depth. c2pool reached CONFIRMED state 56 shares earlier. For four hours the two implementations used different PPLNS formulas on the same shares. 1,164 GENTX failures, 956 peer disconnections, 21 LTC blocks submitted but none accepted. The fix was one field: use chain depth, not absolute height.
Update, November 2026. The public fix for this desync (31 March 2026) records it as CONFIRMED about 100 shares early and more than 24,000 GENTX failures overnight.
The address handling is similarly layered. V35 shares carry only an LTC payout script — there is no merged address field. During the mixed window, the DOGE payout for a V35 share must be auto-converted from the LTC script: decode the pubkey hash from whatever format the miner used (P2PKH, bech32, P2SH) and derive a DOGE P2PKH address. V36 shares can carry explicit merged addresses set by the miner in the stratum login field (LTC_ADDR,DOGE_ADDR.worker). So the same PPLNS walk encounters three kinds of DOGE address: auto-converted from V35 shares, auto-converted from V36 shares where the miner omitted the field, and explicitly provided on V36 shares. A single miner who set an explicit DOGE address in their stratum login will appear twice in the merged payout list during the mixed window — once under the auto-converted address (from their older V35 shares still in the window) and once under the explicit address (from their newer V36 shares). Both are valid payouts for the same miner, but they are different script keys. Every node must produce both entries with identical amounts, or the merged_payout_hash diverges and shares get rejected.
We found a byte-ordering bug in the bech32 auto-conversion path. p2pool’s IntType(160) reads the 20-byte witness program as a little-endian integer, then formats it back to big-endian hex for the DOGE address derivation. The bytes come out reversed. On our 3-miner testnet, a fourth phantom miner appeared in the DOGE payout list — it was the bech32 miner’s address with the hash160 byte-swapped. P2PKH addresses were not affected because the double reversal cancels out.
I think there is something worth noting about this transition: the mechanism is more complex than the feature it enables. The merged mining logic, the exponential decay, the compact scripts — each is straightforward. The hard part is changing them while the network is running and the PPLNS window remembers both eras.
The Dogecoin auxblock problem
Merged mining requires building a Dogecoin block template with PPLNS payouts to multiple miners. The standard Dogecoin RPC for this is createauxblock, but it takes a single payout address and returns a pre-built block hash. You cannot customize the coinbase. For a centralized pool paying one operator, this is fine. For a decentralized pool that needs 27 miners in the coinbase, it does not work.
For p2pool, we wrote an mm-adapter — a JSON-RPC middleware that bypasses createauxblock entirely, calls getblocktemplate on the Dogecoin daemon instead, and lets p2pool build its own coinbase with the full PPLNS payout list. The adapter handles merkle root computation, block hash calculation, and submits complete blocks via submitblock. It is a workaround for an RPC interface that was not designed for multi-address payouts.
c2pool does not need the adapter. The embedded DOGE SPV node builds merged mining templates directly, the same way it builds LTC templates. The coinbase is constructed internally with the full PPLNS payout structure.
Block propagation
p2pool has two interfaces to the coin network: one RPC connection and one P2P connection, both to the same local daemon. When a block is found, it submits via submitblock RPC. The daemon then relays through its own peers. The pool sees the network through a single daemon.
We added a broadcaster to p2pool-merged-v36 that changes this. It bootstraps from the daemon’s peer list but then discovers its own peers independently via P2P addr messages. The scoring is deliberate: daemon-sourced peers get a low base score (30) because the daemon will broadcast to them anyway. Peers discovered through P2P get a higher score (150) because they represent unique propagation paths the daemon does not reach. The local daemon connection is protected (score 999999, never dropped) and serves as the anchor. Low latency, outbound connections, and successful broadcast history all increase a peer’s score. The result is that the broadcaster preferentially connects to peers the daemon does not know about, maximizing coverage.
This matters because block propagation is a race. Centralized pools running in datacentres have sub-second propagation to well-connected nodes. A decentralized pool running on a home connection that loses the propagation race loses the block reward. If a block arrives late, the reward goes to whoever propagated first.
c2pool maintains its own independent P2P connections to both the Litecoin and Dogecoin networks — separate from any daemon. When a block is found, it is broadcast simultaneously to all connected peers (5 to 20, with Sybil resistance via per-subnet limits). For Litecoin, we implemented BIP 152 compact block relay: instead of sending the full block, the node sends the header plus 6-byte SipHash short IDs for each transaction. Peers reconstruct the block from their own mempool. A typical block drops from over a megabyte to roughly 50 KB on the wire. For Dogecoin merged blocks, we send an inventory announcement and let peers request the full block — the child chain does not need the same propagation urgency as the parent.
Update, November 2026. Every Litecoin block ends with a HogEx, and a version-2 compact block has no room for the MWEB extension, so c2pool sends a block it finds on Litecoin as a full block. It still receives compact blocks.
The difference is architectural. p2pool treats the daemon as its only interface to the coin network. c2pool treats the coin network as something it participates in directly.
Seven consensus problems
1. The async compute problem
p2pool’s think() function is the central loop of the share tracker. It scores chain heads, verifies shares, selects the best chain. In Python with Twisted, this runs cooperatively on the reactor thread. Twisted’s event loop naturally interleaves think() with network I/O.
Boost.Asio doesn’t work like Twisted. When think() ran synchronously on the io_context, it blocked everything: P2P message handling, stratum responses, merged mining template rebuilds. We observed 47-minute log gaps, four peers timing out simultaneously, and a watchdog reporting “think last fired 18 seconds ago.” The node appeared dead every 15 to 60 minutes.
The fix was a synchronization redesign. think() runs on a dedicated compute thread under an exclusive std::shared_mutex. The IO thread never blocks on it — writes queue to a pending buffer, reads use shared_lock. The critical change was moving work refresh out of the exclusive lock. This single change reduced the exclusive hold from 6 seconds to 100–400 milliseconds. The difference matters: without it, P2P peers time out and disconnect, stratum miners get stale work, and the node slowly isolates itself.
p2pool never needed this because Twisted’s cooperative multitasking handles it implicitly. In C++ you have to design the concurrency explicitly, and every detail matters.
2. Skip lists, delta caching, and the chain walk problem
p2pool’s share chain is a DAG with heads, tails, and a main chain. Navigation and aggregation are everywhere: get the height of a share, compute cumulative work between two points, aggregate PPLNS weights over a window of 8,640 shares.
The original Python implementation uses several layered data structures for this. We ported and extended all of them:
Probabilistic skip lists. Three separate skip list implementations — DistanceSkipList for O(log n) ancestor navigation, WeightsSkipList for O(log n) PPLNS weight accumulation with delta caching, and StatsSkipList for O(log n) dashboard statistics aggregation (version counts, miner distribution, difficulty sums). Each uses a geometric random skip length distribution: a share has probability 0.5^k of having a level-k skip pointer. Skip levels are built lazily during traversal — the first query through a region is O(n), subsequent queries are O(log n) amortized.
Reference-based delta caching. TrackerView maintains a four-level cache of (head, tail, height, work, min_work) deltas. Each share maps to a reference ID, and the reference maps to a delta-to-chain-end. When a share is removed, only the entries using that reference are invalidated — O(1) selective invalidation instead of clearing the entire cache.
The surprising finding: for the PPLNS walk specifically, none of these help. V36 exponential decay depends on each share’s position relative to the tip, not just aggregate statistics. The same share contributes different weight depending on where it sits. Skip list delta caching can’t precompute position-dependent values. The PPLNS walk is inherently O(chain_length), which led us to a different structure entirely.
3. Exponential decay PPLNS
Original p2pool (V35) uses a flat PPLNS window: shares are weighted by their difficulty (the work required to find them) but not by their position in the window. A share at the tip counts the same as a share about to age out. This creates a pool-hopping vulnerability. A hopper joins during lucky periods, accumulates shares weighted by difficulty alone, and leaves during droughts — their shares carry full weight for as long as they remain in the window.
V36 introduces exponential decay as a consensus change:
weight(share) = work * 2^(-depth / half_life) half_life = CHAIN_LENGTH / 4 (~2160 shares, ~18 hours)
Update, November 2026. The half-life is 2160 shares on both the Litecoin and the Bitcoin share chain. On the Litecoin share chain a share is targeted every 15 seconds, so 2160 shares are about 9 hours; the 18 hours above holds for a 30-second share period, as on Bitcoin.
Recent shares matter exponentially more than old ones. But implementing bit-exact decay in C++ was harder than expected. The function uses 40-bit fixed-point arithmetic with iterative truncation: each depth’s decay factor is computed from the previous one via a 128-bit multiply-and-shift. We needed portable 128-bit multiplication across platforms — __uint128_t on GCC/Clang, _umul128 on MSVC. A 1-bit rounding difference at any depth cascades through 8,640 shares into a completely different PPLNS output, which becomes a different coinbase transaction, which means a different share hash, which every peer rejects.
The V35-to-V36 transition is where it gets interesting. When V36 activates, the PPLNS window contains a mix of V35 (flat weight) and V36 (decayed weight) shares. The walk must switch formulas at the exact right share. We observed c2pool’s PPLNS weight collapsing from 33% to 8% at the activation boundary before finding the exact share height where V36 kicks in.
We spent weeks debugging this with cross-implementation comparison tools: logging every share’s weight on both c2pool and p2pool, diffing the output, tracing the first bit where they diverged. The final implementation matches p2pool bit-for-bit on the same share chain.
4. The dense PPLNS ring buffer
The exponential decay walk is inherently O(chain_length) — you can’t use skip list caches because decay depends on each share’s position. Every attempt_verify() needs decayed weights, and with 100+ shares to verify per cycle, the redundant walks dominated runtime.
We built DensePPLNSRing (since renamed DensePPLNSWindow): a std::deque of PPLNSEntry structs (attempts, donation, script) kept in chain order, for mostly sequential memory access instead of pointer-chasing through a hash map. A static decay table of chain_length entries is precomputed once at startup — decay_table[d] gives the exact 40-bit fixed-point multiplier for depth d, eliminating all runtime exponential computation. The table is built iteratively: each entry is mul128_shift(prev, decay_per, 40), where decay_per derives from the half-life. This guarantees bit-exact results matching the walk-based code while replacing per-share arithmetic with a single table lookup.
On top of this, HeadPPLNS wraps the ring with extend/slide operations and lazy weight caching. When think() verifies 100 consecutive shares, it builds the ring once at the first share’s position (one O(chain_length) pass), then slides backward for each subsequent share — O(1) per share instead of O(chain_length). The dirty flag tracks when cached cumulative weights need recomputation.
Before (hash-map walk): 100 shares * 500us = 50ms After (ring + slide): 1 * 500us + 99 * 80us = 8.4ms (~6x faster)
5. Cross-chain address translation
In p2pool with merged mining, each share’s coinbase pays out both LTC and DOGE rewards. The miner provides one LTC address. The pool must derive a valid DOGE address from it.
It turns out to be harder than it sounds. LTC supports P2PKH, P2SH, P2WPKH (bech32), P2WSH, and P2TR. DOGE supports only P2PKH and P2SH — no SegWit, no Taproot. A miner with an ltc1q… bech32 address can’t receive DOGE directly. The pool decodes the 20-byte witness program and derives a DOGE P2PKH address from the same hash.
We identified 12 distinct cases: explicit addresses, version byte swaps, bech32 decode paths, P2WSH/P2TR that cannot be converted at all (their rewards get redistributed), swapped address order detection, and reverse derivation when someone provides a DOGE address in the LTC field.
Then there is bare multisig (P2MS), a script format with no standard address representation. It also carries one of the most famous bugs in Bitcoin: OP_CHECKMULTISIG pops one extra item from the stack due to an off-by-one error in the original implementation. Every Bitcoin-derived chain inherited this, so every spending script must supply one extra dummy element for it to pop. The NULLDUMMY rule requires that element to be empty.
During the V35-to-V36 transition, we found phantom miners: three real miners on our testnet, but four appeared in the DOGE payout list. The extra one was a normalization bug — a bech32 address decoded to a witness program, mapped to a hash160, mapped to a DOGE P2PKH, but the byte order was wrong. The same miner appeared twice under different derivations.
6. Merged mining consensus
V36 adds merged mining as a consensus-level extension. Each share commits to a merged_payout_hash — a hash of how DOGE rewards should be distributed. Every node must compute the exact same hash for the same share.
The address resolution follows a tiered system. V36 shares with explicit DOGE addresses use them directly. V36 shares without explicit addresses get auto-converted from the LTC script. V35 shares in a mixed window have no merged address field at all — auto-convert from LTC, but P2WPKH must be decoded from the witness program, P2SH version bytes swapped, and P2WSH/P2TR excluded entirely.
Excluded miners’ rewards get redistributed. There are four modes: pplns (proportional among all miners), fee (node operator), boost (give to stratum-connected miners with zero shares in the window — the small miner helper), and donate (development fund).
The boost mode is interesting for decentralization. On a pool with 90 GH/s, a miner with 1 MH/s needs roughly three days to find a share. During those three days, they’re contributing work but receiving nothing. boost channels redistributed rewards to exactly these miners.
Update, November 2026. At one share per 15 seconds across a 90 GH/s pool, a 1 MH/s miner expects a share about every 15.6 days (15 s ÷ (1 MH/s ÷ 90 GH/s)), not three days. The point about the boost mode stands.
There’s also a subtlety around pool restarts. When the node restarts, miners reconnect but haven’t completed stratum authorization yet. The ASIC is hashing at full speed with no payout address assigned. Shares go to the node’s default address, but without proper difficulty — the system doesn’t know the miner’s real hashrate. We observed 70% of effective hashrate wasted during reconnection windows. The fix: unauthorized sessions use proper difficulty based on total local hashrate, not the individual (unknown) miner’s.
7. Death spiral prevention
This is probably the hardest problem for any small decentralized pool. p2pool targets one share every 30 seconds from the entire pool’s combined hashrate. If a 70 GH/s miner leaves a 100 GH/s pool, the remaining 30 GH/s finds shares at one-third the expected rate. Original p2pool limits difficulty change to plus or minus 10% per share. Recovery from a 3× hashrate drop needs approximately 23 shares to halve difficulty. At the reduced share rate, that takes over 10 minutes. Miners see long gaps, dashboards show stale warnings, and they leave.
Update, November 2026. The 30-second share period is p2pool’s Bitcoin figure. The Litecoin share chain, in p2pool and in c2pool, targets one share every 15 seconds. Also, a clamp of ±10% per share lets the target double in about 8 shares (1.18 ≈ 2.1) and triple in about 12, so the clamp alone does not account for the “approximately 23 shares” above; that figure is kept as originally written.
V36 introduces a hybrid emergency difficulty adjustment, inspired by the BCH EDA but different in design. It activates after 10 minutes of silence, applies exponential decay to the target with linear interpolation within each halving period. The linear interpolation is the key difference from BCH’s original — it produces a smooth difficulty curve instead of the step-function jumps that made BCH’s EDA gameable.
Update, November 2026. In the code the emergency rule starts after 20 share periods without a share (300 seconds on Litecoin, not 10 minutes). From there the reference target doubles for every further 10 share periods, with linear interpolation in between, and the usual ±10% clamp applies to the result. See Difficulty adjustment.
c2pool, like p2pool-v36, has a whale departure detector: when the pool hashrate falls below half of its 30-minute average, the node asks for the easiest share target the ±10% clamp allows, instead of waiting for the normal convergence. It is a local rule, not consensus.
Understanding MWEB
Litecoin activated MWEB (MimbleWimble Extension Blocks) for optional confidential transactions. Most mining pools pass through whatever the daemon gives them. An embedded SPV node doesn’t have that luxury — it must understand the MWEB structure itself.
Each Litecoin block contains a HogEx (“Hogwarts Express”, the MWEB integration transaction) as its last entry. This transaction bridges the main UTXO set and the MWEB extension block. Our embedded node extracts the MWEB state (roots, MMR sizes, kernel/stealth offsets) from each full block received via P2P and carries it forward when building the next template. The MWEB block hash uses blake3, matching Litecoin Core’s libmw.
We use a carry-forward approach: extract state from the previous block, construct an empty MWEB block plus HogEx transaction for the next one. Since we don’t process MWEB transactions ourselves (no confidential transaction support), the extension block is always empty. This has the disadvantage that MWEB-only transactions are not included in our block templates. But the HogEx must be structurally valid or Litecoin nodes reject the block, so getting the carry-forward right was not optional.
Update, November 2026. With a local litecoind, c2pool can now put litecoind’s MWEB extension block into its template (--ltc-mweb-ext litecoind), after checking it against its own MWEB state. The default, and the daemonless node, still use an empty extension block.
The OOM crash: 10 GB in 100 seconds
The production node crashed silently. No crash log, no backtrace. An external watchdog thread detected the event loop freeze, but the kernel’s OOM killer was faster.
Root cause: a data race between the IO thread and the compute thread. The PPLNS walk followed a dangling pointer during share pruning. RSS went from 1.4 GB to 11.3 GB in 100 seconds as the corrupted walk allocated unbounded temporary structures.
The fix was shared_lock on all IO-thread tracker callbacks. The lesson was that in a system where two threads access the same graph structure, the failure mode isn’t a wrong answer — it’s exponential memory consumption from a corrupted traversal.
Making the sharechain visible
Decentralized mining has a verification problem: how does a miner know the pool is paying them fairly? The math is verifiable, but raw share hashes and chain lengths mean nothing to a working miner.
The idea was that a miner should be able to verify their own payout in a few seconds.
The main view is a canvas-rendered pixel grid showing all 8,640 shares in the PPLNS window. Each share is a colored square — the layout is borrowed from the Windows Disk Defragmenter visualization that made disk health immediately comprehensible. Color maps to miner identity (deterministic HSL from address), brightness indicates verified or unverified status, gold borders mark block solutions. When new shares arrive via SSE, old shares scroll off one end and new ones appear at the other.
Below the grid, a squarified treemap shows the current payout distribution. Each cell is sized proportionally to a miner’s PPLNS weight. Large cells show address, percentages, hashrate, V36 status. Small cells show just the percentage. V35-only miners appear desaturated with a “NO DOGE” label — they do not receive merged mining rewards.
Each share is clickable. The individual share page shows the share’s technical details (hash, miner, difficulty, version, timestamp, coinbase tag) and the full PPLNS treemap at that share’s position — who would have been paid what if a block had been found at that exact moment. This makes it possible to trace payout changes share by share through the transition window. Anyone running their own node sees the same data independently — the dashboard is a local view of the sharechain, not a hosted service.
We kept the classical p2pool stats that miners expect (hashrate, share counts, peer connections, uptime) and added luck computation and deviation tracking back to the dashboard. Luck over a period is the number of blocks found divided by the number expected. It tends to confuse people when presented without context, but it is one of the better ways to verify that the pool is performing within statistical bounds and that the PPLNS distribution is fair over time.
Update, November 2026. The first version of this paragraph had the ratio upside down (expected divided by actual). Since v0.2.12.9 the dashboard computes luck from effort, with a 95% interval for each period; see how the dashboard measures luck.
The V36 transition progress appears as a live progress bar: percentage of shares signaling V36, the 95% activation threshold, the ratchet state progression. It uses SSE push, so open connections do not add load to the node.
Cross-implementation testing
We did not find these bugs with unit tests. Unit tests verify that your implementation is internally consistent. They do not tell you whether it matches the consensus of a different implementation running the same protocol.
Our test methodology: two p2pool nodes and one c2pool node on an isolated Litecoin testnet, with three Scrypt ASIC miners (one per node). Every share propagates to all three nodes. Every GENTX mismatch is logged with both implementations’ outputs side by side. We compare per-share PPLNS weights, coinbase outputs, difficulty targets.
The Dogecoin side required its own infrastructure. The public DOGE testnet has a block storm bug — difficulty collapsed to the point where blocks arrive at roughly 3.3 per second, making it unusable for any testing that depends on realistic timing. We forked the Dogecoin daemon and created an isolated testnet (testnet4alpha) with AuxPoW enabled from genesis, sane difficulty, and controlled peer connections. This is not public; it runs only between our test machines. We bundled a lightweight blockchain explorer with c2pool specifically to inspect this private chain: decode coinbase scripts, trace PPLNS payouts, verify AuxPoW commitments, check which blocks were found by which pool. It was a development tool before it was a feature.
A typical test run goes through predictable phases: V35 healthy operation (shares 0–800, PPLNS climbing to expected 33%), V36 boundary entry (shares 800–950, where the activation boundary enters the PPLNS window), and sustained mixed-mode operation. The V36 boundary is where every consensus bug surfaces. It is reproducible.
We built a full restart procedure that kills all nodes, flushes all data, clears daemon bans, starts p2pool with a head start (20 shares of solo operation), then introduces c2pool. The monitoring script tracks PPLNS percentage, GENTX failures, topology (head count, chain length), and template match (coinbasevalue comparison between nodes) at per-share granularity.
It turns out that running a second implementation on the same share chain is one of the more reliable ways to find consensus bugs. Both implementations agree on the same data, or they don’t. There is no ambiguity.
Open questions
A few things we keep thinking about.
Is PPLNS necessarily single-temporal? The current system — whether flat (V35) or exponentially decayed (V36) — looks at one time dimension. All shares in the window are weighted by their position relative to the tip. But the difficulty adjustment already creates natural epoch boundaries (every 2016 blocks on Bitcoin and Litecoin; at every block on Dogecoin since DigiShield). A share that exceeds the current difficulty target by a wide margin represents more entropy than one that barely passes. The current system treats them identically. It is an open question whether shares could carry weight across epoch boundaries — credited to the epoch their difficulty actually corresponds to rather than the one they happened to arrive in. The settlement mechanics when epochs collapse get complicated quickly, but the pool-hopping resistance properties are interesting.
Does decentralized mining need a terminal? We’ve been experimenting with a Qt-based desktop interface that wraps the full embedded node — launch page, overview, mining status, sharechain visualizer, log viewer, settings. A self-contained application with no daemon dependencies and no configuration files. Whether this actually makes decentralized mining more accessible or just adds a layer of abstraction is something we don’t know yet.
Update, November 2026. The c2pool repository now contains two Qt applications under ui/: c2pool-qt, and c2wallet-qt, which includes an offline signer built with no network code.
How chain-specific is the architecture? The embedded SPV and PPLNS machinery don’t assume Litecoin. They work with any Scrypt chain. DigiByte is an obvious candidate — another Scrypt chain that could run as a second independent sharechain with its own merged mining. The share format is the same. The chain-specific parts (difficulty adjustment algorithm, block timing, address version bytes) are parameterized. We tested it on testnet. Whether there is enough DGB mining hashrate to sustain a decentralized pool is a separate question.
Update, November 2026. A DigiByte node now runs live on mainnet with no coin daemon (c2pool-dgb). It mines DigiByte’s Scrypt algorithm as a parent chain of its own, not as a child of Litecoin, and it has no testnet mode.
We’ve been running it on mainnet alongside p2pool v36 nodes. The share chains stay in sync. There are still rough edges.
Update, November 2026. Since the share version 3601 flag day (2026-11-13), Python p2pool is no longer on the Litecoin share chain; only c2pool v0.2.12.1 and later are. The Python implementations are no longer maintained.
The open questions above are the seed of V37, the next design line in c2pool. “Is PPLNS necessarily single-temporal?” became the multi-temporal MRR roundabout buffer: work credited to the origin-time bin it was done in, not the position at which it arrived. The wide-margin observation became the rule that work is credited by the target it met, never by how far below that target a hash happened to fall (see Real difficulty). “How chain-specific is the architecture?” became native multichain lanes. The hard-won lessons documented here (replay, not reconstruct; verify each share by its own version; bit-exact fixed point; find bugs with a second implementation) are the foundation the V37 design builds on. V37 is at the design and prototype stage and is not run in production. See the Purple Paper summary.